Skip to content

Commit

Permalink
docs(examples): add Num
Browse files Browse the repository at this point in the history
  • Loading branch information
ernado committed Nov 5, 2021
1 parent 397189e commit 876d2c0
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 1 deletion.
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,41 @@ fmt.Println(raw.Type(), raw)
// array [1, 2, 3]
```

## Number

Use [jx.Decoder.Num](https://pkg.go.dev/github.com/ogen-go/jx#Decoder.Num) to read numbers, similar to `json.Number`.
Also supports string numbers, like `"12345"`, which is common js-compatible way to represent `uint64`.

```go
d := jx.DecodeStr(`{"foo": "10531.0"}`)

var n jx.Num
if err := d.Obj(func(d *jx.Decoder, key string) error {
v, err := d.Num()
if err != nil {
return err
}
n = v
return nil
}); err != nil {
panic(err)
}

fmt.Println(n)
fmt.Println("positive:", n.Positive())

// Can decode floats with zero fractional part as integers:
v, err := n.Int64()
if err != nil {
panic(err)
}
fmt.Println("int64:", v)
// Output:
// "10531.0"
// positive: true
// int64: 10531
```

## Validate

Check that byte slice is valid json with [jx.Valid](https://pkg.go.dev/github.com/ogen-go/jx#Valid):
Expand Down
31 changes: 31 additions & 0 deletions examples_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,3 +106,34 @@ func ExampleDecoder_Raw() {
// Output:
// array [1, 2, 3]
}

func ExampleDecoder_Num() {
// Can decode numbers and number strings.
d := jx.DecodeStr(`{"foo": "10531.0"}`)

var n jx.Num
if err := d.Obj(func(d *jx.Decoder, key string) error {
v, err := d.Num()
if err != nil {
return err
}
n = v
return nil
}); err != nil {
panic(err)
}

fmt.Println(n)
fmt.Println("positive:", n.Positive())

// Can decode floats with zero fractional part as integers:
v, err := n.Int64()
if err != nil {
panic(err)
}
fmt.Println("int64:", v)
// Output:
// "10531.0"
// positive: true
// int64: 10531
}
9 changes: 8 additions & 1 deletion num.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,14 @@ import (
type Num []byte

func (n Num) dec() Decoder {
head := 0
if n.Str() {
head = 1
}
return Decoder{
buf: n,
tail: len(n),
head: head,
}
}

Expand All @@ -34,7 +39,9 @@ func (n Num) floatAsInt() error {
if !dot {
continue
}
if c != '0' {
switch c {
case '0', '"': // ok
default:
return errors.Wrap(badToken(c), "non-zero fractional part")
}
}
Expand Down

0 comments on commit 876d2c0

Please sign in to comment.