-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodec.go
More file actions
77 lines (64 loc) · 1.95 KB
/
codec.go
File metadata and controls
77 lines (64 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Copyright (c) 2012, SoundCloud Ltd.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Source code and contact info at http://github.com/soundcloud/visor
package visor
import (
"encoding/json"
"errors"
"strconv"
"strings"
)
// A Codec represents a protocol for encoding and
// decoding file values in the coordinator.
type Codec interface {
Encode(input interface{}) ([]byte, error)
Decode(input []byte) (interface{}, error)
}
// ByteCodec is a transparent Codec which doesn't
// perform any serialization or deserialization.
type ByteCodec struct{}
func (*ByteCodec) Encode(input interface{}) ([]byte, error) {
return input.([]byte), nil
}
func (*ByteCodec) Decode(input []byte) (interface{}, error) {
return input, nil
}
// StringCodec is a Codec which converts data to and from the Go *string* type.
type StringCodec struct{}
func (*StringCodec) Encode(input interface{}) (output []byte, err error) {
switch i := input.(type) {
case string:
output = []byte(i)
case []byte: // TODO: do we want allow bytes?
output = i
default:
err = errors.New("expected string or []byte input")
}
return
}
func (*StringCodec) Decode(input []byte) (interface{}, error) {
return string(input), nil
}
type JSONCodec struct{}
func (*JSONCodec) Encode(input interface{}) ([]byte, error) {
return json.Marshal(input)
}
func (*JSONCodec) Decode(input []byte) (val interface{}, err error) {
err = json.Unmarshal(input, &val)
return
}
type IntCodec struct{}
func (*IntCodec) Encode(input interface{}) ([]byte, error) {
return []byte(strconv.Itoa(input.(int))), nil
}
func (*IntCodec) Decode(input []byte) (interface{}, error) {
return strconv.Atoi(string(input))
}
type ListCodec struct{}
func (*ListCodec) Encode(input interface{}) ([]byte, error) {
return []byte(strings.Join(input.([]string), " ")), nil
}
func (*ListCodec) Decode(input []byte) (interface{}, error) {
return strings.Fields(string(input)), nil
}