Skip to content

Commit

Permalink
feat: add unit result type
Browse files Browse the repository at this point in the history
  • Loading branch information
alanshaw authored and hannahhoward committed Oct 22, 2024
1 parent 175193f commit f12c0d0
Show file tree
Hide file tree
Showing 4 changed files with 85 additions and 0 deletions.
31 changes: 31 additions & 0 deletions core/result/ok/datamodel/unit.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package datamodel

import (
// to use go:embed
_ "embed"
"fmt"

"github.com/ipld/go-ipld-prime"
"github.com/ipld/go-ipld-prime/schema"
)

//go:embed unit.ipldsch
var unitSchema []byte

var unitType schema.Type

func init() {
ts, err := ipld.LoadSchemaBytes(unitSchema)
if err != nil {
panic(fmt.Errorf("loading unit schema: %w", err))
}
unitType = ts.TypeByName("Unit")
}

func UnitType() schema.Type {
return unitType
}

func Schema() []byte {
return unitSchema
}
1 change: 1 addition & 0 deletions core/result/ok/datamodel/unit.ipldsch
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
type Unit struct {}
21 changes: 21 additions & 0 deletions core/result/ok/unit.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package ok

import (
"github.com/ipld/go-ipld-prime/datamodel"
"github.com/ipld/go-ipld-prime/node/basicnode"
)

// Unit is a success type that can be used when there is no data to return from
// a capability handler.
type Unit struct{}

func (u Unit) ToIPLD() (datamodel.Node, error) {
np := basicnode.Prototype.Any
nb := np.NewBuilder()
ma, err := nb.BeginMap(0)
if err != nil {
return nil, err
}
ma.Finish()
return nb.Build(), nil
}
32 changes: 32 additions & 0 deletions core/result/ok/unit_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package ok

import (
"testing"

"github.com/ipld/go-ipld-prime/datamodel"
"github.com/storacha/go-ucanto/core/ipld/codec/cbor"
udm "github.com/storacha/go-ucanto/core/result/ok/datamodel"
"github.com/stretchr/testify/require"
)

func TestUnit(t *testing.T) {
u := Unit{}
nd, err := u.ToIPLD()
require.NoError(t, err)

// should be represented as a map
require.Equal(t, nd.Kind(), datamodel.Kind_Map)

// should contain no items
it := nd.MapIterator()
require.True(t, it.Done())

bytes, err := cbor.Encode(&u, udm.UnitType())
require.NoError(t, err)

u2 := Unit{}
err = cbor.Decode(bytes, &u2, udm.UnitType())
require.NoError(t, err)

require.Equal(t, u, u2)
}

0 comments on commit f12c0d0

Please sign in to comment.