Merge "pkg/types: add InvertedBool"

This commit is contained in:
mpl 2014-01-23 21:58:12 +00:00 committed by Gerrit Code Review
commit a629124f44
2 changed files with 70 additions and 0 deletions

View File

@ -173,3 +173,24 @@ func (v *varStatReadSeeker) Read(p []byte) (int, error) {
func (v *varStatReadSeeker) Seek(offset int64, whence int) (int64, error) {
return v.rs.Seek(offset, whence)
}
// InvertedBool is a bool that marshals to and from JSON with the opposite of its in-memory value.
type InvertedBool bool
func (ib InvertedBool) MarshalJSON() ([]byte, error) {
return json.Marshal(!bool(ib))
}
func (ib *InvertedBool) UnmarshalJSON(b []byte) error {
var bo bool
if err := json.Unmarshal(b, &bo); err != nil {
return err
}
*ib = InvertedBool(!bo)
return nil
}
// Get returns the logical value of ib.
func (ib InvertedBool) Get() bool {
return !bool(ib)
}

View File

@ -101,3 +101,52 @@ func TestTime3339_empty(t *testing.T) {
}
}
}
func TestInvertedBool_Unmarshal(t *testing.T) {
tests := []struct {
json string
want bool
}{
{json: `{}`, want: true},
{json: `{"key": true}`, want: true},
{json: `{"key": false}`, want: false},
}
type O struct {
Key InvertedBool
}
for _, tt := range tests {
obj := &O{}
if err := json.Unmarshal([]byte(tt.json), obj); err != nil {
t.Fatalf("Could not unmarshal %s: %v", tt.json, err)
}
if obj.Key.Get() != tt.want {
t.Errorf("Unmarshaled %s as InvertedBool; got %v, wanted %v", tt.json, obj.Key.Get(), tt.want)
}
}
}
func TestInvertedBool_Marshal(t *testing.T) {
tests := []struct {
internalVal bool
want string
}{
{internalVal: true, want: `{"key":false}`},
{internalVal: false, want: `{"key":true}`},
}
type O struct {
Key InvertedBool `json:"key"`
}
for _, tt := range tests {
obj := &O{
Key: InvertedBool(tt.internalVal),
}
b, err := json.Marshal(obj)
if err != nil {
t.Fatalf("Could not marshal %v: %v", tt.internalVal, err)
}
if string(b) != tt.want {
t.Errorf("Marshaled InvertedBool %v; got %v, wanted %v", tt.internalVal, string(b), tt.want)
}
}
}