Debian Codegraph @

src/Data/Bytestring/Builder/Base.agda

raw
1 ------------------------------------------------------------------------
2 -- The Agda standard library
3 --
4 -- Bytestrings: builder type and functions
5 ------------------------------------------------------------------------
6
7 {-# OPTIONS --cubical-compatible #-}
8
9 module Data.Bytestring.Builder.Base where
10
11 open import Data.Nat.Base using (ℕ; zero; suc; _/_; _%_; _^_)
12 open import Data.Word8.Base as Word8 using (Word8)
13 open import Data.Word64.Base as Word64 using (Word64)
14 open import Function.Base using (_∘′_)
15
16 ------------------------------------------------------------------------------
17 -- Re-export type and operations
18
19 open import Data.Bytestring.Builder.Primitive as Prim public
20 using ( Builder
21 ; toBytestring
22 ; bytestring
23 ; word8
24 ; empty
25 ; _<>_
26 )
27
28 ------------------------------------------------------------------------------
29 -- High-level combinators
30
31 module List where
32
33 open import Data.List.Base as List using (List)
34
35 concat : List Builder → Builder
36 concat = List.foldr _<>_ empty
37
38 module Vec where
39
40 open import Data.Vec.Base as Vec using (Vec)
41
42 concat : ∀ {n} → Vec Builder n → Builder
43 concat = Vec.foldr′ _<>_ empty
44 open Vec
45
46 ------------------------------------------------------------------------------
47 -- Generic word-specific combinators
48
49 open import Data.Vec.Base as Vec using (Vec; []; _∷_)
50
51 wordN : ∀ {n} → Vec Word8 n → Builder
52 wordN = concat ∘′ Vec.map word8
53
54 toWord8sLE : ∀ {w} {W : Set w} (n : ℕ) (toℕ : W → ℕ) → W → Vec Word8 n
55 toWord8sLE n toℕ w = loop (toℕ w) n where
56
57 loop : ℕ → (n : ℕ) → Vec Word8 n
58 loop acc 0 = []
59 loop acc 1 = Word8.fromℕ acc ∷ []
60 loop acc (suc n) = Word8.fromℕ (acc % 2 ^ 8) ∷ loop (acc / 2 ^ 8) n
61
62 toWord8sBE : ∀ {w} {W : Set w} (n : ℕ) (toℕ : W → ℕ) → W → Vec Word8 n
63 toWord8sBE n toℕ w = Vec.reverse (toWord8sLE n toℕ w)
64
65 ------------------------------------------------------------------------------
66 -- Builders for Word64
67
68 word64LE : Word64 → Builder
69 word64LE w = wordN (toWord8sLE 8 Word64.toℕ w)
70
71 word64BE : Word64 → Builder
72 word64BE w = wordN (toWord8sBE 8 Word64.toℕ w)