Compare commits

..

No commits in common. "a8488bd6fb127f25c3f995d7c887fd366a23a8bb" and "3f808e974991c017f323157c718e23d91ae1a17b" have entirely different histories.

2 changed files with 6 additions and 127 deletions

View File

@ -5,20 +5,14 @@ import (
"encoding/json"
)
var _ json.Marshaler = Nothing[bool]()
var _ json.Marshaler = Nothing[string]()
// MarshalJSON makes it so json.Marshaler is implemented.
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)
type jsonMarshaler interface {
bool | string
}
if receiver.isnothing() {
return nil, fmt.Errorf("cannot marshal opt.Nothing[%T]() into JSON", receiver.value)
// 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)
}
return json.Marshal(receiver.value)

View File

@ -1,115 +0,0 @@
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
}
}