Landin library reference discuss source

core/mem/bytes.ldn

1--  The full allocation extent stays private beside the initialized witness.
2--  Borrowed byte views do not replace that allocation identity.
3buffer: type = struct
4    values: storage(u8)
5    extent: usize
6end buffer
7--- Opaque descriptor for an initialized byte allocation, retaining its full
8--- allocation extent.
9public byte_buffer: type = buffer
10
11--- Lend the buffer's mutable initialized bytes. The buffer must remain
12--- allocated while the view is used.
13public bytes: (source: byte_buffer) -> (view: []mut u8 from source) =
14    view = used(source.values)
15end bytes
16
17--- Allocate `count` zero-initialized bytes. A zero count returns an empty
18--- buffer without calling the provider; allocation failure reports
19--- `out_of_memory`.
20public allocate_bytes: (provider: type is allocator, memory: provider,
21                        count: usize)
22                       -> (result: byte_buffer) ! out_of_memory =
23    zero: usize = 0
24    if count == 0 then
25        none_yet := empty_storage(item: u8)
26        result = (values: none_yet, extent: zero)
27        return
28    end if
29    block: ptr mut u8 = try provider.alloc(memory, count, alignof u8)
30    --  Zero all `count` bytes the provider returned, a word at a time,
31    --  before the prefix claims them.
32    first: ptr mut [1]u8 = ptr(usize(block))
33    mut zeroes: []mut u8 = first.val[0..<1]
34    unchecked begin
35        --  The provider's block holds `count` bytes.
36        zeroes = zeroes[0..<count]
37    end unchecked
38    fill(zeroes, 0)
39    mut fresh := storage_over(item: u8, base: block, slots: count)
40    initial: u8 = 0
41    admitted: usize = admit(fresh, initial) else (problem)
42        --  Refusal is unreachable for this private state. If it occurs,
43        --  release the saved allocation without trusting damaged counts.
44        _ = problem
45        provider.free(memory, block, count)
46        fail out_of_memory
47    end
48    _ = admitted
49    unchecked begin
50        --  Every one of the `count` slots now holds a zero.
51        fresh.prefix = fresh.prefix[0..<count]
52    end unchecked
53    result = (values: fresh, extent: count)
54end allocate_bytes
55
56--- Free the buffer using its saved extent and reset it. Empty buffers require
57--- no provider call. End all byte views before deletion.
58public release_bytes: (provider: type is allocator, memory: provider,
59                       inout value: byte_buffer) -> none =
60    return when value.extent == 0
61    extent: usize = value.extent
62    clear(value.values)
63    block: ptr mut u8 = detach(value.values) else (problem)
64        _ = problem
65        return
66    end
67    value.extent = 0
68    provider.free(memory, block, extent)
69end release_bytes