summaryrefslogtreecommitdiff
path: root/src/hub/src/spreadspace.org/sfive/s5cvt.go
blob: 12c0562caaf02c2fc9b9a1f2d25bcd56ad59e96f (plain) (blame)
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
package sfive

import (
	"encoding/json"
	"fmt"
)

type FullDecoder interface {
	Decode(jsonString []byte) (DataUpdateFull, error)
}

type FullEncoder interface {
	Encode(data DataUpdateFull) []byte
}

type StatefulDecoder struct {
	sourceId SourceId
}

type PlainDecoder struct{}

type PlainEncoder struct{}

func NewStatefulDecoder(jsonString []byte) (decoder FullDecoder, err error) {
	res := new(StatefulDecoder)
	err = json.Unmarshal(jsonString, &res.sourceId)
	if err != nil {
		return
	}
	if res.sourceId.Version != 1 {
		err = fmt.Errorf("unsupported version, expected 1, actual %v", res.sourceId.Version)
	}
	decoder = res
	return
}

func NewPlainDecoder() FullDecoder {
	return new(PlainDecoder)
}

func (self *StatefulDecoder) Decode(jsonString []byte) (dat DataUpdateFull, err error) {
	dat.CopyFromSourceId(&self.sourceId)
	err = json.Unmarshal(jsonString, &dat)
	// like in PlainDecoder, let the client decide how to use partial results
	// (Unmarshal returns partial results in case of errors)
	return
}

func (self *PlainDecoder) Decode(jsonString []byte) (dat DataUpdateFull, err error) {
	err = json.Unmarshal(jsonString, &dat)
	return
}

func (self *PlainEncoder) Encode(data *DataUpdateFull) []byte {
	res, err := json.Marshal(data)
	if err != nil {
		s5l.Panicln("failed to encode DataUpdateFull")
	}
	return res
}