1-- Honest typed storage. The representation stays module-internal: callers
2-- can hold a storage(T), but only these operations can expose a value
3-- or change the initialized-prefix count.
4
5--- The index is outside the initialized prefix.
6---
7--- This atom and `empty` are the two every core container fails with. An
8--- index past the initialized prefix is `out_of_bounds` whether the
9--- container is raw storage, a vector, a spill list or a bounded log;
10--- taking from a container with nothing to take is `empty`. A key lookup
11--- that finds nothing fails `not_found`, because a missing key is not a
12--- bad index.
13public out_of_bounds: atom
14--- No initialized item or backing allocation is available for this operation.
15public empty: atom
16--- The operation requires storage with an empty initialized prefix.
17public not_empty: atom
18
19no_storage: atom
20allocation: type = no_storage | ptr mut u8
21
22raw: type (item: type) = struct
23 base: allocation
24 capacity_count: usize
25 prefix: []mut item
26end raw
27
28--- Opaque typed storage over caller-owned backing. Tracks capacity and an
29--- initialized prefix; it does not own an allocator or prove the backing
30--- lifetime.
31---
32--- The alias is the opaque name other core modules can put in fields and
33--- signatures. It still normalizes to raw(item), whose private declaration
34--- keeps the representation inaccessible outside this module.
35public storage: type (item: type) = raw(item)
36--- The provider cannot satisfy the size or alignment request, or its
37--- arithmetic cannot represent the extent.
38public out_of_memory: atom
39--- The sought key, node, file, argument, variable, text or symbol is not
40--- there: what every library lookup that finds nothing fails with (D2028).
41public not_found: atom
42
43--- Explicit allocation capability, given by a handle: a small copyable
44--- value passed by value that refers to its provider's state. Free each
45--- successful block once through the provider that allocated it, with its
46--- current byte extent. Keep the provider's state and backing alive until all
47--- uses end. Alignment zero or one means byte alignment; zero-byte requests
48--- follow the provider's documented policy.
49public allocator: type = concept (provider: type)
50 --- Allocate the requested byte extent or report out_of_memory. Return
51 --- backing valid until the matching free; honor the requested alignment.
52 alloc: (self: provider, size: usize, alignment: usize)
53 -> (block: ptr mut u8) ! out_of_memory
54 --- Extend this same block in place. Return false without changing the
55 --- block or provider state when extension is refused.
56 grow: (self: provider, block: ptr mut u8,
57 old_size: usize, new_size: usize, alignment: usize)
58 -> (grown: bool)
59 --- Give a successful block a new byte extent, larger or smaller, in place
60 --- or by moving it, and return where it now is. Its first
61 --- min(old_size, new_size) bytes are the ones it held, it honors the same
62 --- alignment, and it is freed with `new_size`; a moved block's old
63 --- address is given back and is not used again. Report out_of_memory
64 --- with the block and provider unchanged when there is no room for it.
65 --- A provider that cannot resize in place answers with `relocate`; one
66 --- that can grows in place here first, since a container grows its
67 --- storage through `resize` alone.
68 resize: (self: provider, block: ptr mut u8,
69 old_size: usize, new_size: usize, alignment: usize)
70 -> (moved: ptr mut u8) ! out_of_memory
71 --- Return a successful block with its current extent. The caller ends all
72 --- uses first and must use the original provider.
73 free: (self: provider, block: ptr mut u8, size: usize) -> none
74end allocator
75
76--- Request a byte extent with the supplied alignment through the provider.
77--- Propagates `out_of_memory`; the caller owns the resulting allocation
78--- obligation.
79public allocate: (provider: type is allocator, memory: provider,
80 size: usize, alignment: usize)
81 -> (block: ptr mut u8) ! out_of_memory =
82 block = try provider.alloc(memory, size, alignment)
83end allocate
84
85--- Grow a block of `old_size` bytes to `new_size` where it is, through the
86--- provider. Returns true when the block grew; free it with `new_size` from
87--- then on. Returns false, with nothing changed, when the provider refuses,
88--- as any provider may.
89public grow: (provider: type is allocator, memory: provider,
90 block: ptr mut u8, old_size: usize, new_size: usize,
91 alignment: usize) -> (grown: bool) =
92 grown = provider.grow(memory, block, old_size, new_size, alignment)
93end grow
94
95--- Give a block of `old_size` bytes the extent `new_size` through the
96--- provider, which may move it: the result holds the block's first
97--- min(old_size, new_size) bytes and is freed with `new_size`. Propagates
98--- `out_of_memory`, after which the old block is still the caller's.
99public resize: (provider: type is allocator, memory: provider,
100 block: ptr mut u8, old_size: usize, new_size: usize,
101 alignment: usize)
102 -> (moved: ptr mut u8) ! out_of_memory =
103 moved = try provider.resize(memory, block, old_size, new_size, alignment)
104end resize
105
106-- A writable view of `size` bytes at `block`, which a provider returned.
107-- The block borrows nothing [0810], so neither does the view.
108block_bytes: (block: ptr mut u8, size: usize) -> (view: []mut u8) =
109 view = []
110 return when size == 0
111 first: ptr mut [1]u8 = ptr(usize(block))
112 view = first.val[0..<1]
113 unchecked begin
114 -- The provider's block holds `size` bytes, at least one.
115 view = view[0..<size]
116 end unchecked
117end block_bytes
118
119--- Resize by moving, the `resize` of a provider that cannot resize in
120--- place: allocate `new_size` bytes with `alignment`, copy the first
121--- min(old_size, new_size) bytes there and free the old block with
122--- `old_size`. A refused allocation reports `out_of_memory` with the old
123--- block untouched. A provider's own `resize` entry calls it once any
124--- in-place change it can make has been refused.
125public relocate: (provider: type is allocator, memory: provider,
126 block: ptr mut u8, old_size: usize, new_size: usize,
127 alignment: usize)
128 -> (moved: ptr mut u8) ! out_of_memory =
129 moved = try provider.alloc(memory, new_size, alignment)
130 kept: usize = if new_size < old_size then new_size else old_size end if
131 -- Two live blocks of at least `kept` bytes: the copy always fits.
132 into: []mut u8 = block_bytes(moved, kept)
133 copy(into, block_bytes(block, kept)) else none
134 provider.free(memory, block, old_size)
135end relocate
136
137--- Return a block to its provider using the allocation's current extent. The
138--- caller must end all uses first; no item cleanup runs.
139public release: (provider: type is allocator, memory: provider,
140 block: ptr mut u8, size: usize) -> none =
141 provider.free(memory, block, size)
142end release
143
144--- Create an empty descriptor without allocating backing.
145---
146--- A descriptor without an allocation is not a zero-address allocation.
147--- It owns no extent, admits no item and cannot yield a pointer on disposal.
148public empty_storage: (item: type) -> (store: storage(item)) =
149 prefix: []mut item = []
150 store = (base: no_storage, capacity_count: 0, prefix: prefix)
151end empty_storage
152
153--- Describe `slots` items over an existing byte range without allocating or
154--- initializing items. The caller supplies sufficient, correctly aligned
155--- backing and keeps it alive; the extent multiplication must be
156--- representable.
157public storage_over: (item: type, base: ptr mut u8, slots: usize)
158 -> (result: storage(item) from base) =
159 prefix: []mut item = []
160 result = (base: base, capacity_count: slots, prefix: prefix)
161end storage_over
162
163--- Return the bytes `slots` items take: zero for a zero-sized item, which
164--- still has its slots. Reports `out_of_memory` when they do not fit `usize`.
165public storage_extent: (item: type, slots: usize)
166 -> (extent: usize) ! out_of_memory =
167 size: usize = sizeof item
168 extent = 0
169 return when size == 0
170 maximum: usize = 0 -% 1
171 fail out_of_memory when slots > maximum / size
172 extent = slots * size
173end storage_extent
174
175--- Give a storage's block back through the provider that gave it, first
176--- discarding its initialized prefix without reading it, and leave it with
177--- no storage. Release what the items refer to first: nothing here does.
178public release_storage: (item: type, provider: type is allocator,
179 inout store: storage(item), memory: provider)
180 -> none =
181 clear(store)
182 slots: usize = capacity(store)
183 return when slots == 0
184 -- Every capacity a storage reaches through `reserve_storage` passed
185 -- `storage_extent`, so this product is representable.
186 extent: usize = slots * sizeof item
187 block: ptr mut u8 = detach(store) else (problem)
188 _ = problem
189 return
190 end
191 provider.free(memory, block, extent)
192end release_storage
193
194-- Grow a storage that holds a block of `old_extent` bytes to `slots`
195-- items, `extent` bytes, through the provider's `resize`, which grows it
196-- in place or moves it, a large block's pages where it can: the block's
197-- first `old_extent` bytes, the prefix among them, are where the result
198-- is. `out_of_memory` leaves the storage as it was; a storage with a
199-- positive extent holds a block, so its absence is never the reason.
200resize_storage: (item: type, provider: type is allocator,
201 inout store: storage(item), memory: provider,
202 old_extent: usize, extent: usize, slots: usize)
203 -> none ! out_of_memory =
204 count: usize = length(store)
205 match store.base
206 no_storage: fail out_of_memory
207 ptr (base): begin
208 moved: ptr mut u8 = try provider.resize(memory, base, old_extent,
209 extent, alignof item)
210 store.base = moved
211 store.capacity_count = slots
212 first: ptr mut [1]item = ptr(usize(moved))
213 mut kept: []mut item = first.val[0..<1]
214 unchecked begin
215 -- The block holds `slots` items, at least `count` and at
216 -- least one, and its first `count` are the prefix's.
217 kept = kept[0..<count]
218 end unchecked
219 store.prefix = kept
220 end
221 end match
222end resize_storage
223
224-- The address of a storage's block, or zero when it holds none.
225start_of: (item: type, store: storage(item)) -> (address: usize) =
226 address = 0
227 match store.base
228 no_storage: return
229 ptr (base): address = usize(base)
230 end match
231end start_of
232
233-- The containers' one way of taking slots: spec.md's D356.
234--- Make room for at least `want` items, keeping the initialized prefix.
235--- A storage with a block asks the provider to `resize` it, which grows it
236--- in place or moves it; one without, or whose items have no size, takes a
237--- fresh block, the prefix copied into it and the old one freed. A move
238--- invalidates views of the old block. `out_of_memory` leaves the
239--- storage, its prefix and its capacity as they were. This is the
240--- containers' one way of taking slots.
241public reserve_storage: (item: type, provider: type is allocator,
242 inout store: storage(item), memory: provider,
243 want: usize) -> none ! out_of_memory =
244 old_count: usize = length(store)
245 old_capacity: usize = capacity(store)
246 return when want <= old_capacity
247 extent: usize = try storage_extent(item: item, slots: want)
248 old_extent: usize = old_capacity * sizeof item
249 if old_extent > 0 then
250 try resize_storage(store, memory, old_extent, extent, want)
251 return
252 end if
253 block: ptr mut u8 = try provider.alloc(memory, extent, alignof item)
254 mut fresh := storage_over(item: item, base: block, slots: want)
255 copy_prefix(fresh, store, old_count) else (problem)
256 -- An empty replacement larger than the old capacity takes every
257 -- item; were that invariant ever broken, roll back rather than
258 -- report a provider's exhaustion that did not happen.
259 _ = problem
260 release_storage(fresh, memory)
261 fail out_of_memory
262 end
263 release_storage(store, memory)
264 store = fresh
265end reserve_storage
266
267--- Copy `bytes` after a byte storage's initialized prefix and count them
268--- in it, as `admit_copy` does, first making room for `want` bytes in all
269--- as `reserve_storage` does when the storage holds fewer. `bytes` may be
270--- a view of the storage's own block (D1122): the block keeps its bytes
271--- when it grows or moves, so they are read where the block now is, and
272--- what is appended is what they held when the call began. A move
273--- invalidates views of the old block once the call has returned.
274--- `out_of_memory`, when the provider refuses or `want` bytes would not
275--- hold the prefix and `bytes`, leaves the storage, its prefix and its
276--- capacity as they were.
277public reserve_admit_copy: (provider: type is allocator,
278 inout store: storage(u8), memory: provider,
279 want: usize, bytes: []u8)
280 -> none ! out_of_memory =
281 old_count: usize = length(store)
282 old_capacity: usize = capacity(store)
283 slots: usize = if want > old_capacity then want else old_capacity end if
284 fail out_of_memory when lenof bytes > slots - old_count
285 mut source: []u8 = bytes
286 if slots > old_capacity then
287 old_start: usize = start_of(store)
288 try reserve_storage(store, memory, slots)
289 if old_capacity > 0 and lenof bytes > 0 then
290 at: usize = usize(addr bytes[0])
291 if at >= old_start and at - old_start < old_capacity then
292 -- `bytes` lay in the old block, whose first
293 -- `old_capacity` bytes the block now holds from its
294 -- start: read them there.
295 first: ptr mut [1]u8 = ptr(start_of(store) + (at - old_start))
296 mut moved: []mut u8 = first.val[0..<1]
297 unchecked begin
298 -- A view of the old block ends within its bytes.
299 moved = moved[0..<lenof bytes]
300 end unchecked
301 source = moved
302 end if
303 end if
304 end if
305 admit_copy(store, source) else (problem)
306 _ = problem
307 fail out_of_memory
308 end
309end reserve_admit_copy
310
311--- Return the logical slot capacity, including slots for zero-sized items.
312public capacity: (item: type, store: storage(item)) -> (count: usize) =
313 count = store.capacity_count
314end capacity
315
316--- Return the number of initialized items in the prefix.
317public length: (item: type, store: storage(item)) -> (count: usize) =
318 count = lenof store.prefix
319end length
320
321--- Lend a mutable slice of the initialized prefix. End uses of the view
322--- before invalidating or freeing its backing.
323public used: (item: type, store: storage(item))
324 -> (view: []mut item from store) =
325 view = store.prefix
326end used
327
328--- Lend the bytes past a byte storage's initialized prefix, its spare
329--- capacity, for the caller to write before `admit_bytes` counts them: the
330--- buffer a read fills. They hold whatever the backing held. End uses of
331--- the view before the storage is reserved, released or disposed.
332public spare_bytes: (store: storage(u8)) -> (room: []mut u8 from store) =
333 room = store.prefix[0..<0]
334 count: usize = length(store)
335 spare: usize = store.capacity_count - count
336 return when spare == 0
337 match store.base
338 no_storage: return
339 ptr (base): begin
340 first: ptr mut [1]u8 = ptr(usize(base) + count)
341 mut whole: []mut u8 = first.val[0..<1]
342 unchecked begin
343 -- The backing holds `capacity_count` bytes from `base`.
344 whole = whole[0..<spare]
345 end unchecked
346 room = whole
347 end
348 end match
349end spare_bytes
350
351--- Count the first `count` bytes of the spare capacity, which the caller
352--- has written, as initialized: the prefix ends past them. Reports
353--- `out_of_memory`, changing nothing, when fewer than `count` bytes are
354--- spare.
355public admit_bytes: (inout store: storage(u8), count: usize)
356 -> none ! out_of_memory =
357 have: usize = length(store)
358 fail out_of_memory when count > store.capacity_count - have
359 return when count == 0
360 match store.base
361 no_storage: fail out_of_memory
362 ptr (base): begin
363 first: ptr mut [1]u8 = ptr(usize(base))
364 mut whole: []mut u8 = first.val[0..<1]
365 unchecked begin
366 -- The backing holds `capacity_count` bytes from `base`.
367 whole = whole[0..<have + count]
368 end unchecked
369 store.prefix = whole
370 end
371 end match
372end admit_bytes
373
374--- Copy `bytes` after a byte storage's initialized prefix and count them in
375--- it, with `copy`, a word at a time where it moves words. Reports
376--- `out_of_memory`, changing nothing, when the spare capacity is shorter
377--- than `bytes`.
378public admit_copy: (inout store: storage(u8), bytes: []u8)
379 -> none ! out_of_memory =
380 count: usize = lenof bytes
381 return when count == 0
382 room: []mut u8 = spare_bytes(store)
383 fail out_of_memory when count > lenof room
384 copy(room[0..<count], bytes) else (problem)
385 _ = problem
386 fail out_of_memory
387 end
388 try admit_bytes(store, count)
389end admit_copy
390
391--- Append a complete value into a spare slot and return its index. Reports
392--- `out_of_memory` without publishing a new prefix when no slot is available.
393public admit: (item: type, inout store: storage(item),
394 escaping into store value: item)
395 -> (index: usize) ! out_of_memory =
396 index = length(store)
397 fail out_of_memory when index >= store.capacity_count
398 wanted: usize = index + 1
399 if index == 0 then
400 match store.base
401 no_storage: fail out_of_memory
402 ptr (base): begin
403 first: ptr mut [1]item = ptr(usize(base))
404 first.val[0] = value
405 store.prefix = first.val[0..<1]
406 end
407 end match
408 else
409 unchecked begin
410 store.prefix[index] = value
411 store.prefix = store.prefix[0..<wanted]
412 end unchecked
413 end if
414end admit
415
416--- Copy the item at `index`. Reports `out_of_bounds` before reading outside
417--- the initialized prefix; references inside the copy retain their origin.
418public get: (item: type, store: storage(item), index: usize)
419 -> (value: item from held store) ! out_of_bounds =
420 fail out_of_bounds when index >= length(store)
421 value = store.prefix[index]
422end get
423
424--- Overwrite an initialized item. Reports `out_of_bounds` before mutation;
425--- the caller handles resources held by the replaced value.
426public replace: (item: type, inout store: storage(item), index: usize,
427 escaping into store value: item) -> none ! out_of_bounds =
428 fail out_of_bounds when index >= length(store)
429 store.prefix[index] = value
430end replace
431
432--- Copy one initialized source item to the end of the target. Checks source
433--- index and target capacity before mutation; the source remains initialized.
434---
435--- The complete source value is read before the destination's narrow
436--- unchecked append. The new prefix is published only after its typed store.
437public transfer: (item: type, inout target: storage(item),
438 source: storage(item), index: usize)
439 -> (admitted: usize) ! out_of_bounds | out_of_memory =
440 fail out_of_bounds when index >= length(source)
441 admitted = length(target)
442 fail out_of_memory when admitted >= target.capacity_count
443 saved: item = source.prefix[index]
444 wanted: usize = admitted + 1
445 if admitted == 0 then
446 match target.base
447 no_storage: fail out_of_memory
448 ptr (base): begin
449 first: ptr mut [1]item = ptr(usize(base))
450 first.val[0] = saved
451 target.prefix = first.val[0..<1]
452 end
453 end match
454 else
455 unchecked begin
456 -- The private transfer copies an already-retained value into
457 -- independent raw storage, as the first-slot path does above.
458 -- Capture that destination before publishing its new witness.
459 slot: ptr mut item = ptr(usize(addr target.prefix[admitted]))
460 slot.val = saved
461 target.prefix = target.prefix[0..<wanted]
462 end unchecked
463 end if
464end transfer
465
466--- Copy the first `count` initialized source items, in order, into an empty
467--- target. Reports `out_of_bounds` when the source holds fewer, `not_empty`
468--- when the target already holds items and `out_of_memory` when its
469--- capacity is too small, each before any mutation. The source remains
470--- initialized.
471---
472--- A zero-sized item has one logical value repeated at the same address, so
473--- its prefix is established with one complete typed store and extended to
474--- `count` in constant time.
475public copy_prefix: (item: type, inout target: storage(item),
476 source: storage(item), count: usize)
477 -> none ! out_of_bounds | not_empty | out_of_memory =
478 fail out_of_bounds when count > length(source)
479 fail not_empty when length(target) <> 0
480 fail out_of_memory when count > target.capacity_count
481 return when count == 0
482
483 if sizeof item <> 0 then
484 -- The items' bytes move whole, with `copy`, a word at a time where
485 -- it moves words: the source holds `count` items, so their extent
486 -- is representable, and the target's capacity holds them.
487 extent: usize = count * sizeof item
488 match target.base
489 no_storage: fail out_of_memory
490 ptr (base): begin
491 held: ptr mut u8 = ptr(usize(addr source.prefix[0]))
492 copy(block_bytes(base, extent), block_bytes(held, extent))
493 else none
494 first: ptr mut [1]item = ptr(usize(base))
495 mut kept: []mut item = first.val[0..<1]
496 unchecked begin
497 -- The target's backing holds at least `count` items.
498 kept = kept[0..<count]
499 end unchecked
500 target.prefix = kept
501 end
502 end match
503 return
504 end if
505
506 saved: item = source.prefix[0]
507 match target.base
508 no_storage: fail out_of_memory
509 ptr (base): begin
510 first: ptr mut [1]item = ptr(usize(base))
511 first.val[0] = saved
512 target.prefix = first.val[0..<1]
513 end
514 end match
515 unchecked begin
516 target.prefix = target.prefix[0..<count]
517 end unchecked
518end copy_prefix
519
520--- Remove and return the last initialized item, the raw pop. Reports `empty`
521--- when the prefix is empty; backing and capacity remain available.
522public withdraw: (item: type, inout store: storage(item))
523 -> (value: item from held store) ! empty =
524 count: usize = length(store)
525 fail empty when count == 0
526 tail: usize = count - 1
527 value = store.prefix[tail]
528 store.prefix = store.prefix[0..<tail]
529end withdraw
530
531--- Discard all initialized items in constant time while retaining backing and
532--- capacity. Resources referred to by those values remain the caller's
533--- responsibility.
534public clear: (item: type, inout store: storage(item)) -> none =
535 store.prefix = store.prefix[0..<0]
536end clear
537
538--- Detach backing from an empty descriptor and reset it. Reports
539--- `not_empty` if items remain, or `empty` if no allocation exists. The
540--- returned pointer must still be freed through its provider.
541public detach: (item: type, inout store: storage(item))
542 -> (block: ptr mut u8 from store)
543 ! not_empty | empty =
544 fail not_empty when length(store) <> 0
545 match store.base
546 no_storage: fail empty
547 ptr (base): block = base
548 end match
549 store.base = no_storage
550 store.prefix = []
551 store.capacity_count = 0
552end detach
553
554--- Return the first offset at or after `used` within an `extent`-byte range
555--- at `base` whose address meets `alignment` and leaves room for `size`
556--- bytes. Reports `out_of_memory` when the range or the address space cannot
557--- hold it. This is the arithmetic every bump provider needs; the caller
558--- publishes `offset + size` as its new use only on success.
559---
560--- Zero alignment has the same byte-aligned meaning as one. Every operation
561--- that could overflow is guarded, including the end of a zero- or nonzero-
562--- sized result, so failure leaves allocator state for the caller to retain.
563public aligned_offset: (base: ptr mut u8, used: usize, extent: usize,
564 size: usize, alignment: usize)
565 -> (offset: usize) ! out_of_memory =
566 maximum: usize = 0 -% 1
567 fail out_of_memory when used > extent
568
569 base_address: usize = usize(base)
570 fail out_of_memory when used > maximum - base_address
571 current_address: usize = base_address + used
572
573 mut padding: usize = 0
574 if alignment > 1 then
575 -- alignof requests take the mask path; direct calls may need
576 -- division.
577 mask: usize = alignment - 1
578 mut remainder: usize = 0
579 if (alignment & mask) == 0 then
580 remainder = current_address & mask
581 else
582 remainder = current_address % alignment
583 end if
584 if not (remainder == 0) then
585 padding = alignment - remainder
586 end if
587 end if
588
589 fail out_of_memory when padding > extent - used
590 fail out_of_memory when padding > maximum - current_address
591 offset = used + padding
592 aligned_address: usize = current_address + padding
593 fail out_of_memory when size > extent - offset
594 fail out_of_memory when size > maximum - aligned_address
595end aligned_offset