From ac4cc8feaaef747295b8705fa7f1b6d43d72f4dd Mon Sep 17 00:00:00 2001 From: Jose Marcial Vieira Bisneto Date: Sat, 26 Nov 2016 10:39:53 -0300 Subject: [PATCH] path/path.c: Implemented SplitN. Renamed Segments() to SplitN(), added parameters, and created a new Segments() using SplitN() while maintaining the original functionality. --- include/ipfs/path/path.h | 1 + path/path.c | 52 +++++++++++++++++++++++++++++----------- 2 files changed, 39 insertions(+), 14 deletions(-) diff --git a/include/ipfs/path/path.h b/include/ipfs/path/path.h index 0116ed2..a305938 100644 --- a/include/ipfs/path/path.h +++ b/include/ipfs/path/path.h @@ -21,6 +21,7 @@ } PathErrs; char* PathFromCid (struct Cid *c); + char** SplitN (char *p, char *delim, int n); char** Segments (char *p); int SegmentsLength (char **s); void FreeSegments (char ***s); diff --git a/path/path.c b/path/path.c index d3f9fe7..75b71b7 100644 --- a/path/path.c +++ b/path/path.c @@ -16,32 +16,56 @@ char* PathFromCid (struct Cid *c) return rpath; } -char** Segments (char *p) +char** SplitN (char *p, char *delim, int n) { - int slash_count, i; - char *c, **rsegs, *rbuf; + char *c, **r, *rbuf; + int i, dlen = strlen(delim); - if (*p == '/') p++; // Ignore leading slash - - for (c = p , slash_count = 0 ; *c ; c++) { - if (*c == '/') slash_count++; + if (n == 0) { + return NULL; // no split? } - if (!slash_count) return NULL; + if (n < 0) { // negative, count all delimiters + 1. + for (c = p , n = 0 ; c ; n++) { + c = strstr(c, delim); + if (c) { + c += dlen; + } + } + } else { + n++; // increment param value. + } rbuf = malloc(strlen(p) + 1); - if (!rbuf) return NULL; + if (!rbuf) { + return NULL; + } - rsegs = calloc(sizeof(char*), slash_count + 2); // slashs splits plus NULL pointer termination - if (!rsegs) { - free(rbuf); + r = calloc(sizeof(char*), n + 1); // splits plus NULL pointer termination + if (!r) { + free(r); return NULL; } strcpy(rbuf, p); // keep original - for (rsegs[0] = strtok(rbuf, "/"), i = 0 ; (rsegs[i] = strtok(NULL, "/")) ; i++); + for (c = rbuf, i = 0 ; i < n && c ; i++) { + r[i] = c; + c = strstr(c, delim); + if (c) { + *c = '\0'; + c += dlen; + } + } + r[i] = NULL; - return rsegs; + return r; +} + +char** Segments (char *p) +{ + if (*p == '/') p++; // Ignore leading slash + + return SplitN (p, "/", -1); } // Count Segments