2023-09-23 00:29:41 +00:00
package opt
import (
2024-08-08 17:58:13 +00:00
"encoding"
"fmt"
"reflect"
2024-07-04 16:54:41 +00:00
"github.com/reiver/go-erorr"
2024-08-09 03:27:27 +00:00
"github.com/reiver/go-json"
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 ) {
2024-08-08 17:58:13 +00:00
case json . Marshaler , encoding . TextMarshaler , bool , int , int8 , int16 , int32 , int64 , string , uint , uint8 , uint16 , uint32 , uint64 :
2023-09-23 20:44:37 +00:00
// these are OK.
default :
2024-08-08 17:58:13 +00:00
var reflectedType reflect . Type = reflect . TypeOf ( receiver . value )
if nil == reflectedType {
return nil , errBadReflection
}
if reflect . Struct != reflectedType . Kind ( ) {
return nil , erorr . Errorf ( "opt: cannot marshal something of type %T into JSON because parameterized type is ‘ %T’ is not supported" , receiver , receiver . value )
}
2023-09-23 20:44:37 +00:00
}
2024-06-16 14:03:11 +00:00
if receiver . IsNothing ( ) {
2024-08-08 17:58:13 +00:00
return nil , json . ErrEmpty ( fmt . Sprintf ( "opt: cannot marshal opt.Nothing[%T]() into JSON" , receiver . value ) )
2023-09-23 00:29:41 +00:00
}
return json . Marshal ( receiver . value )
}