Skip to content

Add RawMessage.Type to report a value's CBOR major type - #805

Open
ChrisJr404 wants to merge 1 commit into
fxamacker:masterfrom
ChrisJr404:rawmessage-type
Open

Add RawMessage.Type to report a value's CBOR major type#805
ChrisJr404 wants to merge 1 commit into
fxamacker:masterfrom
ChrisJr404:rawmessage-type

Conversation

@ChrisJr404

Copy link
Copy Markdown

Description

This adds a Type method to RawMessage so callers can check the outer kind of a raw value without fully decoding it, which is what #440 asked for.

The motivation is the same one from that issue: with json.RawMessage you can peek at the first byte to see whether you're looking at an object, array, string, etc., but doing the equivalent with a cbor.RawMessage meant writing a little partial decoder over the initial byte and remembering the CBOR major type encoding. RawMessage.Type() reads the major type from the initial byte and returns it as an exported Type value, so branching on the kind is a one-liner:

switch t, _ := raw.Type(); t {
case cbor.TypeArray:
    // ...
case cbor.TypeMap:
    // ...
}

The exported Type mirrors the major types in RFC 8949 Section 3.1, and its String() reuses the descriptions the package already had internally so there's no second copy of that mapping to keep in sync. Type() only looks at the initial byte and deliberately does not check well-formedness, so it stays cheap and has no effect on anyone not calling it; callers that need validation can still use Wellformed. It returns an error when the message is empty.

PR Was Proposed and Welcomed in Currently Open Issue

Checklist (for code PR only, ignore for docs PR)

  • Include unit tests that cover the new code
  • Pass all unit tests
  • Pass all lint checks in CI (goimports, gosec, staticcheck, etc.)
  • Sign each commit with your real name and email.
  • Certify the Developer's Certificate of Origin 1.1

Certify the Developer's Certificate of Origin 1.1

  • By marking this item as completed, I certify the Developer Certificate of Origin 1.1.

Inspecting the outer kind of a cbor.RawMessage previously required either
decoding it into a Go value or hand-rolling a partial decoder over the
initial byte. Add a Type method that returns the CBOR major type read from
the initial byte, mirroring the way the first byte of a json.RawMessage can
be inspected to branch on its kind, along with an exported Type enum and a
String method that reuses the existing type descriptions.

Type only looks at the initial byte and does not verify well-formedness, so
it stays cheap; callers that need validation can still use Wellformed.

Closes fxamacker#440.

Signed-off-by: Chris (ChrisJr404) <11917633+ChrisJr404@users.noreply.github.com>
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

Successfully merging this pull request may close these issues.

1 participant