Skip to content

Commit

Permalink
DID implements Scanner and Valuer interfaces (#161)
Browse files Browse the repository at this point in the history
* Implement Scanner and Valuer interfaces

* lint
  • Loading branch information
tomdaffurn authored Aug 1, 2024
1 parent 24a79d9 commit d927bc2
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
22 changes: 22 additions & 0 deletions dids/did/did.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package did

import (
"database/sql/driver"
"errors"
"fmt"
"regexp"
"strings"
)
Expand Down Expand Up @@ -65,6 +67,26 @@ func (d *DID) UnmarshalText(text []byte) error {
return nil
}

// Scan implements the Scanner interface
func (d *DID) Scan(src any) error {
switch obj := src.(type) {
case nil:
return nil
case string:
if src == "" {
return nil
}
return d.UnmarshalText([]byte(obj))
default:
return fmt.Errorf("unsupported scan type %T", obj)
}
}

// Value implements the driver Valuer interface
func (d DID) Value() (driver.Value, error) {
return d.String(), nil
}

// relevant ABNF rules: https://www.w3.org/TR/did-core/#did-syntax
var (
pctEncodedPattern = `(?:%[0-9a-fA-F]{2})`
Expand Down
56 changes: 56 additions & 0 deletions dids/did/did_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,59 @@ func TestParse(t *testing.T) {
}
}
}

func TestDID_ScanValueRoundtrip(t *testing.T) {
tests := []struct {
object did.DID
raw string
wantErr bool
}{
{
raw: "did:example:123456789abcdefghi",
object: MustParse("did:example:123456789abcdefghi"),
},
{
raw: "did:example:123456789abcdefghi;foo=bar;baz=qux",
object: MustParse("did:example:123456789abcdefghi;foo=bar;baz=qux"),
},
{
raw: "did:example:123456789abcdefghi?foo=bar&baz=qux",
object: MustParse("did:example:123456789abcdefghi?foo=bar&baz=qux"),
},
{
raw: "did:example:123456789abcdefghi#keys-1",
object: MustParse("did:example:123456789abcdefghi#keys-1"),
},
{
raw: "did:example:123456789abcdefghi?foo=bar&baz=qux#keys-1",
object: MustParse("did:example:123456789abcdefghi?foo=bar&baz=qux#keys-1"),
},
{
raw: "did:example:123456789abcdefghi;foo=bar;baz=qux?foo=bar&baz=qux#keys-1",
object: MustParse("did:example:123456789abcdefghi;foo=bar;baz=qux?foo=bar&baz=qux#keys-1"),
},
}
for _, tt := range tests {
t.Run(tt.raw, func(t *testing.T) {
var d did.DID
if err := d.Scan(tt.raw); (err != nil) != tt.wantErr {
t.Errorf("Scan() error = %v, wantErr %v", err, tt.wantErr)
}
assert.Equal(t, tt.object, d)

value, err := d.Value()
assert.NoError(t, err)
actual, ok := value.(string)
assert.True(t, ok)
assert.Equal(t, tt.raw, actual)
})
}
}

func MustParse(input string) did.DID {
d, err := did.Parse(input)
if err != nil {
panic(err)
}
return d
}

0 comments on commit d927bc2

Please sign in to comment.