Skip to content

Commit

Permalink
feat: added RawValue interface (zserge#127)
Browse files Browse the repository at this point in the history
* feat: added RawValue interface

To allow for the detection of a `nil` return, a new interface is added (to maintain backwards compatibility) and implemented by `value`. This interface, `RawValue`, allows the retrieval of the raw bytes but requires a type assertion.

* fix: add bytes to Value

* fix: use bytes for test
  • Loading branch information
nrwiersma committed Mar 19, 2021
1 parent 4161d59 commit 4d6397d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
2 changes: 2 additions & 0 deletions value.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ type Value interface {
Bool() bool
Object() map[string]Value
Array() []Value
Bytes() []byte
}

type value struct {
Expand All @@ -21,6 +22,7 @@ type value struct {
}

func (v value) Err() error { return v.err }
func (v value) Bytes() []byte { return v.raw }
func (v value) To(x interface{}) error { return json.Unmarshal(v.raw, x) }
func (v value) Float() (f float32) { v.To(&f); return f }
func (v value) Int() (i int) { v.To(&i); return i }
Expand Down
15 changes: 15 additions & 0 deletions value_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package lorca

import (
"bytes"
"encoding/json"
"errors"
"testing"
Expand Down Expand Up @@ -50,3 +51,17 @@ func TestValueComplex(t *testing.T) {
t.Fail()
}
}

func TestRawValue(t *testing.T) {
var v Value

v = value{raw: json.RawMessage(nil)}
if v.Bytes() != nil {
t.Fail()
}

v = value{raw: json.RawMessage(`"hello"`)}
if !bytes.Equal(v.Bytes(), []byte(`"hello"`)) {
t.Fail()
}
}

0 comments on commit 4d6397d

Please sign in to comment.