//! returns: 0 //! Slices grow in a static heap and through its allocator view, and exhaustion throws. /// The allocation error, which the compiler knows. @language union AllocError: Copy { OutOfMemory } /// A heap, which holds elements of any type. @language record Heap {} /// Allocate the backing storage of a static heap. @intrinsic constant fn new(size: u32) -> Heap; /// The allocator view of a heap, which provides plain elements. @language record Allocator {} /// A region of memory for growable slices. static POOL: Heap = new(256); /// Storage declared as a constant can hold values that contain pointers. constant EXTRA: Heap = new(32); /// A plain record. record Point: Copy { /// Horizontal coordinate. x: i32, /// Vertical coordinate. y: i32, } /// Numbers that holders point to. static NUMBERS: [u32; 2] = [7, 8]; /// A record that holds a pointer, which only a heap can provide. record Holder { /// Owned pointer to a number. p: *u32, } /// Append through the allocator view. fn push(xs: *mut [u32], v: u32, a: &Allocator) -> *mut [u32] throws (AllocError) { let mut ys = xs; try ys.append(v, a); return ys; } @default fn main() -> i32 { let mut xs: *mut [u32] = &mut []; try! xs.append(7, &POOL); try! xs.append(8, &POOL); assert xs.len == 2 and xs[0] == 7 and xs[1] == 8; // Elements keep their values when the slice moves. let mut ps: *mut [Point] = &mut []; try! ps.append(Point { x: 1, y: 2 }, &POOL); try! ps.reserve(4, &POOL); try! ps.resize(3, Point { x: 5, y: 6 }, &POOL); assert ps.len == 3 and ps[0].x == 1 and ps[2].y == 6; try! xs.extend(&[9, 10], &POOL); assert xs.len == 4 and xs[3] == 10 and xs[0] == 7; // A heap handle coerces to its allocator view. let ys = try! push(&mut [], 3, &POOL); assert ys.len == 1 and ys[0] == 3; // A heap holds elements that have pointers, which an allocator view cannot. let mut hs: *mut [Holder] = &mut []; try! hs.append(Holder { p: &NUMBERS[0] }, &POOL); try! hs.append(Holder { p: &NUMBERS[1] }, &POOL); try! hs.reserve(8, &POOL); assert hs.len == 2 and *hs[0].p == 7 and *hs[1].p == 8; // One object. let p = try! POOL.new(Point { x: 3, y: 4 }); assert p.x == 3 and p.y == 4; let q = try! POOL.new(Holder { p: &NUMBERS[0] }); assert *q.p == 7; let handle = &POOL; let r = try! (*handle).new(9 as u32); assert *r == 9; let s = try! (&POOL).new(10 as u32); assert *s == 10; let extra = try! EXTRA.new(Holder { p: &NUMBERS[1] }); assert *extra.p == 8; // Exhaustion throws and leaves the slice unchanged. let mut big: *mut [u32] = &mut []; try big.reserve(1000, &POOL) catch e { assert e == AllocError::OutOfMemory; assert big.len == 0; return 0; }; return 1; }