github.com/go-email-validator/go-email-validator@v0.0.0-20230409163946-b8b9e6a0552e/pkg/presentation/mailboxvalidator/nullable_bool.go (about)

     1  package mailboxvalidator
     2  
     3  import (
     4  	"encoding/json"
     5  )
     6  
     7  const (
     8  	// MBVTrue is "true" in the return
     9  	MBVTrue = "True"
    10  	// MBVFalse is "False" in the return
    11  	MBVFalse = "False"
    12  	// MBVEmpty is "" in the return
    13  	MBVEmpty = ""
    14  )
    15  
    16  // EmptyBool is a type for mailboxvalidator bool
    17  type EmptyBool struct {
    18  	*bool
    19  }
    20  
    21  // NewEmptyBool create EmptyBool with bool
    22  func NewEmptyBool(boolean bool) EmptyBool {
    23  	return EmptyBool{
    24  		bool: &boolean,
    25  	}
    26  }
    27  
    28  // NewEmptyBoolWithNil create EmptyBool with nil
    29  func NewEmptyBoolWithNil() EmptyBool {
    30  	return EmptyBool{
    31  		bool: nil,
    32  	}
    33  }
    34  
    35  // ToBool returns boolean value
    36  func (e EmptyBool) ToBool() bool {
    37  	if e.bool == nil {
    38  		return false
    39  	}
    40  
    41  	return *e.bool
    42  }
    43  
    44  // UnmarshalJSON implements json.UnmarshalJSON
    45  func (e *EmptyBool) UnmarshalJSON(data []byte) error {
    46  	err := json.Unmarshal(data, &e.bool)
    47  
    48  	return err
    49  }
    50  
    51  // MarshalJSON implements json.Marshaler
    52  func (e *EmptyBool) MarshalJSON() ([]byte, error) {
    53  	return json.Marshal(e.bool)
    54  }
    55  
    56  // ToString converts bool to string
    57  func (e EmptyBool) ToString() string {
    58  	if e.bool == nil {
    59  		return ""
    60  	}
    61  
    62  	if *e.bool {
    63  		return MBVTrue
    64  	}
    65  	return MBVFalse
    66  }
    67  
    68  // ToBool converts string to bool
    69  func ToBool(value string) (result EmptyBool) {
    70  	if value == MBVEmpty {
    71  		return
    72  	}
    73  
    74  	boolean := value == MBVTrue
    75  	return EmptyBool{&boolean}
    76  }