github.com/cloudfoundry-community/cloudfoundry-cli@v6.44.1-0.20240130060226-cda5ed8e89a5+incompatible/types/optional_string_slice.go (about)

     1  package types
     2  
     3  import (
     4  	"encoding/json"
     5  	"strings"
     6  )
     7  
     8  type OptionalStringSlice struct {
     9  	IsSet bool
    10  	Value []string
    11  }
    12  
    13  func NewOptionalStringSlice(s ...string) OptionalStringSlice {
    14  	return OptionalStringSlice{
    15  		IsSet: true,
    16  		Value: s,
    17  	}
    18  }
    19  
    20  func (o *OptionalStringSlice) UnmarshalJSON(rawJSON []byte) error {
    21  	var receiver []string
    22  	if err := json.Unmarshal(rawJSON, &receiver); err != nil {
    23  		return err
    24  	}
    25  
    26  	// This ensures that the empty state is always a nil slice, not an allocated (but empty) slice
    27  	switch len(receiver) {
    28  	case 0:
    29  		o.Value = nil
    30  	default:
    31  		o.Value = receiver
    32  	}
    33  
    34  	o.IsSet = true
    35  	return nil
    36  }
    37  
    38  func (o OptionalStringSlice) MarshalJSON() ([]byte, error) {
    39  	if len(o.Value) > 0 {
    40  		return json.Marshal(o.Value)
    41  	}
    42  
    43  	return []byte(`[]`), nil
    44  }
    45  
    46  func (o OptionalStringSlice) OmitJSONry() bool {
    47  	return !o.IsSet
    48  }
    49  
    50  func (o OptionalStringSlice) String() string {
    51  	return strings.Join(o.Value, ", ")
    52  }