Skip to content

cm: implement JSON [un]marshaling for Option types #301

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
24 changes: 24 additions & 0 deletions cm/option.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
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 Down Expand Up @@ -57,3 +59,25 @@ func (o option[T]) Value() T {
}
return o.some
}

// MarshalJSON implements the json.Marshaler interface.
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.

Methods should be on option[T] so named option types inherit the methods.

Copy link
Author

Choose a reason for hiding this comment

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

Is there an example I can follow for a named option type? I assumed that if external implementations named a type it would be for Option[T], perhaps I should implement the un/marshaling for both?

Copy link
Collaborator

Choose a reason for hiding this comment

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

// This type would not have the JSON methods.
type OptionalI32 cm.Option[int32]

This is why the methods are implemented on option, which is embedded in Option, so methods are preserved.

Copy link
Author

@brooksmtownsend brooksmtownsend Mar 11, 2025

Choose a reason for hiding this comment

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

@ydnar added a few more test cases that show that this works for named and nested options 🫡

I did find that I could remove the Option[T].MarshalJSON implementation and still have tests work, but removing Option[T].UnmarshalJSON did fail the cases that we have, so I left both in.

Copy link
Collaborator

Choose a reason for hiding this comment

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

This is not necessary.

if !o.isSome {
return json.Marshal(nil)
}
return json.Marshal(o.Some())
}

// UnmarshalJSON implements the json.Unmarshaler interface.
func (o *Option[T]) UnmarshalJSON(data []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.

This is not necessary.

if string(data) == "null" {
*o = None[T]()
return nil
}
var v T
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*o = Some(v)
return nil
}
62 changes: 61 additions & 1 deletion cm/option_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package cm

import "testing"
import (
"encoding/json"
"testing"
)

func TestOption(t *testing.T) {
o1 := None[string]()
Expand Down Expand Up @@ -65,3 +68,60 @@ func TestOption(t *testing.T) {
t.Errorf("Value: %v, expected %v", got, want)
}
}

func TestOptionMarshalJSON(t *testing.T) {
type TestStruct struct {
Field Option[string] `json:"field"`
}

// Test marshaling None
ts1 := TestStruct{Field: None[string]()}
data1, err := json.Marshal(ts1)
if err != nil {
t.Fatalf("json.Marshal failed: %v", err)
}
expected1 := `{"field":null}`
if string(data1) != expected1 {
t.Errorf("json.Marshal: got %s, expected %s", data1, expected1)
}

// Test marshaling Some
ts2 := TestStruct{Field: Some("hello")}
data2, err := json.Marshal(ts2)
if err != nil {
t.Fatalf("json.Marshal failed: %v", err)
}
expected2 := `{"field":"hello"}`
if string(data2) != expected2 {
t.Errorf("json.Marshal: got %s, expected %s", data2, expected2)
}
}

func TestOptionUnmarshalJSON(t *testing.T) {
type TestStruct struct {
Field Option[string] `json:"field"`
}

// Test unmarshaling None
data1 := []byte(`{"field":null}`)
var ts1 TestStruct
if err := json.Unmarshal(data1, &ts1); err != nil {
t.Fatalf("json.Unmarshal failed: %v", err)
}
if got, want := ts1.Field.None(), true; got != want {
t.Errorf("ts1.Field.None: %t, expected %t", got, want)
}

// Test unmarshaling Some
data2 := []byte(`{"field":"hello"}`)
var ts2 TestStruct
if err := json.Unmarshal(data2, &ts2); err != nil {
t.Fatalf("json.Unmarshal failed: %v", err)
}
if got, want := ts2.Field.isSome, true; got != want {
t.Errorf("ts2.Field.Some: %t, expected %t", got, want)
}
if got, want := ts2.Field.Value(), "hello"; got != want {
t.Errorf("ts2.Field.Value: %v, expected %v", got, want)
}
}