harec

[hare] Hare compiler, written in C11 for POSIX OSs
Log | Files | Refs | README | LICENSE

ensure.ha (767B)


      1 export type slice = struct {
      2 	data: nullable *void,
      3 	length: size,
      4 	capacity: size,
      5 };
      6 
      7 export fn ensure(s: *slice, membsz: size) void = {
      8 	let cap = s.capacity;
      9 	if (cap >= s.length) {
     10 		return;
     11 	};
     12 	for (cap < s.length) {
     13 		assert(cap >= s.capacity, "slice out of memory (overflow)");
     14 		if (cap == 0) {
     15 			cap = s.length;
     16 		} else {
     17 			cap *= 2;
     18 		};
     19 	};
     20 	s.capacity = cap;
     21 	const data = realloc(s.data, s.capacity * membsz);
     22 	assert(data != null || s.capacity * membsz == 0);
     23 	s.data = data;
     24 };
     25 
     26 export fn unensure(s: *slice, membsz: size) void = {
     27 	let cap = s.capacity;
     28 	for (cap > s.length) {
     29 		cap /= 2;
     30 	};
     31 	cap *= 2;
     32 	s.capacity = cap;
     33 	const data = realloc(s.data, s.capacity * membsz);
     34 	assert(data != null || s.capacity * membsz == 0);
     35 	s.data = data;
     36 };