Skip to content

Commit

Permalink
add json support to Pointer (#180)
Browse files Browse the repository at this point in the history
* add json support to Pointer
* update changelog
* coverage
  • Loading branch information
trim21 authored Aug 6, 2024
1 parent e9f70be commit 8768b7d
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 3 deletions.
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## Unreleased
- No changes yet.
### Added
- Add `MarshalJSON` and `UnmarshalJSON` method to `atomic.Pointer[T]` type
allowing users to use pointer with json.

## [1.11.0] - 2023-05-02
### Fixed
Expand Down
20 changes: 19 additions & 1 deletion pointer_go118.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,27 @@

package atomic

import "fmt"
import (
"encoding/json"
"fmt"
)

// String returns a human readable representation of a Pointer's underlying value.
func (p *Pointer[T]) String() string {
return fmt.Sprint(p.Load())
}

// MarshalJSON encodes the wrapped pointer into JSON.
func (p *Pointer[T]) MarshalJSON() ([]byte, error) {
return json.Marshal(p.Load())
}

// UnmarshalJSON decodes JSON into the wrapped pointer.
func (p *Pointer[T]) UnmarshalJSON(b []byte) error {
var v T
if err := json.Unmarshal(b, &v); err != nil {
return err
}
p.Store(&v)
return nil
}
27 changes: 26 additions & 1 deletion pointer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,17 @@
package atomic

import (
"encoding/json"
"fmt"
"testing"

"github.com/stretchr/testify/require"
)

func TestPointer(t *testing.T) {
type foo struct{ v int }
type foo struct {
V int `json:"v"`
}

i := foo{42}
j := foo{0}
Expand Down Expand Up @@ -94,6 +97,28 @@ func TestPointer(t *testing.T) {
atom := tt.newAtomic()
require.Equal(t, fmt.Sprint(tt.initial), atom.String(), "String did not return the correct value.")
})

t.Run("MarshalJSON", func(t *testing.T) {
atom := tt.newAtomic()
marshaledPointer, err := json.Marshal(atom)
require.NoError(t, err)
marshaledRaw, err := json.Marshal(tt.initial)
require.NoError(t, err)
require.Equal(t, marshaledRaw, marshaledPointer, "MarshalJSON did not return the correct value.")
})
})
}

t.Run("UnmarshalJSON", func(t *testing.T) {
var p Pointer[foo]

require.NoError(t, json.Unmarshal([]byte(`{"v":1024}`), &p))
require.Equal(t, 1024, p.Load().V, "UnmarshalJSON should have expected result")
})

t.Run("UnmarshalJSON error", func(t *testing.T) {
var p Pointer[foo]

require.Error(t, json.Unmarshal([]byte(`{"v":true}`), &p), "json.Unmarshal should return an error")
})
}

0 comments on commit 8768b7d

Please sign in to comment.