From dbbde543b1946b82b65d529e384a47704a3d43e7 Mon Sep 17 00:00:00 2001 From: Solomon Hykes Date: Mon, 24 Mar 2014 17:24:48 -0700 Subject: [PATCH] beam/data: convenience Message type for chained manipulation Docker-DCO-1.1-Signed-off-by: Solomon Hykes (github: shykes) --- beam/data/message.go | 47 ++++++++++++++++++++++++++++++++++ beam/data/message_test.go | 53 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 100 insertions(+) create mode 100644 beam/data/message.go create mode 100644 beam/data/message_test.go diff --git a/beam/data/message.go b/beam/data/message.go new file mode 100644 index 0000000..fffa228 --- /dev/null +++ b/beam/data/message.go @@ -0,0 +1,47 @@ +package data + +import ( +) + +type Message string + +func Empty() Message { + return Message(Encode(nil)) +} + +func (m Message) Add(k, v string) Message { + data, err := Decode(string(m)) + if err != nil { + return m + } + if values, exists := data[k]; exists { + data[k] = append(values, v) + } else { + data[k] = []string{v} + } + return Message(Encode(data)) +} + +func (m Message) Set(k string, v ...string) Message { + data, err := Decode(string(m)) + if err != nil { + panic(err) + return m + } + data[k] = v + return Message(Encode(data)) +} + +func (m Message) Del(k string) Message { + data, err := Decode(string(m)) + if err != nil { + panic(err) + return m + } + delete(data, k) + return Message(Encode(data)) +} + +func (m Message) String() string { + return string(m) +} diff --git a/beam/data/message_test.go b/beam/data/message_test.go new file mode 100644 index 0000000..7685769 --- /dev/null +++ b/beam/data/message_test.go @@ -0,0 +1,53 @@ +package data + +import ( + "testing" +) + +func TestEmptyMessage(t *testing.T) { + m := Empty() + if m.String() != Encode(nil) { + t.Fatalf("%v != %v", m.String(), Encode(nil)) + } +} + +func TestSetMessage(t *testing.T) { + m := Empty().Set("foo", "bar") + output := m.String() + expectedOutput := "000;3:foo,6:3:bar,," + if output != expectedOutput { + t.Fatalf("'%v' != '%v'", output, expectedOutput) + } + decodedOutput, err := Decode(output) + if err != nil { + t.Fatal(err) + } + if len(decodedOutput) != 1 { + t.Fatalf("wrong output data: %#v\n", decodedOutput) + } +} + +func TestSetMessageTwice(t *testing.T) { + m := Empty().Set("foo", "bar").Set("ga", "bu") + output := m.String() + expectedOutput := "000;3:foo,6:3:bar,,2:ga,5:2:bu,," + if output != expectedOutput { + t.Fatalf("'%v' != '%v'", output, expectedOutput) + } + decodedOutput, err := Decode(output) + if err != nil { + t.Fatal(err) + } + if len(decodedOutput) != 2 { + t.Fatalf("wrong output data: %#v\n", decodedOutput) + } +} + +func TestSetDelMessage(t *testing.T) { + m := Empty().Set("foo", "bar").Del("foo") + output := m.String() + expectedOutput := Encode(nil) + if output != expectedOutput { + t.Fatalf("'%v' != '%v'", output, expectedOutput) + } +}