Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-geocore

Source of release 0.7.3

0.7.3 / src / core / growing.lucb

## Heap arrays that grow by doubling: `Growing`, which keeps its capacity
## across rebuilds of retained overlays, and `grown` for parallel arrays that
## share one count (builders).
import memory

## `values` (heap) with room for `needed`, its first `used` kept: itself
## when it is large enough, else a doubled copy (at least `least`) that
## replaces it, the old array freed.
pub func grown[T](values: T[], used: usize, needed: usize, least: usize = 16) -> T[]!:
    if needed <= values.length: return values
    var capacity: usize = least if values.length < least else values.length
    while capacity < needed: capacity *= 2
    let replacement = try new T[capacity] --- in memory.heap
    if used > 0: memory.copy(replacement, values, used)
    if values.length > 0: free(values) in memory.heap
    return replacement

## A heap array that grows by doubling and keeps its capacity across rebuilds.
pub struct Growing[T]:
    pub var items: T[]
    pub var count: usize = 0

    pub func view() -> const T[]:
        return self.items[..<self.count]

    pub func clear():
        self.count = 0

    pub func reserve(capacity: usize) -> !:
        self.items = try grown[T](self.items, self.count, capacity, 64)

    pub func push(value: T) -> !:
        try self.reserve(self.count + 1)
        self.items[self.count] = value
        self.count += 1

    ## `value` put at `at` (0..count), the items from there moved up one.
    pub func insert(at: usize, value: T) -> !:
        if at > self.count: trap("Growing.insert past the end")
        try self.reserve(self.count + 1)
        var index = self.count
        while index > at:
            self.items[index] = self.items[index - 1]
            index -= 1
        self.items[at] = value
        self.count += 1

    pub func fill(count: usize, value: T) -> !:
        try self.reserve(count)
        for at in 0..<count: self.items[at] = value
        self.count = count

    ## Grow to `count` items, the new ones `value` (the rest kept).
    pub func extend(count: usize, value: T) -> !:
        try self.reserve(count)
        for at in self.count..<count: self.items[at] = value
        if count > self.count: self.count = count

    pub func assign(values: const T[]) -> !:
        try self.reserve(values.length)
        if values.length > 0: memory.copy(self.items, values, values.length)
        self.count = values.length

    pub func close():
        if self.items.length > 0: free(self.items) in memory.heap
        var empty: T[]
        self.items = empty
        self.count = 0

pub func same_ids(stored: const Growing[i64]*, values: const i64[]) -> bool:
    if values.length != stored.count: return false
    for at in 0..<values.length:
        if stored.items[at] != values[at]: return false
    return true