Silk

silk/bytes

Owned arbitrary bytes for file contents, process output, and other encoding-neutral data.

When to use

Use Bytes when every octet must round-trip unchanged. Use silk.string.String instead when the value is known to be valid UTF-8 and callers need text operations.

Details

make creates an empty value without allocating, while zeroed, copy, and append may require an Allocator. Shared and exclusive views borrow only the initialized prefix; later appends can reallocate, so do not retain a view across a mutation.

Examples

Copy, append, and update bytes

import silk.bytes as Bytes

import silk.allocator { Allocator }

import silk.effect { Effect }

import silk.u8 as u8

effect fn build() -> i32
! Allocator.OutOfMemoryError {
  let mut allocator = Allocator.systemAllocatorProvider()
  let source = b"AB"
  let copying = Bytes.copy(&source)
    |> Effect.provideMut<Allocator>(&mut allocator)
  let mut bytes = run copying
  let suffix = b"C"
  let appending = Bytes.append(&mut bytes, &suffix)
    |> Effect.provideMut<Allocator>(&mut allocator)
  let appended = run appending
  let mut writable = Bytes.asMutSlice(&mut bytes)
  writable[1] = u8.toU8(48)
  let readable = Bytes.asSlice(&bytes)
  return u8.toI32(readable[0]) - u8.toI32(readable[1]) + u8.toI32(readable[2]) - 42
}

effect fn recover(error: Allocator.OutOfMemoryError) -> i32 {
  return 0
}

pub fn main() -> i32 {
  return run Effect.catchAll(build(), recover)
}

Import as Bytes with import silk.bytes.

Public declarations: 8.

Bytes

pub struct Bytes

An owned encoding-neutral sequence of arbitrary octets.

Details

A value owns its initialized bytes and releases their storage on drop. Its length can grow with append, and its capacity is not part of the public contract.

make

pub fn make() -> Bytes

Creates an empty Bytes value without allocating storage.

zeroed

pub effect fn zeroed(length: usize) -> Bytes ! OutOfMemoryError ? &mut Allocator

Allocates an owned initialized byte buffer of exactly length zero octets.

Details

A zero length returns an empty value without an allocation.

length

pub fn length(self: &silk/bytes.Bytes) -> usize

Returns the initialized byte count.

copy

pub effect fn copy(values: &[u8]) -> Bytes ! OutOfMemoryError ? &mut Allocator

Copies a complete borrowed byte sequence into independently owned storage.

append

pub effect fn append(self: &mut silk/bytes.Bytes, values: &[u8]) -> () ! OutOfMemoryError ? &mut Allocator

Appends a complete borrowed byte sequence in source order.

Details

If growth fails, the original bytes and their length remain unchanged.

asSlice

pub fn asSlice(self: &silk/bytes.Bytes) -> &[u8]

Borrows all initialized octets as one shared lexical slice.

asMutSlice

pub fn asMutSlice(self: &mut silk/bytes.Bytes) -> &mut [u8]

Borrows all initialized octets as one exclusive lexical slice.

Gotchas

Do not retain this slice across append, because an append can replace the allocation.

On this page