DocsLanguage Guide
Inline Layout
Contiguous pointer-free values, relative references, variant-sized unions and zero-copy bytes.
An ordinary struct that holds a String or an array holds a pointer to a buffer somewhere else on the heap. That is usually what you want, but it has costs: every nested string and array is another allocation, the value's parts are scattered through memory, and before you can write the value to a file or a socket you have to serialise it, walking every pointer.
Inline layout is Sable's alternative, taken from the Goose language's data model. An @inline_layout struct is one contiguous block of bytes containing no pointers at all. Its strings and arrays are stored in place, inside the block. The whole nested value costs one allocation, it is read where it lies, and it is already in the form you would write to disk.
This chapter covers inline-layout structs and the arrays and references that live inside them, zero-copy serialisation, the inline arrays T[k] and T[..k], viewing plain data as bytes, and control over a struct's padding and alignment. It builds on the array family from Arrays and Collections and the references from Memory and Ownership.
Inline-Layout Structs#
You ask for inline layout with an attribute:
@inline_layoutstruct OrderLine { var sku: U8[..16] // inline, at most 16 bytes var qty: U16 var price: U32 // in cents}@inline_layoutstruct Order { var id: U64 var customer: U8[..32] // inline, at most 32 bytes var lines: OrderLine[>..] // a grow-only array, stored inline var parent: Order&<u32>? // a 4-byte relative reference; 0 means none}The block is laid out with the fixed-size fields first, at offsets the compiler knows, and then each variable-size field in the order it is declared, each with its count stored just before its elements. Nested inline structs are stored in place. There is no pointer anywhere in it.
You build and change one like any other struct:
var order = Order { id: 7, customer: "Ann", lines: [], parent: none }order.lines.append(OrderLine { sku: "A-1", qty: 2, price: 1999 })order.lines.append(OrderLine { sku: "B-22", qty: 1, price: 500 })var total: U64 = 0for line in order.lines { total += U64(line.qty) * U64(line.price)}print("\(order.customer.toString()): \(order.lines.count) lines, \(total)")Ann: 2 lines, 4498A string literal fills a U8[..k] with its UTF-8 bytes, and toString() reads them back as a String. Storing more than the bound allows traps (too many bytes for the inline array).
What that bought you:
- One allocation. The whole order, its customer and every line, is one block. The Goose project's worked example of this shape takes 29 bytes and no allocations, against 160 bytes and one allocation in C++ and 153 bytes and four in Rust.
- Locality. Going through
order.linesreads memory in order. - Position independence. With no absolute pointers, the block can be copied anywhere, written to a file or sent over a socket as it is.
- In-place construction. A value is built at its final destination, field by field, never built somewhere and then copied there.
An inline-layout value is still a value. Copying it shares the block until one copy changes, at which point that copy gets a block of its own:
var a = Order { id: 1, customer: "Ann", lines: [], parent: none }var b = ab.customer = "Bob"print("\(a.customer.toString()) \(b.customer.toString())") // Ann BobIterable, Not Indexable#
Elements of different sizes can't be found by arithmetic, so an inline array whose elements vary in size can be gone through with for, but not indexed: order.lines[3] is a compile error because OrderLine holds a variable-size sku. If you need random access, build a side index of references as you go through. An inline array of fixed-size elements, such as Node[>..] below, can be indexed as usual.
References Inside the Block#
Field access, elements, and a loop's element are views into the block, never copies: line in the loop above reads the order's own bytes. Views are references, held to root inference like any other (see Memory and Ownership). A view rooted in a local block can't be returned, and a change to the block — growing an array moves the bytes after it — makes every view taken before it stale:
@inline_layoutstruct Item { var value: I32 }@inline_layoutstruct Bag { var items: Item[>..] }fn first(_ bag: Bag&) -> Item& { return &bag.items[0] // fine: rooted in the caller's value}var bag = Bag { items: [Item { value: 1 }] }let kept = &bag.items[0]bag.items.append(Item { value: 2 })print(kept.value) // error: this reference into local 'bag' is staleAppending to an array while you go through it is refused for the same reason.
Relative References#
An ordinary reference, T&, is a machine address: 8 bytes, and meaningless once the block is copied somewhere else. Inside an inline block you use a relative reference instead, which stores an offset:
| Type | Size | Meaning |
|---|---|---|
Order& |
8 bytes | A machine address |
Order&<u32> |
4 bytes | An offset from the field's own address |
Order&<u16> |
2 bytes | The same, in two bytes |
Order&<u32>? |
4 bytes | An optional one: an offset of 0 means none |
Order&<u16 in pool> |
2 bytes | An offset from the base of a named pool |
Relative references are what let inline layout describe linked structures — a tree with parent links — without pointers, and so without losing position independence:
@inline_layoutstruct Node { var value: I32 var parent: Node&<u32>?}@inline_layoutstruct Tree { var root: Node&<u32>? var name: U8[..32] var nodes: Node[>..]}fn depth(_ tree: Tree, _ index: Int) -> Int { var steps = 0 var current = tree.nodes[index].parent while current != none { steps += 1 current = current!.parent } return steps}var tree = Tree { root: none, name: "t", nodes: [] }tree.nodes.append(Node { value: 10, parent: none })tree.nodes.append(Node { value: 20, parent: none })tree.nodes.append(Node { value: 30, parent: none })tree.nodes[1].parent = &tree.nodes[0]tree.nodes[2].parent = &tree.nodes[1]tree.root = &tree.nodes[0]print("\(depth(tree, 0)) \(depth(tree, 1)) \(depth(tree, 2))") // 0 1 2print(tree.nodes[2].parent!.parent!.value) // 10You set a relative reference from an ordinary one, &tree.nodes[0], and read it back as a reference. When a change of size moves bytes — giving the tree a longer name moves every node — every relative reference across the move is measured again, so the links stay right.
Note
Pools, and so T&<u16 in pool>, are not built yet. Relative references from a field's own address work today.
Zero-Copy Serialisation#
Because an inline-layout value contains no pointers, it already is its serialised form. Bytes.of gives you its bytes, with no serialising pass:
fn save(_ order: Order) -> U8[>..] { return Bytes.of(order)}Going the other way is where care is needed: bytes from a file or a socket may be truncated, corrupt or hostile. fromBytes validates them before it gives you a value. It checks the framing, every count against its bound and the bytes left, every Bool and Char, and that every relative reference points at the start of a value of its type. Bad input gives .Invalid with a reason, never a value with a bad reference in it:
fn load(_ bytes: U8[>..]) -> Order? { match Order.fromBytes(bytes) { case .Ok(let order) => { return order } case .Invalid(let why) => { print("rejected order: \(why)") } } return none}var corrupt = save(order)corrupt.append(0)let refused = load(corrupt) // prints "rejected order: bytes after the value"The result is a Decoded<Order>, a @frozen union of Ok(value:) and Invalid(why:), so a match on it needs no default. This is a validate once, then use model: after fromBytes succeeds, reading the value checks nothing more.
Every @inline_layout struct conforms to Sable.Core's InlineLayout protocol, whose one requirement is static fn fromBytes(_ bytes: U8[>..]) -> Decoded<Self>. The compiler writes it for the struct's layout, as @derive writes ==. Generic code asks for it by name, and Bytes.of takes only an InlineLayout value:
fn decode<T: InlineLayout>(_ bytes: U8[>..]) -> Decoded<T> { return T.fromBytes(bytes)}There is deliberately no way to view an arbitrary slice of bytes as inline values, as C#'s MemoryMarshal.Cast does: that would be the trust-the-bytes model this design rules out. A value fromBytes gives you is a block of its own, made as the bytes are checked. Code that does trust its bytes reads them in an unsafe block, through RawPtr.load(as:byteOffset:) (see Unsafe Code and C Interop). For bytes read and written value by value, use ByteBuffer and ByteReader, and for buffers kept for reuse, BufferPool.
Inline Arrays#
Two kinds of array keep their elements where the array itself is, with no buffer at all: T[k], exactly k elements, and T[..k], up to k elements, growing and shrinking within that room. Unlike @inline_layout, these work anywhere: in a local (on the stack), in a struct's or a class's field, in a union's payload, in a closure's capture, in a global.
var recent: Int[..8] = [] // room for 8, no allocationfor reading in [3, 1, 4, 1, 5] { recent.append(reading)}print(recent.count) // 5let identity: F32[3] = [1, 0, 0]T[k] is laid out as k elements one after another. T[..k] is laid out as its count, an Int, followed by room for k elements, of which the first count are in use. So SmallVec<Int, 8> and ArrayVec<Int, 8>, which are built on Element[..N], cost no allocation while they are within their room.
An inline array is a value in the way a struct is. Copying one copies its elements; destroying it destroys them; and since nothing is shared there is no copy-on-write. Its size is part of its type. It is never moved around whole if it needn't be: passed to a function, it is passed as a large struct is, by borrowing the caller's storage, and a function returning one writes it where the caller says. An element is read, written or passed inout where it is.
An inline array takes at most 64 KiB (S7004), because it is copied whole and may live on a stack of 256 KiB. The heap's array kinds hold any number.
Lending as a Slice#
Passed where a slice T[:] is wanted, an inline array lends itself: the slice is a view of the array's own storage, with nothing copied, as long as the compiler can prove the view can't outlive the use. That covers a call that keeps nothing of its argument, total(xs) for fn total(_: Int[:]), xs.contains(element: 3), and xs[1..<3] passed to a call:
fn total(_ values: Int[:]) -> Int { var sum = 0 for v in values { sum += v } return sum}var scores: Int[4] = [7, 9, 4, 8]print(total(scores)) // 28: no copyscores.sort() // sorted where it isprint(scores) // [4, 7, 8, 9]A mutating member of T[:] — sort(), reverse(), swapAt — is lent the whole array for the call, so it changes the elements where they are. A range passed inout, f(&xs[1..<3]), is lent the same way. Where the proof fails — a slice stored, returned, captured, or given to a function that keeps it — the slice is the elements copied into a buffer of their own, as toArray() always is. That is still correct, at the cost of one allocation.
Variant-Sized Unions#
A union normally reserves room for its largest case, so that a value can change case in place and an array of them can be indexed. Sable's design has a second mode, written with .. after the name, where each value takes exactly its case's size:
union Shape { Circle(r: F32), Rect(w: F32, h: F32), Poly(pts: Vec2[>..]) } // fixed modeunion Shape.. { Circle(r: F32), Rect(w: F32, h: F32), Poly(pts: Vec2[>..]) } // variable modeIn variable mode, an array of values is compact and sequential, and a reference may point into a payload, because a payload never moves. The price is that a value can never change case, and an array of them is walked rather than indexed. It suits data whose shape is fixed once made: syntax trees, message logs, protocol frames. A syntax tree of 100,000 nodes in variable mode is typically 40–60% of its size in fixed mode, because the largest node is usually much larger than the median.
Note
Variant-sized unions are part of the design and parse today, but are not built yet. So are generic inline-layout structs, T[k] and the shrinking and slice kinds of array inside an @inline_layout struct, and indexing elements that vary in size.
Viewing Plain Data as Bytes#
Some types are their bytes and nothing else: no padding, no pointers, no bit patterns that aren't a value. Sable.Core calls them PlainData. The integers and floats are; so is a struct made only of them, with no padding and no deinit (and not @noncopy or @inline_layout), and an inline array T[k] of one. A Bool, a Char, an enum, a union, an optional, a tuple, a class, a closure, a reference and a buffered array are not: each has bytes that belong to no value, or bit patterns that are no value.
Conformance is worked out from what a type is made of, as Sendable's is. A type that declares : PlainData is held to it (S3490).
A slice of a plain type can be seen as a slice of another plain type, with nothing copied. reinterpreted(as:) gives a view of the same buffer, measured in the other type's stride, and bytes is the view as U8:
struct Vector3 { var x: F32; var y: F32; var z: F32 } // 12 bytes, no paddinglet points: Vector3[>..] = [Vector3(x: 1, y: 2, z: 3), Vector3(x: 4, y: 5, z: 6)]let floats = points.reinterpreted(as: F32.self) // F32[:], count 6, the same bufferlet again = floats.reinterpreted(as: Vector3.self) // and backlet raw = points.bytes // U8[:], count 24print(floats[4]) // 5.0The view is an ordinary slice: you can keep it and pass it on, and it holds the buffer as any slice does. Because neither type has a byte that is no one's or a bit pattern that is no value, every read through the view is a value, and every write leaves the other type's values whole.
The run must be a whole number of the other type's values, and must start at a multiple of its stride from the start of the buffer, or the view traps. An array's first element always does:
points[1..<2].reinterpreted(as: U64.self) // traps: it starts 12 bytes inBoth element types must be PlainData: S3023 when the array's element isn't, S3007 when the target type isn't.
Writing Through a View#
Where the array may be written, so may its view, and writing through the view changes the array's elements where they are:
var mesh: Vector3[>..] = [Vector3(x: 1, y: 2, z: 3), Vector3(x: 4, y: 5, z: 6)]fn halve(_ values: inout F32[:]) { for i in 0..<values.count { values[i] /= 2 }}mesh.reinterpreted(as: F32.self)[4] = 50halve(&mesh.reinterpreted(as: F32.self))mesh.reinterpreted(as: F32.self).reverse()The array lends itself to the view for the access, as it does to an inout T[:] argument: it is made the only reference to its buffer (or, for an inline array, lent where it is), so nothing is copied, and has it back when the access ends. A view handed back with a different count of bytes traps. A let array's view only reads (S3010).
Controlling Layout: @packed and @align#
For a struct that must match a file format or a C struct exactly, two attributes control its padding and alignment.
@packed lays the fields one after another with no padding between them, and aligns the struct to a byte:
@packedstruct WireHeader { var kind: U8 var length: U32 // at offset 1, not 4} // 5 bytes@align(n), where n is a power of two up to 16, aligns the struct to at least n bytes and rounds its size up to a multiple of n. More than 16 is an error (S3510), since 16 is the alignment of every block the runtime allocates. With @packed as well, the struct is aligned to exactly n.
@align(16)struct Particle { var position: Vector3 var mass: F32}These are C's layouts — __attribute__((packed)) and _Alignas(n) — and a struct passed to or from C is passed as C passes its own. A field of a packed struct passed inout may be misaligned, so it is copied to an aligned place for the call and back after.
On an @inline_layout struct, @align(n) puts the struct at a multiple of n from the start of a value that holds it, and rounds its fixed part up to one, which gives a record format a fixed stride:
@inline_layout@align(8)struct Stamp { var kind: U8 var code: U16}print(Bytes.of(Stamp { kind: 1, code: 2 }).count) // 8When to Use Inline Layout#
Reach for these tools when the shape of the bytes matters:
@inline_layoutfor records you write, send or map: saved documents, messages, caches, anything where serialising is a cost you'd rather not pay. Read-mostly data with many small strings and arrays is where it saves the most.T[k]andT[..k]for small, bounded collections in hot code, where a heap allocation per value would dominate.PlainDataviews for handing numeric data to a GPU, a file or a hash function without copying.@packedand@alignfor matching a layout someone else has defined.
For everything else, an ordinary struct with ordinary arrays and strings is simpler, and is still a Tier 0 value.