Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Little-endian Nat encoding and decoding #11

Closed
pchiusano opened this issue Jun 9, 2021 · 1 comment
Closed

Little-endian Nat encoding and decoding #11

pchiusano opened this issue Jun 9, 2021 · 1 comment
Assignees

Comments

@pchiusano
Copy link
Member

I wanted these for some random number generation stuff.

pull-request.load git@github.com:unisonweb/base:.trunk git@github.com:pchiusano/unisoncode:.prs.natHelpers

Added definitions:

 Bytes.at!                         : Nat -> Bytes ->{Abort} Nat (+2 metadata)
 Bytes.at!.doc                     : Doc (+2 metadata)
 Nat.fromBytesLittleEndian         : Bytes ->{Abort} Nat (+2 metadata)
 Nat.fromBytesLittleEndian.doc     : Doc (+2 metadata)
 Nat.toBytesLittleEndian           : Nat -> Bytes (+2 metadata)
 Nat.toBytesLittleEndian.doc       : Doc (+2 metadata)
 Nat.toBytesLittleEndian.test.ex1  : [Result] (+3 metadata)
 Nat.toBytesLittleEndian.test.prop : [Result] (+3 metadata)
.prs.natHelpers> docs Bytes.at!

  `at! i bs` returns the `i`-th (0-based) byte in `bs` and calls abort if the index is out of
  bounds.
  
  # Examples
  
        toOptional '(at! 9 Bytes.empty)
        ⧨
        None
  
        toOptional '(at! 1 0xs1122334455)
        ⧨
        Some 34

.prs.natHelpers> docs Nat.toBytesLittleEndian

  Convert a Nat to its Bytes, in little endian order.
  
  The resulting Bytes will always have size 8.
  
  # Examples
  
        toBytesLittleEndian 1 Universal.=== 0xs0000000000000001
        ⧨
        true
  
        toBytesLittleEndian (Nat.shiftLeft 1 60) Universal.=== 0xs1000000000000000
        ⧨
        true
  
        toBytesLittleEndian 18446744073709551615 Universal.=== 0xsffffffffffffffff
        ⧨
        true
  
  # See also
  
    * fromBytesLittleEndian which converts in the other direction

.prs.natHelpers> docs Nat.fromBytesLittleEndian

  Reads a Nat from a Bytes, assuming most significant bytes come first.
  
  Calls abort if the input has size less than 8.
  
  # Examples
  
        toOptional '(fromBytesLittleEndian (toBytesLittleEndian 2))
        ⧨
        Some 2
  
        toOptional '(fromBytesLittleEndian (toBytesLittleEndian 93948238))
        ⧨
        Some 93948238
  
    In this example, the function is only given 1 byte, so it does abort:
  
        toOptional '(fromBytesLittleEndian 0xs00)
        ⧨
        None
@pchiusano
Copy link
Member Author

Just noticed this was merged earlier, closing @runarorama

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants