Skip to content

Commit

Permalink
Make Deck satisfy the sql.Scanner interface
Browse files Browse the repository at this point in the history
  • Loading branch information
zchenyu committed May 18, 2022
1 parent d75c73a commit 2c93564
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 4 deletions.
22 changes: 18 additions & 4 deletions card.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package cards

import (
"errors"
)

type Card int32

var (
Expand Down Expand Up @@ -53,22 +57,32 @@ func NewCard(s string) Card {

func NewCards(s string) []Card {
cards := []Card{}
for i := 0; i < len(s); i += 2 {
cards = append(cards, NewCard(s[i:i+2]))
}
return cards
for i := 0; i < len(s); i += 2 {
cards = append(cards, NewCard(s[i:i+2]))
}
return cards
}

func (c Card) MarshalText() ([]byte, error) {
return []byte(c.String()), nil
}

func (c *Card) UnmarshalText(text []byte) error {
if len(text) != 2 {
return errors.New("must have len 2")
}
*c = NewCard(string(text))
// TODO: validate
return nil
}

func (c Card) MarshalJSON() ([]byte, error) {
return []byte("\"" + c.String() + "\""), nil
}

func (c *Card) UnmarshalJSON(b []byte) error {
*c = NewCard(string(b[1:3]))
// TODO: validate
return nil
}

Expand Down
7 changes: 7 additions & 0 deletions card_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,13 @@ func TestMarshalText(t *testing.T) {
assert.Equal(t, "Ah", string(b))
}

func TestUnmarshalText(t *testing.T) {
var c Card
assert.Nil(t, c.UnmarshalText([]byte("Ah")))
assert.Equal(t, NewCard("Ah"), c)
assert.Error(t, c.UnmarshalText([]byte("Ahh")), "must have len 2")
}

func TestMarshalJSON(t *testing.T) {
cards := []Card{
NewCard("Ah"),
Expand Down
21 changes: 21 additions & 0 deletions deck.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package cards

import (
"errors"
"fmt"
"math/rand"
"time"
)
Expand Down Expand Up @@ -62,6 +64,25 @@ func (deck *Deck) Empty() bool {
return len(deck.cards) == 0
}

// Scan implements the Scanner interface.
func (deck *Deck) Scan(src interface{}) error {
switch v := src.(type) {
case string:
if len(v)%2 != 0 {
return errors.New("string must have even length")
}
deck.cards = make([]Card, len(v)/2)
for i := 0; i < len(v); i += 2 {
if err := deck.cards[i/2].UnmarshalText([]byte(v)); err != nil {
return fmt.Errorf("Could not unmarshal card '%s': %v", v[i:i+2], err)
}
}
return nil
default:
return errors.New("must be `string` type")
}
}

func initializeFullCards() []Card {
var cards []Card

Expand Down

0 comments on commit 2c93564

Please sign in to comment.