flan/test/programs/bytes-copy.flan

49 lines
1.9 KiB
Plaintext

;;;; (bytes s) copies, (bytes-view s) aliases — the ruling from the
;;;; INSERTIONSORT dogfooding session. The pin is the exact inverse of the
;;;; old aliasing: a write through the copy leaves the original string
;;;; printing unchanged, where the old (bytes s) either showed the write
;;;; through or trapped, depending on where the string's storage was.
(defonce frame Allocator)
(defn main [] i32
;; 1. The copy is writable and independent. Under the old reinterpret this
;; second line printed ZNSERTIONSORT too (or the whole program died in
;; .rodata) — the original staying itself is the whole of the change.
(let [s "INSERTIONSORT"
b (bytes s)]
(set (at b 0) \Z)
(println (str b)) ; ZNSERTIONSORT
(println s) ; INSERTIONSORT
;; The copy's block came from the context allocator, and free hands it
;; back there — which is what keeps this program leak-free.
(free b))
;; 2. A literal's copy is writable — the exact form that used to segfault
;; at -O0 and silently do nothing at -O2.
(let [b (bytes "hi")]
(set (at b 0) \H)
(println (str b)) ; Hi
(free b))
;; 3. The view still costs nothing and reads the string's own storage.
(let [v (bytes-view "abc")]
(println (length v)) ; 3
(println (at v 2))) ; 99
;; 4. (bytes s a) names the allocator, like (vec-new T a) and (clone v a):
;; the copy's block comes from the arena and free-all reclaims it.
(set frame (arena-new 4096))
(let [b (bytes "arena" frame)]
(set (at b 4) \A)
(println (str b))) ; arenA
(free-all frame)
(arena-destroy frame)
;; 5. (clone xs) with no allocator is the context's too, and free releases
;; it the same way.
(let [c (clone (slice [1 2 3]))]
(println (at c 2)) ; 3
(free c))
0)