2023-09-23 00:29:41 +00:00
package opt
import (
"encoding/json"
2023-09-27 00:43:16 +00:00
2024-07-04 16:54:41 +00:00
"github.com/reiver/go-erorr"
2023-09-23 00:29:41 +00:00
)
2023-09-23 20:44:37 +00:00
var _ json . Marshaler = Nothing [ bool ] ( )
var _ json . Marshaler = Nothing [ string ] ( )
2023-09-23 00:29:41 +00:00
// MarshalJSON makes it so json.Marshaler is implemented.
2023-09-23 20:44:37 +00:00
func ( receiver Optional [ T ] ) MarshalJSON ( ) ( [ ] byte , error ) {
switch interface { } ( receiver . value ) . ( type ) {
2023-09-25 02:35:13 +00:00
case bool , string , json . Marshaler :
2023-09-23 20:44:37 +00:00
// these are OK.
default :
2023-09-27 00:43:16 +00:00
return nil , erorr . Errorf ( "opt: 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-23 20:44:37 +00:00
}
2024-06-16 14:03:11 +00:00
if receiver . IsNothing ( ) {
2023-09-27 00:43:16 +00:00
return nil , erorr . Errorf ( "opt: cannot marshal opt.Nothing[%T]() into JSON" , receiver . value )
2023-09-23 00:29:41 +00:00
}
return json . Marshal ( receiver . value )
}