module Std.Bytes -- #242: source-order traversal with explicit state, not suspended functions. -- The cursor owns an immutable suffix view; the accumulator type is erased. family BytesTraversalState : Type 0 parameter erased state : Type 0 constructor BytesTraversalStateValue field unrestricted traversalRemaining : Bytes field unrestricted traversalAccumulated : state end-family -- Visit each byte exactly once in increasing offset order. The consumer is -- pure and may be non-associative. Empty input returns the initial state. -- Count the input once; exactly that many head/tail steps cannot overrun it. -- Storage retained by the consumer is its own contract. The traversal itself -- retains one suffix and one accumulator, rather than a per-byte closure chain. def bytesFoldFromStart = (lambda erased state : Type 0 . unrestricted consume : (pi unrestricted offset : Nat . unrestricted value : Byte . unrestricted accumulated : state . state) . unrestricted initial : state . unrestricted input : Bytes . eliminate BytesTraversalState (lambda unrestricted cursor : (family BytesTraversalState state) . state) (nat-eliminate (lambda unrestricted count : Nat . family BytesTraversalState state) (constructor BytesTraversalState BytesTraversalStateValue state input initial) (lambda unrestricted offset : Nat . unrestricted previous : (family BytesTraversalState state) . eliminate BytesTraversalState (lambda unrestricted cursor : (family BytesTraversalState state) . family BytesTraversalState state) previous (branch BytesTraversalStateValue remaining accumulated . constructor BytesTraversalState BytesTraversalStateValue state (bytes-tail remaining) (consume offset (bytes-head remaining) accumulated))) (bytes-length input)) (branch BytesTraversalStateValue remaining accumulated . accumulated)) -- Total range mechanisms: dropping past the end returns empty; the prefix -- builder pads with zero bytes past the end. Bounded codecs must admit ranges -- before calling these. Structural compiler lowering preserves these laws. def bytesDrop = (lambda unrestricted count : Nat . nat-eliminate (lambda unrestricted current : Nat . pi unrestricted input : Bytes . Bytes) (lambda unrestricted input : Bytes . input) (lambda unrestricted predecessor : Nat . unrestricted induction : (pi unrestricted input : Bytes . Bytes) . unrestricted input : Bytes . induction (bytes-tail input)) count) def bytesPrefixBuilder = (lambda unrestricted count : Nat . nat-eliminate (lambda unrestricted current : Nat . pi unrestricted input : Bytes . BytesBuilder) (lambda unrestricted input : Bytes . (bytes-builder-empty)) (lambda unrestricted predecessor : Nat . unrestricted induction : (pi unrestricted input : Bytes . BytesBuilder) . unrestricted input : Bytes . bytes-builder-append (pipe input bytes-head (bytes-cons b"") bytes-builder-chunk) (induction (bytes-tail input))) count)