This is a minor refactor to use `for´ loops instead of `while´ ones
when parsing subpaths, and to condition exiting the second loop on
filling the array, rather than on reaching the end of the string. If
there is a bug in the code which causes the array to be too small, this
will simply clip the result rather than try to assign to out‐of‐bounds
memory. If there is a bug in the code which causes the array to be too
big, the program will loop endlessly rather than fail an `assert()´
check. The improvement in the first case is deemed to justify the
slight degradation of behaviour in the second.
// The portion of the pathinfo which follows the third slash is the
// subpath of the request. An empty sting is equivalent to having no
// subpath. Trailing and successive slashes are dropped.
// The portion of the pathinfo which follows the third slash is the
// subpath of the request. An empty sting is equivalent to having no
// subpath. Trailing and successive slashes are dropped.
- char const* sos = ndx[0];
char const* sep = nullptr;
size_t n·s = 0;
char const* sep = nullptr;
size_t n·s = 0;
+ for (
+ char const* sos = ndx[0];
+ sos < end[0];
+ sos = (end[0] > sep ? sep + 1 : end[0])
+ ) {
// Count the number of segments in the pathinfo so that the correct
// amount of space can be allocated.
sep = strchr(sos, '/');
// Count the number of segments in the pathinfo so that the correct
// amount of space can be allocated.
sep = strchr(sos, '/');
if (sep > sos) {
++n·s;
}
if (sep > sos) {
++n·s;
}
- if (end[0] > sep) {
- sos = sep + 1;
- } else {
- sos = end[0];
- }
- }
- req.subpath = calloc(n·s + 1, sizeof(char*));
- if (!req.subpath) {
- return req;
- size_t i·s = 0;
- while (end[0] > ndx[0]) {
- // Add the segments to the newly allocated array.
- sep = strchr(ndx[0], '/');
- if (!sep) {
- sep = end[0];
+ if (n·s > 0) {
+ req.subpath = calloc(n·s + 1, sizeof(char*));
+ if (!req.subpath) {
+ return req;
- if (sep > ndx[0]) {
- req.subpath[i·s++] = strndup(ndx[0], sep - ndx[0]);
- }
- if (end[0] > sep) {
- ndx[0] = sep + 1;
- } else {
- ndx[0] = end[0];
+ for (
+ size_t i·s = 0;
+ i·s < n·s;
+ ndx[0] = (end[0] > sep ? sep + 1 : end[0])
+ ) {
+ // Add the segments to the newly allocated array.
+ sep = strchr(ndx[0], '/');
+ if (!sep) {
+ sep = end[0];
+ }
+ if (sep > ndx[0]) {
+ req.subpath[i·s++] = strndup(ndx[0], sep - ndx[0]);
+ }
+ req.subpath[n·s] = nullptr;
- assert(i·s == n·s);
- req.subpath[i·s] = nullptr;
// Return the result.
return req;
// Return the result.
return req;