From 20b9f5d6f15639897c741298cc8087363a4c7221 Mon Sep 17 00:00:00 2001 From: mpl Date: Thu, 23 Jan 2014 16:40:28 +0100 Subject: [PATCH] pkg/types: add InvertedBool Will be needed for json tagged serverconfig in subsequent commit. http://camlistore.org/issue/339 Change-Id: I41ae6e9918b23eb9bdb471e402de0415f3499dc3 --- pkg/types/types.go | 21 ++++++++++++++++++ pkg/types/types_test.go | 49 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) diff --git a/pkg/types/types.go b/pkg/types/types.go index f76ed1f8f..b4431c7bf 100644 --- a/pkg/types/types.go +++ b/pkg/types/types.go @@ -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) +} diff --git a/pkg/types/types_test.go b/pkg/types/types_test.go index e3f847c06..8708c7dd4 100644 --- a/pkg/types/types_test.go +++ b/pkg/types/types_test.go @@ -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) + } + } +}