-
Notifications
You must be signed in to change notification settings - Fork 20
wit/bindgen,cm: marshal & unmarshal for record types #225
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
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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 | ||
|
|
@@ -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) { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This should also check if buf ==
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 👍 the |
||
| *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] { | ||
|
|
||
There was a problem hiding this comment.
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.