hare

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

ensure.ha (943B)


      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) bool = {
     11 	let cap = s.capacity;
     12 	if (cap >= s.length) {
     13 		return true;
     14 	};
     15 	for (cap < s.length) {
     16 		assert(cap >= s.capacity, "slice out of memory (overflow)");
     17 		if (cap == 0) {
     18 			cap = s.length;
     19 		} else {
     20 			cap *= 2;
     21 		};
     22 	};
     23 	s.capacity = cap;
     24 	let data = realloc(s.data, s.capacity * membsz);
     25 	if (data == null) {
     26 		if (s.capacity * membsz == 0) {
     27 			s.data = null;
     28 			return true;
     29 		} else {
     30 			return false;
     31 		};
     32 	};
     33 	s.data = data;
     34 	return true;
     35 };
     36 
     37 export fn unensure(s: *slice, membsz: size) void = {
     38 	let cap = s.capacity;
     39 	for (cap > s.length) {
     40 		cap /= 2;
     41 	};
     42 	cap *= 2;
     43 	s.capacity = cap;
     44 	let data = realloc(s.data, s.capacity * membsz);
     45 
     46 	if (data != null || s.capacity * membsz == 0) {
     47 		s.data = data;
     48 	};
     49 };