Files
sakurac/tests/programs/constants_view_other_constants_1.sakura
2026-11-19 04:54:17 -06:00

61 lines
2.0 KiB
Plaintext

import std::io;
# A constant holds views of another constant's array, which it shares rather
# than copies: a view of a view, views within a struct and within memory the
# constant allocated, an empty view at the array's end, and a reference to an
# element.
const primes: u64[5] = [2, 3, 5, 7, 11];
const all: span<u64> = primes[:];
const middle: span<u64> = primes[1:3];
const inner: span<u64> = rest(middle);
const none: span<u64> = primes[5:0];
const largest: &u64 = &primes[4];
const words: strview[3] = ["one", "two", "three"];
const later: span<strview> = words[1:];
struct table {
var name: strview;
var rows: span<u64>;
}
const odd: table = table{ name = "odd", rows = primes[1:] };
def rest(of: span<u64>): span<u64> {
return of.sub(1, of.length - 1) else { return of; };
}
def halves(): span<span<u64>> {
val made := raw_allocate(2 * size_of::<span<u64>>()) as *mut span<u64>;
made[0] = primes[0:2];
made[1] = primes[2:3];
return span::<span<u64>>::over(made as *span<u64>, 2);
}
const split: span<span<u64>> = halves();
def sum(of: span<u64>): u64 {
var total := 0u;
for each in of { total += each; }
return total;
}
def main(): void {
println($"{all.length} {sum(all)} {middle[0]} {middle[2]} {inner[0]} {inner.length} {none.length}");
println($"{later[0]} {later[1]} {later.length}");
println($"{odd.name} {odd.rows.length} {sum(odd.rows)}");
println($"{split.length} {sum(split[0])} {sum(split[1])}");
# The views are of the array itself, not of copies of it.
println($"{all.data == primes[:].data} {inner.data == primes[2:].data} {split[1].data == primes[2:].data} {none.data == primes[5:0].data}");
# A reference to an element, as a constant and as the program runs, is to
# the element where the array is.
val held: &u64 = &primes[4];
println($"{largest} {(largest as *u64) == all.data + 4} {(held as *u64) == all.data + 4}");
# A local constant views a global one.
const first: span<u64> = primes[1:2];
println($"{sum(first)} {first.data == all.data + 1}");
}