Skip to content

Commit

Permalink
Merge pull request #12 from manicar2093/fix/recognize-empty-from-unma…
Browse files Browse the repository at this point in the history
…rshall

fix: recognize empty from unmarshall
  • Loading branch information
manicar2093 authored May 24, 2024
2 parents d671c2f + 7f4926f commit 0eb9b9e
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 6 deletions.
8 changes: 6 additions & 2 deletions goption.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@ func Empty[T any]() Optional[T] {

// Of returns an Optional with the specified present value. It does not matters if value is nil
func Of[T any](value T) Optional[T] {
_, isValid := isValidData(value)
return Optional[T]{value: value, isValidValue: isValid}
return Optional[T]{value: value, isValidValue: getIsValidDataBool(value)}
}

// Get when a value is present returns the value, otherwise throws ErrNoSuchElement.
Expand Down Expand Up @@ -80,3 +79,8 @@ func isValidData[T any](value T) (reflect.Value, bool) {
return val, !val.IsZero()
}
}

func getIsValidDataBool[T any](value T) bool {
_, is := isValidData(value)
return is
}
12 changes: 8 additions & 4 deletions json.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,18 @@ package goption
import (
"encoding/json"
"reflect"
"strconv"
)

func (c *Optional[T]) UnmarshalJSON(data []byte) error {
if string(data) == `"null"` {
c.isValidValue = false
return nil
unquoted, err := strconv.Unquote(string(data))
if err != nil {
return err
}
if unquoted == "null" {
unquoted = ""
}
c.isValidValue = len(data) > 0
c.isValidValue = getIsValidDataBool(unquoted)
if err := json.Unmarshal(data, &c.value); err != nil {
return err
}
Expand Down
13 changes: 13 additions & 0 deletions json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,19 @@ var _ = Describe("Json", func() {
Expect(holder.IsPresent()).To(BeFalse())
})
})

When("is zero", func() {
It("creates an empty optional", func() {
var (
jsonData = []byte(`""`)
holder = goption.Empty[string]()
)
err := holder.UnmarshalJSON(jsonData)

Expect(err).ToNot(HaveOccurred())
Expect(holder.IsPresent()).To(BeFalse())
})
})
})

Describe("MarshalJson", func() {
Expand Down

0 comments on commit 0eb9b9e

Please sign in to comment.