Skip to content

Commit

Permalink
Try to add cbor support
Browse files Browse the repository at this point in the history
  • Loading branch information
tulir committed Nov 1, 2023
1 parent ce83c3b commit c01c067
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
4 changes: 4 additions & 0 deletions internal/cbor/cbor.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ const (
additionalTypeEmbeddedJSON uint16 = 262
additionalTypeTagHexString uint16 = 263

// Expected later encoding for CBOR-to-JSON converters - from https://www.rfc-editor.org/rfc/rfc8949.html#section-3.4.5.2
additionalTypeTagBase64Standard byte = 22
additionalTypeTagBase64RawURL byte = 23

// Unspecified number of elements.
additionalTypeInfiniteCount byte = 31
)
Expand Down
11 changes: 11 additions & 0 deletions internal/cbor/decode_stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,17 @@ func decodeTagData(src *bufio.Reader) []byte {
}
src.UnreadByte()
return decodeStringToDataUrl(src, "application/cbor")
case additionalTypeTagBase64Standard, additionalTypeTagBase64RawURL:
data := decodeString(src, true)
enc := base64.StdEncoding
if byte(val) == additionalTypeTagBase64RawURL {
enc = base64.RawURLEncoding
}
output := make([]byte, enc.EncodedLen(len(data))+2)
output[0] = '"'
output[len(output)-1] = '"'
enc.Encode(output[1:len(output)-1], data)
return output
default:
panic(fmt.Errorf("Unsupported Additional Tag Type: %d in decodeTagData", val))
}
Expand Down
17 changes: 17 additions & 0 deletions internal/cbor/types.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cbor

import (
"encoding/base64"
"fmt"
"math"
"net"
Expand Down Expand Up @@ -484,3 +485,19 @@ func (e Encoder) AppendHex(dst []byte, val []byte) []byte {
dst = append(dst, byte(additionalTypeTagHexString&0xff))
return e.AppendBytes(dst, val)
}

// AppendBase64 adds a TAG and inserts base64 bytes as a string.
func (e Encoder) AppendBase64(enc *base64.Encoding, dst []byte, val []byte) []byte {
switch enc {
case base64.StdEncoding:
dst = append(dst, majorTypeTags|additionalTypeIntUint8)
dst = append(dst, additionalTypeTagBase64Standard)
return e.AppendBytes(dst, val)
case base64.RawURLEncoding:
dst = append(dst, majorTypeTags|additionalTypeIntUint8)
dst = append(dst, additionalTypeTagBase64RawURL)
return e.AppendBytes(dst, val)
default:
return e.AppendString(dst, enc.EncodeToString(val))
}
}

0 comments on commit c01c067

Please sign in to comment.