Skip to content

Commit c785a7f

Browse files
committed
Added ParsePrimitiveValue convenience function for users
1 parent 56ced5d commit c785a7f

File tree

2 files changed

+182
-79
lines changed

2 files changed

+182
-79
lines changed

parser.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -477,3 +477,32 @@ func unsafeBytesToString(data []byte) string {
477477
sh := reflect.StringHeader{Data: h.Data, Len: h.Len}
478478
return *(*string)(unsafe.Pointer(&sh))
479479
}
480+
481+
// ParseBoolean parses a Boolean ValueType into a Go bool (not particularly useful, but here for completeness)
482+
func ParseBoolean(vbytes []byte) bool {
483+
return (vbytes[0] == 't') // assumes value is already validated by Get(), etc. as signaled by jtype == Boolean
484+
}
485+
486+
// ParseString parses a String ValueType into a Go []byte (the main parsing work is unescaping the JSON string)
487+
func ParseStringAsBytes(vbytes []byte) ([]byte, error) {
488+
var stackbuf [unescapeStackBufSize]byte // stack-allocated array for allocation-free unescaping of small strings (hopefully; the Go compiler might just always kick stackbuf[:] into the heap)
489+
return Unescape(vbytes, stackbuf[:])
490+
}
491+
492+
// ParseString parses a String ValueType into a Go string (the main parsing work is unescaping the JSON string)
493+
func ParseString(vbytes []byte) (string, error) {
494+
if vbytesUnesc, err := ParseStringAsBytes(vbytes); err != nil {
495+
return "", nil
496+
} else {
497+
return string(vbytesUnesc), nil
498+
}
499+
}
500+
501+
// ParseNumber parses a Number ValueType into a Go float64
502+
func ParseNumber(vbytes []byte) (float64, error) {
503+
if v, err := strconv.ParseFloat(unsafeBytesToString(vbytes), 64); err != nil { // TODO: use better BytesParseFloat in PR #25
504+
return 0, MalformedValueError
505+
} else {
506+
return v, nil
507+
}
508+
}

0 commit comments

Comments
 (0)