2023-09-24 00:40:03 +00:00
package nul
import (
"encoding/json"
2023-09-27 00:48:15 +00:00
"sourcecode.social/reiver/go-erorr"
2023-09-24 00:40:03 +00:00
)
var _ json . Marshaler = Nothing [ bool ] ( )
var _ json . Marshaler = Nothing [ string ] ( )
// MarshalJSON makes it so json.Marshaler is implemented.
func ( receiver Nullable [ T ] ) MarshalJSON ( ) ( [ ] byte , error ) {
switch interface { } ( receiver . value ) . ( type ) {
2023-09-27 00:48:15 +00:00
case bool , string , json . Marshaler :
2023-09-24 00:40:03 +00:00
// these are OK.
default :
2023-09-27 00:48:15 +00:00
return nil , erorr . Errorf ( "nul: cannot marshal something of type %T into JSON because parameterized type is ‘ %T’ rather than ‘ bool’ , ‘ string’ , or ‘ json.Marshaler’ " , receiver , receiver . value )
2023-09-24 00:40:03 +00:00
}
if receiver . isnothing ( ) {
2023-09-27 00:48:15 +00:00
return nil , erorr . Errorf ( "nul: cannot marshal opt.Nothing[%T]() into JSON" , receiver . value )
2023-09-24 00:40:03 +00:00
}
if receiver . isnull {
return json . Marshal ( nil )
}
return json . Marshal ( receiver . value )
}