interpret/src/pair.c

60 lines
1.4 KiB
C

/** @license 2023 Neil Edelman, distributed under the terms of the
[MIT License](https://opensource.org/licenses/MIT).
A `pair` is `[a, b)` pair of pointers to char.
@std C99 */
#include "pair.h"
#include <stdint.h>
#include <errno.h>
#include <assert.h>
/** @return Constructs `a` and `b` as a pair. */
struct pair pair(const char *const a, const char *const b) {
struct pair p;
p.a = a, p.b = b;
return p;
}
/** Doesn't check anything.
@return Whether it was able to parse unsigned `p` to `n`. */
int pair_to_natural(const char *s, const char *const e, uint32_t *const n) {
uint32_t accum = 0;
while(s < e) {
unsigned next = accum * 10 + (unsigned)(*s - '0');
if(accum >= next) return errno = ERANGE, 0;
accum = next;
s++;
}
*n = accum;
return 1;
}
int pair_is_equal(struct pair x, struct pair y) {
assert(x.a <= x.b && y.a <= y.b);
if(!x.a) return !y.a;
if(!y.a) return 0;
if(x.b - x.a != y.b - y.a) return 0;
while(x.a < x.b) { if(*x.a != *y.a) return 0; x.a++, y.a++; }
return 1;
}
int pair_is_string(struct pair x, const char *y) {
assert(x.a <= x.b);
if(!x.a) return !y;
if(!y) return 0;
while(x.a < x.b) { if(*x.a != *y || !*y) return 0; x.a++, y++; }
return !*y;
}
/** djb2 <http://www.cse.yorku.ca/~oz/hash.html> */
uint32_t pair_djb2(struct pair p) {
uint32_t hash = 5381, c;
while(p.a < p.b) {
c = (unsigned char)*p.a++;
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
}
return hash;
}