harec

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

04-strings.ha (1673B)


      1 fn measurements() void = {
      2 	const x = "Hello!";
      3 	assert(len(x) == 6);
      4 	assert(len("Hello!") == 6);
      5 	assert(len("Hello!\0") == 7);
      6 	assert(len("He\0llo!") == 7);
      7 	assert(size(str) == size(*u8) + size(size) * 2);
      8 	const alignment: size =
      9 		if (size(*u8) > size(size)) size(*u8)
     10 		else size(size);
     11 	assert(align(str) % alignment == 0);
     12 
     13 	static assert(len("Hello!") == 6);
     14 };
     15 
     16 fn storage() void = {
     17 	const string = "こんにちは";
     18 	const ptr = &string: *struct {
     19 		data: *[*]u8,
     20 		length: size,
     21 		capacity: size,
     22 	};
     23 	assert(ptr.length == 15 && ptr.capacity == 15);
     24 
     25 	// UTF-8 encoded
     26 	const expected: [_]u8 = [
     27 		0xE3, 0x81, 0x93, 0xE3, 0x82, 0x93, 0xE3, 0x81,
     28 		0xAB, 0xE3, 0x81, 0xA1, 0xE3, 0x81, 0xAF,
     29 	];
     30 	for (let i = 0z; i < len(expected); i += 1) {
     31 		assert(ptr.data[i] == expected[i]);
     32 	};
     33 
     34 	const empty = "";
     35 	const ptr2 = &empty: *struct {
     36 		data: nullable *[*]u8,
     37 		length: size,
     38 		capacity: size,
     39 	};
     40 	assert(ptr2.data == null);
     41 };
     42 
     43 fn concat() void = {
     44 	const s = "Hell" "o, " "wor" "ld!";
     45 	const t = *(&s: **[*]u8);
     46 	const expected = [
     47 		'H', 'e', 'l', 'l', 'o', ',', ' ',
     48 		'w', 'o', 'r', 'l', 'd', '!',
     49 	];
     50 	for (let i = 0z; i < len(expected); i += 1) {
     51 		assert(t[i] == expected[i]: u32: u8);
     52 	};
     53 };
     54 
     55 fn equality() void = {
     56 	assert("foo" != "bar");
     57 	assert("foo" != "foobar");
     58 	assert("foobar" == "foobar");
     59 	assert("foo\0bar" != "foo\0foo");
     60 	static assert("foo" != "bar");
     61 	static assert("foo" != "foobar");
     62 	static assert("foobar" == "foobar");
     63 	static assert("foo\0bar" != "foo\0foo");
     64 };
     65 
     66 fn raw() void = {
     67 	assert(`hello \" world` == "hello \\\" world");
     68 };
     69 
     70 export fn main() void = {
     71 	measurements();
     72 	storage();
     73 	concat();
     74 	equality();
     75 	raw();
     76 };