Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion cm/list.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package cm

import "unsafe"
import (
"encoding/json"
"unsafe"
)

// List represents a Component Model list.
// The binary representation of list<T> is similar to a Go slice minus the cap field.
Expand All @@ -9,6 +12,20 @@ type List[T any] struct {
list[T]
}

func (l List[T]) MarshalJSON() ([]byte, error) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These methods should be on the inner list[T] struct.

return json.Marshal(l.Slice())
}

func (l *List[T]) UnmarshalJSON(buf []byte) error {
var data []T
err := json.Unmarshal(buf, &data)
if err != nil {
return err
}
*l = ToList(data)
return nil
}

// AnyList is a type constraint for generic functions that accept any [List] type.
type AnyList[T any] interface {
~struct {
Expand Down
25 changes: 25 additions & 0 deletions cm/option.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package cm

import (
"encoding/json"
)

// Option represents a Component Model [option<T>] type.
//
// [option<T>]: https://component-model.bytecodealliance.org/design/wit.html#options
Expand All @@ -8,6 +12,27 @@ type Option[T any] struct {
option[T]
}

// MarshalJSON implements the json.Marshaler interface for [Option].
func (o Option[T]) MarshalJSON() ([]byte, error) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These methods should be on the inner struct.

return json.Marshal(o.Some())
}

// UnmarshalJSON unmarshals the Option from JSON.
func (o *Option[T]) UnmarshalJSON(buf []byte) error {
if len(buf) == 0 {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should also check if buf == null.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 the null story here is interesting. will push it up as part of the breaking this PR into many

*o = None[T]()
return nil
}

var v T
if err := json.Unmarshal(buf, &v); err != nil {
return err
}

*o = Some(v)
return nil
}

// None returns an [Option] representing the none case,
// equivalent to the zero value.
func None[T any]() Option[T] {
Expand Down
Loading