Compare commits

..

2 Commits

2 changed files with 127 additions and 6 deletions

View File

@ -5,14 +5,20 @@ import (
"encoding/json"
)
type jsonMarshaler interface {
bool | string
}
var _ json.Marshaler = Nothing[bool]()
var _ json.Marshaler = Nothing[string]()
// MarshalJSON makes it so json.Marshaler is implemented.
func (receiver Optional[jsonMarshal]) MarshalJSON() ([]byte, error) {
if !receiver.something {
return nil, fmt.Errorf("cannot marshal opt.Nothing[%T]()", receiver.value)
func (receiver Optional[T]) MarshalJSON() ([]byte, error) {
switch interface{}(receiver.value).(type) {
case bool, string:
// these are OK.
default:
return nil, fmt.Errorf("cannot marshal something of type %T into JSON because parameterized type is %T rather than bool or string", receiver, receiver.value)
}
if receiver.isnothing() {
return nil, fmt.Errorf("cannot marshal opt.Nothing[%T]() into JSON", receiver.value)
}
return json.Marshal(receiver.value)

View File

@ -0,0 +1,115 @@
package opt_test
import (
"testing"
"sourcecode.social/reiver/go-opt"
)
func TestOptional_MarshalJSON_int(t *testing.T) {
tests := []struct{
Value opt.Optional[int]
}{
{
Value: opt.Something(-65536),
},
{
Value: opt.Something(-65535),
},
{
Value: opt.Something(-256),
},
{
Value: opt.Something(-255),
},
{
Value: opt.Something(-5),
},
{
Value: opt.Something(-4),
},
{
Value: opt.Something(-3),
},
{
Value: opt.Something(-2),
},
{
Value: opt.Something(-1),
},
{
Value: opt.Something(0),
},
{
Value: opt.Something(1),
},
{
Value: opt.Something(2),
},
{
Value: opt.Something(3),
},
{
Value: opt.Something(4),
},
{
Value: opt.Something(5),
},
{
Value: opt.Something(255),
},
{
Value: opt.Something(256),
},
{
Value: opt.Something(65535),
},
{
Value: opt.Something(65536),
},
}
for testNumber, test := range tests {
actualBytes, err := test.Value.MarshalJSON()
if nil == err {
t.Errorf("For test #%d, expected an error but did not actually get one." , testNumber)
t.Logf("ACTUAL BYTES: %q", actualBytes)
t.Logf("ERROR: (%T) %s", err, err)
t.Logf("VALUE: %#v", test.Value)
continue
}
}
}
func TestOptional_MarshalJSON_int_fail(t *testing.T) {
var nothing opt.Optional[int]
actualBytes, err := nothing.MarshalJSON()
if nil == err {
t.Error("Expected an error but did not actually get one.")
t.Logf("ACTUAL: %q", actualBytes)
t.Logf("ERROR: (%T) %s", err, err)
return
}
if nil != actualBytes {
t.Error("Expected not bytes but actually get some.")
t.Logf("ACTUAL: %q", actualBytes)
t.Logf("ERROR: (%T) %s", err, err)
return
}
}