Skip to content

Commit

Permalink
Make tokenTypeOf more precise (#325)
Browse files Browse the repository at this point in the history
* Make `tokenTypeOf` more precise

Now `tokenTypeOf` distinguishes between:

- Unsigned 64 bit integers `(0     <= n < 2^64)`: `TypeUInt64`
- Negative 64 bit integers `(-2^64 < n  < 0   )`: `TypeNInt64`
- Integers outside the ranges above             : `TypeInteger`

Fixes #324
  • Loading branch information
Damian Nadales committed Sep 8, 2023
1 parent 4149849 commit c8013b3
Showing 1 changed file with 22 additions and 19 deletions.
41 changes: 22 additions & 19 deletions cborg/src/Codec/CBOR/FlatTerm.hs
Expand Up @@ -562,25 +562,28 @@ fromFlatTerm decoder ft =
-- | Map a 'TermToken' to the underlying CBOR 'TokenType'
tokenTypeOf :: TermToken -> TokenType
tokenTypeOf (TkInt n)
| n >= 0 = TypeUInt
| otherwise = TypeNInt
tokenTypeOf TkInteger{} = TypeInteger
tokenTypeOf TkBytes{} = TypeBytes
tokenTypeOf TkBytesBegin{} = TypeBytesIndef
tokenTypeOf TkString{} = TypeString
tokenTypeOf TkStringBegin{} = TypeStringIndef
tokenTypeOf TkListLen{} = TypeListLen
tokenTypeOf TkListBegin{} = TypeListLenIndef
tokenTypeOf TkMapLen{} = TypeMapLen
tokenTypeOf TkMapBegin{} = TypeMapLenIndef
tokenTypeOf TkTag{} = TypeTag
tokenTypeOf TkBool{} = TypeBool
tokenTypeOf TkNull = TypeNull
tokenTypeOf TkBreak = TypeBreak
tokenTypeOf TkSimple{} = TypeSimple
tokenTypeOf TkFloat16{} = TypeFloat16
tokenTypeOf TkFloat32{} = TypeFloat32
tokenTypeOf TkFloat64{} = TypeFloat64
| n >= 0 = TypeUInt
| otherwise = TypeNInt
tokenTypeOf (TkInteger n) -- See https://github.com/well-typed/cborg/issues/324
| 0 <= n && n <= 0xffffffffffffffff = TypeUInt64 -- 0xffffffffffffffff == 2^64 - 1
| -0xffffffffffffffff <= n && n < 0 = TypeNInt64
| otherwise = TypeInteger
tokenTypeOf TkBytes{} = TypeBytes
tokenTypeOf TkBytesBegin{} = TypeBytesIndef
tokenTypeOf TkString{} = TypeString
tokenTypeOf TkStringBegin{} = TypeStringIndef
tokenTypeOf TkListLen{} = TypeListLen
tokenTypeOf TkListBegin{} = TypeListLenIndef
tokenTypeOf TkMapLen{} = TypeMapLen
tokenTypeOf TkMapBegin{} = TypeMapLenIndef
tokenTypeOf TkTag{} = TypeTag
tokenTypeOf TkBool{} = TypeBool
tokenTypeOf TkNull = TypeNull
tokenTypeOf TkBreak = TypeBreak
tokenTypeOf TkSimple{} = TypeSimple
tokenTypeOf TkFloat16{} = TypeFloat16
tokenTypeOf TkFloat32{} = TypeFloat32
tokenTypeOf TkFloat64{} = TypeFloat64

--------------------------------------------------------------------------------

Expand Down

0 comments on commit c8013b3

Please sign in to comment.