Skip to content

Commit

Permalink
Add yaml marhsaller/unmarshaller
Browse files Browse the repository at this point in the history
  • Loading branch information
leighmacdonald committed Mar 19, 2024
1 parent d178ab8 commit 442a745
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
17 changes: 17 additions & 0 deletions steamid/steamid.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ import (
"strings"
"sync/atomic"
"time"

"gopkg.in/yaml.v3"
)

const (
Expand Down Expand Up @@ -522,6 +524,21 @@ func (t *SteamID) UnmarshalJSON(data []byte) error {
return nil
}

// MarshalText implements encoding.TextMarshaler which is used by the yaml package for marshalling
func (t *SteamID) MarshalText() ([]byte, error) {
return []byte(t.String()), nil
}

// UnmarshalYAML implements the yaml.Unmarshaler interface for steam ids.
func (t *SteamID) UnmarshalYAML(node *yaml.Node) error {
sid := New(node.Value)
if !sid.Valid() {
return ErrInvalidSID
}
*t = sid
return nil
}

// SID32 represents a Steam32
// 172346362.
type SID32 uint32
Expand Down
30 changes: 30 additions & 0 deletions steamid/steamid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"os"
"testing"

"gopkg.in/yaml.v3"

"github.com/leighmacdonald/steamid/v4/steamid"
"github.com/stretchr/testify/require"
)
Expand Down Expand Up @@ -125,6 +127,34 @@ func TestJSON(t *testing.T) {
require.Equal(t, expectedGID.Int64(), r.GID.Int64())
}

func TestYAML(t *testing.T) {
t.Parallel()

type testFormats struct {
Quoted steamid.SteamID `yaml:"quoted"`
}

var out testFormats
require.NoError(t, yaml.Unmarshal([]byte(`{"quoted":"76561197970669109"}`), &out))

expected := steamid.New(76561197970669109)
require.Equal(t, expected, out.Quoted, "Quoted value invalid")

body, errMarshal := yaml.Marshal(&expected)
require.NoError(t, errMarshal)
require.Equal(t, []byte("\"76561197970669109\"\n"), body)

type testGIDResp struct {
GID steamid.SteamID `json:"gid"`
}

var r testGIDResp
require.NoError(t, yaml.Unmarshal([]byte(`{"gid":"103582791441572968"}`), &r))
expectedGID := steamid.New(103582791441572968)

require.Equal(t, expectedGID.Int64(), r.GID.Int64())
}

func TestResolveGID(t *testing.T) {
t.Parallel()

Expand Down

0 comments on commit 442a745

Please sign in to comment.