-
Notifications
You must be signed in to change notification settings - Fork 2
/
document.go
65 lines (60 loc) · 1.5 KB
/
document.go
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
package ot
import (
"encoding/json"
"errors"
"fmt"
)
type Document struct {
Content string
Operations [][]Applier
}
func (doc *Document) Recieve(message Message) ([]Applier, error) {
if message.Revision < 0 || message.Revision >= len(doc.Operations) {
return nil, errors.New("revision not in history")
}
concurentOperations := doc.Operations[message.Revision:]
operation := message.Operation
var err error
for _, authorityOp := range concurentOperations {
operation, _, err = Transform(operation, authorityOp)
if err != nil {
return nil, err
}
}
nextDoc, err := Apply(doc.Content, operation...)
if err != nil {
return nil, err
}
doc.Content = nextDoc
doc.Operations = append(doc.Operations, operation)
return operation, nil
}
type Message struct {
Revision int `json:"revision"`
Operation []Applier `json:"operation"`
}
func (message *Message) UnmarshalJSON(data []byte) error {
var obj struct {
Revision int `json:"revision"`
Opperation []interface{} `json:"operation"`
}
if err := json.Unmarshal(data, &obj); err != nil {
return err
}
message.Revision = obj.Revision
for _, op := range obj.Opperation {
switch o := op.(type) {
case string:
message.Operation = append(message.Operation, Insert(o))
case float64:
if o < 0 {
message.Operation = append(message.Operation, Delete(int(o)))
} else {
message.Operation = append(message.Operation, Retain(int(o)))
}
default:
return fmt.Errorf("unknown op type %v %t", o, o)
}
}
return nil
}