|
| 1 | +------------------------------------------------------------------------ |
| 2 | +-- The Agda standard library |
| 3 | +-- |
| 4 | +-- Bytestrings: simple types and functions |
| 5 | +-- Note that these functions do not perform bound checks. |
| 6 | +------------------------------------------------------------------------ |
| 7 | + |
| 8 | +{-# OPTIONS --cubical-compatible #-} |
| 9 | + |
| 10 | +module Data.Bytestring.Base where |
| 11 | + |
| 12 | +open import Data.Nat.Base using (ℕ; _+_; _*_; _^_) |
| 13 | +open import Agda.Builtin.String using (String) |
| 14 | +import Data.Fin.Base as Fin |
| 15 | +open import Data.Vec.Base as Vec using (Vec) |
| 16 | +open import Data.Word8.Base as Word8 using (Word8) |
| 17 | +open import Data.Word64.Base as Word64 using (Word64) |
| 18 | + |
| 19 | +open import Function.Base using (const; _$_) |
| 20 | + |
| 21 | +------------------------------------------------------------------------------ |
| 22 | +-- Re-export type and operations |
| 23 | + |
| 24 | +open import Data.Bytestring.Primitive as Prim public |
| 25 | + using ( Bytestring |
| 26 | + ; length |
| 27 | + ; take |
| 28 | + ; drop |
| 29 | + ) |
| 30 | + renaming (index to getWord8) |
| 31 | + |
| 32 | +------------------------------------------------------------------------------ |
| 33 | +-- Operations |
| 34 | + |
| 35 | +slice : Word64 → Word64 → Bytestring → Bytestring |
| 36 | +slice start chunk buf = take chunk (drop start buf) |
| 37 | + |
| 38 | +------------------------------------------------------------------------------ |
| 39 | +-- Generic combinators for fixed-size encodings |
| 40 | + |
| 41 | +getWord8s : (n : ℕ) → Bytestring → Word64 → Vec Word8 n |
| 42 | +getWord8s n buf idx |
| 43 | + = let idx = Word64.toℕ idx in |
| 44 | + Vec.map (λ k → getWord8 buf (Word64.fromℕ (idx + Fin.toℕ k))) |
| 45 | + $ Vec.allFin n |
| 46 | + |
| 47 | +-- Little endian representation: |
| 48 | +-- Low place values first |
| 49 | +fromWord8sLE : ∀ {n w} {W : Set w} → (fromℕ : ℕ → W) → Vec Word8 n → W |
| 50 | +fromWord8sLE f ws = f (Vec.foldr′ (λ w acc → Word8.toℕ w + acc * (2 ^ 8)) 0 ws) |
| 51 | + |
| 52 | +-- Big endian representation |
| 53 | +-- Big place values first |
| 54 | +fromWord8sBE : ∀ {n w} {W : Set w} → (fromℕ : ℕ → W) → Vec Word8 n → W |
| 55 | +fromWord8sBE f ws = f (Vec.foldl′ (λ acc w → acc * (2 ^ 8) + Word8.toℕ w) 0 ws) |
| 56 | + |
| 57 | +------------------------------------------------------------------------------ |
| 58 | +-- Getting Word64 |
| 59 | + |
| 60 | +getWord64LE : Bytestring → Word64 → Word64 |
| 61 | +getWord64LE buf idx |
| 62 | + = fromWord8sLE Word64.fromℕ (getWord8s 8 buf idx) |
| 63 | + |
| 64 | +getWord64BE : Bytestring → Word64 → Word64 |
| 65 | +getWord64BE buf idx |
| 66 | + = fromWord8sBE Word64.fromℕ (getWord8s 8 buf idx) |
0 commit comments