hare

[hare] The Hare programming language
git clone https://git.torresjrjr.com/hare.git
Log | Files | Refs | README | LICENSE

ensure.ha (914B)


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