Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //vfs.h
- #define isdot(x) (x == '.')
- #define isfndelim(x) ((x == '/') || (x == 0))
- //vfs.c
- char* vfs_path_compose(char* path, char* buf, uint16_t size) {
- char* bufstart = buf;
- char* bufend;
- char* csource;
- uint8_t copyStage;
- char oldchar;
- if (path[0] == '/') {
- return path;
- }
- //Don't copy, get the pointer directly
- csource = vfs_getcwd(NULL, 0);
- //cwd may not be a relative path...
- if (csource[0] != '/') {
- return NULL;
- }
- copyStage = 0;
- bufend = (char*)((uint16_t)buf + size - 1);
- //Add a slash to begin with (and check for buffer size >= 1)
- if (buf >= bufend) {
- return NULL;
- }
- *buf++ = '/';
- *buf = 0;
- while (1) {
- //Skip over any leading slashes in the source
- while (csource[0] == '/') {
- csource++;
- }
- if (isdot(csource[0]) && isfndelim(csource[1])) {
- //That's a change to "dot", do nothing but advancing forward
- //Skip over the dot
- csource += 1;
- } else if (isdot(csource[0]) && isdot(csource[1]) && isfndelim(csource[2])) {
- //That's a change to "dot-dot", go one directory upward
- //Skip over dot-dot
- csource += 2;
- //Remove any slashes at the end
- while (*(buf - 1) == '/') {
- if ((uint16_t)buf <= (uint16_t)bufstart) {
- return NULL;
- }
- buf--;
- *buf = 0;
- }
- //Remove the last directory
- do {
- if ((uint16_t)buf <= (uint16_t)bufstart) {
- return NULL;
- }
- buf--;
- oldchar = *buf;
- *buf = 0;
- } while (oldchar != '/');
- *buf++ = '/'; //Add the slash at the end
- *buf = 0;
- } else if (csource[0] == 0) {
- //End of source string reached.
- //Switch to next string if there's another string left,
- //finish operation if there's nothing left
- if (copyStage == 0) {
- csource = path;
- copyStage = 1;
- } else {
- break;
- }
- } else {
- //Normal directory, just copy
- //Just in case there's no slash at the end of the buffer
- if (*(buf - 1) != '/') {
- if (buf == bufend) {
- //Overflow...
- return NULL;
- }
- *buf++ = '/';
- *buf = 0;
- }
- //Copy up to (not including) the next slash or string end
- while (!isfndelim(csource[0])) {
- if (buf == bufend) {
- return NULL;
- }
- *buf++ = *csource++;
- *buf = 0;
- }
- //Add a slash at the end of the buffer
- if (buf == bufend) {
- return NULL;
- }
- *buf++ = '/';
- *buf = 0;
- }
- }
- return bufstart;
- }
Advertisement
Add Comment
Please, Sign In to add comment