| 1 |
------------------------------------------------------------------------ |
| 2 |
-- The Agda standard library |
| 3 |
-- |
| 4 |
-- Machine words: unsafe functions using the FFI |
| 5 |
------------------------------------------------------------------------ |
| 6 |
|
| 7 |
{-# OPTIONS --cubical-compatible #-} |
| 8 |
|
| 9 |
module Data.Word64.Unsafe where |
| 10 |
|
| 11 |
open import Agda.Builtin.Bool using (Bool; true; false) |
| 12 |
open import Data.Fin.Base as Fin using (Fin) |
| 13 |
open import Data.Product.Base using (proj₁) |
| 14 |
open import Data.Vec.Base as Vec using (Vec) |
| 15 |
open import Data.Word8.Base as Word8 using (Word8) |
| 16 |
open import Data.Word64.Base using (Word64; fromℕ) |
| 17 |
open import Function.Base using (_$_; _|>_) |
| 18 |
|
| 19 |
------------------------------------------------------------------------ |
| 20 |
-- Re-export primitives publicly |
| 21 |
|
| 22 |
open import Data.Word64.Primitive as Prim public |
| 23 |
using ( show ) |
| 24 |
|
| 25 |
testBit : Word64 → Fin 64 → Bool |
| 26 |
testBit w i = Prim.testBit w (Fin.toℕ i) |
| 27 |
|
| 28 |
_[_]≔_ : Word64 → Fin 64 → Bool → Word64 |
| 29 |
w [ i ]≔ false = Prim.clearBit w (Fin.toℕ i) |
| 30 |
w [ i ]≔ true = Prim.setBit w (Fin.toℕ i) |
| 31 |
|
| 32 |
------------------------------------------------------------------------ |
| 33 |
-- Convert to its components |
| 34 |
|
| 35 |
toBits : Word64 → Vec Bool 64 |
| 36 |
toBits w = Vec.tabulate (testBit w) |
| 37 |
|
| 38 |
fromBits : Vec Bool 64 → Word64 |
| 39 |
fromBits bs = Vec.foldl′ _|>_ (fromℕ 0) |
| 40 |
$ Vec.zipWith (λ i b → _[ i ]≔ b) (Vec.allFin 64) bs |
| 41 |
|
| 42 |
toWord64s : Word64 → Vec Word8 8 |
| 43 |
toWord64s w = |
| 44 |
let ws = proj₁ (Vec.group 8 8 (toBits w)) in |
| 45 |
Vec.map Word8.fromBits ws |