├── common
├── blockpath.go
├── base.go
├── string.go
├── uint32.go
├── order.go
├── string_test.go
├── errors.go
├── uint32_test.go
├── errors_test.go
├── stamp.go
├── stamp_test.go
├── closedrange.go
└── closedrange_test.go
├── text
├── content
│ ├── content.go
│ ├── mod.go
│ ├── del.go
│ ├── del_test.go
│ ├── mod_test.go
│ ├── fmt_test.go
│ ├── fmt.go
│ ├── attrs
│ │ ├── attr.go
│ │ ├── attr_test.go
│ │ ├── attrs.go
│ │ └── attrs_test.go
│ ├── ins_test.go
│ └── ins.go
├── text.go
├── tree
│ ├── ins.go
│ ├── mod.go
│ ├── fmt.go
│ ├── del.go
│ ├── ins_test.go
│ ├── node_test.go
│ ├── del_test.go
│ ├── node.go
│ ├── mod_test.go
│ └── fmt_test.go
├── test
│ └── cases.go
├── text_test.go
└── span
│ ├── span.go
│ └── span_test.go
├── go.mod
├── .github
└── workflows
│ ├── release-please.yaml
│ └── test.yaml
├── .gitignore
├── README.md
├── go.sum
├── block
├── ctrb.go
├── version.go
├── version_test.go
├── block_test.go
├── props.go
├── block.go
└── props_test.go
├── point
├── tag.go
├── point.go
├── tag_test.go
└── point_test.go
└── LICENSE
/common/blockpath.go:
--------------------------------------------------------------------------------
1 | package common
2 |
3 | type BlockPath struct {
4 | NoteID NoteID
5 | BlockID BlockID
6 | }
7 |
--------------------------------------------------------------------------------
/common/base.go:
--------------------------------------------------------------------------------
1 | package common
2 |
3 | import "github.com/google/uuid"
4 |
5 | type Priority = uint32
6 | type ReplicaID = uint32
7 | type Nonce = uint32
8 | type Timestamp = uint64
9 | type BlockID = uuid.UUID
10 | type NoteID = BlockID
11 |
--------------------------------------------------------------------------------
/text/content/content.go:
--------------------------------------------------------------------------------
1 | package content
2 |
3 | type Content[T any] interface {
4 | *INSContent | *DELContent | *FMTContent | *MODContent
5 |
6 | Length() uint32
7 | Concat(other T) T
8 | Slice(start uint32, end uint32) T
9 | Equals(other T) bool
10 | }
11 |
--------------------------------------------------------------------------------
/common/string.go:
--------------------------------------------------------------------------------
1 | package common
2 |
3 | import "unicode/utf16"
4 |
5 | func UTF16Slice(s string, start, end uint32) string {
6 | encoded := utf16.Encode([]rune(s))
7 | return string(utf16.Decode(encoded[start:end]))
8 | }
9 |
10 | func UTF16Length(s string) uint32 {
11 | return uint32(len(utf16.Encode([]rune(s))))
12 | }
13 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/notebox/nb-crdt-go
2 |
3 | go 1.22.0
4 |
5 | require (
6 | github.com/google/uuid v1.6.0
7 | github.com/stretchr/testify v1.9.0
8 | )
9 |
10 | require (
11 | github.com/davecgh/go-spew v1.1.1 // indirect
12 | github.com/pmezard/go-difflib v1.0.0 // indirect
13 | gopkg.in/yaml.v3 v3.0.1 // indirect
14 | )
15 |
--------------------------------------------------------------------------------
/common/uint32.go:
--------------------------------------------------------------------------------
1 | package common
2 |
3 | const UInt32Min = uint32(0)
4 | const UInt32Mid = (uint32(^uint32(0)) - uint32(0)) / 2
5 | const UInt32Max = uint32(^uint32(0))
6 |
7 | func CompareNumber[T ~uint32 | ~int](a, b T) Order {
8 | if a == b {
9 | return Equal
10 | }
11 | if a < b {
12 | return Less
13 | }
14 | return Greater
15 | }
16 |
--------------------------------------------------------------------------------
/common/order.go:
--------------------------------------------------------------------------------
1 | package common
2 |
3 | type Order int
4 |
5 | const (
6 | Splitting Order = iota + 1
7 | Tagging
8 | Less
9 | Prependable
10 | RightOverlap
11 | IncludingRight
12 | IncludingMiddle
13 | IncludingLeft
14 | Equal
15 | IncludedLeft
16 | IncludedMiddle
17 | IncludedRight
18 | LeftOverlap
19 | Appendable
20 | Greater
21 | Tagged
22 | Splitted
23 | )
24 |
--------------------------------------------------------------------------------
/.github/workflows/release-please.yaml:
--------------------------------------------------------------------------------
1 | on:
2 | push:
3 | branches:
4 | - main
5 |
6 | permissions:
7 | contents: write
8 | pull-requests: write
9 |
10 | name: release-please
11 |
12 | jobs:
13 | release-please:
14 | runs-on: ubuntu-latest
15 | steps:
16 | - uses: google-github-actions/release-please-action@v3
17 | with:
18 | release-type: go
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # testing
2 | cover.prof
3 | cover.html
4 |
5 | # production
6 | /dist
7 |
8 | # editor
9 | .idea
10 | .vscode
11 | *.code-workspace
12 | *.suo
13 | *.ntvs*
14 | *.njsproj
15 | *.sln
16 | *.svd
17 | *.userprefs
18 | *.csproj
19 | *.pidb
20 | *.user
21 | *.unityproj
22 | *.booproj
23 | ExportedObj/
24 | *.xcuserstate
25 |
26 | # misc
27 | .DS_Store
28 | .env.local
29 | .env.development.local
30 | .env.test.local
31 | .env.production.local
32 | .eslintcache
33 |
--------------------------------------------------------------------------------
/common/string_test.go:
--------------------------------------------------------------------------------
1 | package common_test
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/notebox/nb-crdt-go/common"
7 | "github.com/stretchr/testify/assert"
8 | )
9 |
10 | func TestUTF16(t *testing.T) {
11 | t.Run("UTF16Slice", func(t *testing.T) {
12 | assert.Equal(t, "😀bb🤖cc👍🏿dd강e", common.UTF16Slice("aa😀bb🤖cc👍🏿dd강ee", 2, 18))
13 | })
14 |
15 | t.Run("UTF16Length", func(t *testing.T) {
16 | assert.Equal(t, uint32(19), common.UTF16Length("aa😀bb🤖cc👍🏿dd강ee"))
17 | })
18 | }
19 |
--------------------------------------------------------------------------------
/common/errors.go:
--------------------------------------------------------------------------------
1 | package common
2 |
3 | type FatalError string
4 |
5 | const (
6 | NoIntersection FatalError = "NoIntersection"
7 | ExistingSpanOverwrite FatalError = "ExistingSpanOverwrite"
8 | UnAppendable FatalError = "UnAppendable"
9 | UnPrependable FatalError = "UnPrependable"
10 | InvalidDistanceBetweenNoRelation FatalError = "InvalidDistanceBetweenNoRelation"
11 | )
12 |
13 | func (fatal FatalError) Error() string {
14 | return string(fatal)
15 | }
16 |
--------------------------------------------------------------------------------
/common/uint32_test.go:
--------------------------------------------------------------------------------
1 | package common_test
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/notebox/nb-crdt-go/common"
7 | "github.com/stretchr/testify/assert"
8 | )
9 |
10 | func TestUInt32(t *testing.T) {
11 | t.Run("Constants", func(t *testing.T) {
12 | assert.Equal(t, uint32(0), common.UInt32Min)
13 | assert.Equal(t, uint32(2147483647), common.UInt32Mid)
14 | assert.Equal(t, uint32(4294967295), common.UInt32Max)
15 | assert.Equal(t, uint32(4294967295), common.UInt32Max)
16 | })
17 |
18 | t.Run("CompareNumber", func(t *testing.T) {
19 | assert.Equal(t, common.Equal, common.CompareNumber(0, 0))
20 | assert.Equal(t, common.Less, common.CompareNumber(0, 1))
21 | assert.Equal(t, common.Greater, common.CompareNumber(1, 0))
22 | })
23 | }
24 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # nb-crdt-go
2 |
3 | [](https://pkg.go.dev/github.com/notebox/nb-crdt-go)
4 | [](https://goreportcard.com/report/github.com/notebox/nb-crdt-go)
5 | [](https://github.com/notebox/nb-crdt-go/actions)
6 | [](https://codecov.io/gh/notebox/nb-crdt-go)
7 | [](https://github.com/sponsors/notebox)
8 |
9 | The Go version of [nb-crdt](https://github.com/notebox/nb-crdt)
10 |
--------------------------------------------------------------------------------
/.github/workflows/test.yaml:
--------------------------------------------------------------------------------
1 | name: test
2 |
3 | on:
4 | push:
5 | branches:
6 | - main
7 | pull_request:
8 | branches:
9 | - main
10 |
11 | jobs:
12 |
13 | build:
14 | runs-on: ubuntu-latest
15 | steps:
16 | - name: Checkout
17 | uses: actions/checkout@v4
18 |
19 | - name: Setup Go
20 | uses: actions/setup-go@v4
21 | with:
22 | go-version: 1.22.0
23 |
24 | - name: Install
25 | run: go mod tidy
26 |
27 | - name: Test
28 | run: go test -race -coverprofile=cover.prof -covermode=atomic ./...
29 |
30 | - name: Copy coverage profile to text
31 | run: cp cover.prof cover.txt
32 |
33 | - name: Codecov
34 | uses: codecov/codecov-action@v4
35 | with:
36 | token: ${{ secrets.CODECOV_TOKEN }}
37 | slug: notebox/nb-crdt-go
38 | file: ./cover.txt
--------------------------------------------------------------------------------
/common/errors_test.go:
--------------------------------------------------------------------------------
1 | package common_test
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/notebox/nb-crdt-go/common"
7 | "github.com/stretchr/testify/assert"
8 | )
9 |
10 | func TestFatalErrors(t *testing.T) {
11 | tests := []struct {
12 | name string
13 | err common.FatalError
14 | }{
15 | {
16 | name: "NoIntersection",
17 | err: common.NoIntersection,
18 | },
19 | {
20 | name: "ExistingSpanOverwrite",
21 | err: common.ExistingSpanOverwrite,
22 | },
23 | {
24 | name: "UnAppendable",
25 | err: common.UnAppendable,
26 | },
27 | {
28 | name: "UnPrependable",
29 | err: common.UnPrependable,
30 | },
31 | {
32 | name: "InvalidDistanceBetweenNoRelation",
33 | err: common.InvalidDistanceBetweenNoRelation,
34 | },
35 | }
36 |
37 | for _, tt := range tests {
38 | t.Run(tt.name, func(t *testing.T) {
39 | assert.Equal(t, tt.name, tt.err.Error())
40 | })
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/common/stamp.go:
--------------------------------------------------------------------------------
1 | package common
2 |
3 | import (
4 | "encoding/json"
5 | )
6 |
7 | type Stamp struct {
8 | ReplicaID ReplicaID
9 | Timestamp Timestamp
10 | }
11 |
12 | func (s *Stamp) MarshalJSON() ([]byte, error) {
13 | return json.Marshal([]any{s.ReplicaID, s.Timestamp})
14 | }
15 |
16 | func (s *Stamp) UnmarshalJSON(data []byte) error {
17 | var raw []json.RawMessage
18 | err := json.Unmarshal(data, &raw)
19 | if err != nil {
20 | return err
21 | }
22 | err = json.Unmarshal(raw[0], &s.ReplicaID)
23 | if err != nil {
24 | return err
25 | }
26 | err = json.Unmarshal(raw[1], &s.Timestamp)
27 | if err != nil {
28 | return err
29 | }
30 | return nil
31 | }
32 |
33 | func (s *Stamp) IsOlderThan(other *Stamp) bool {
34 | if s == nil {
35 | return true
36 | } else if other == nil {
37 | return false
38 | }
39 | if s.Timestamp == other.Timestamp {
40 | return s.ReplicaID < other.ReplicaID
41 | }
42 |
43 | return s.Timestamp < other.Timestamp
44 | }
45 |
--------------------------------------------------------------------------------
/common/stamp_test.go:
--------------------------------------------------------------------------------
1 | package common_test
2 |
3 | import (
4 | "encoding/json"
5 | "testing"
6 |
7 | "github.com/notebox/nb-crdt-go/common"
8 | "github.com/stretchr/testify/assert"
9 | )
10 |
11 | func TestStamp(t *testing.T) {
12 | t.Run("CheckIsNewerThan", func(t *testing.T) {
13 | subject := &common.Stamp{ReplicaID: 1, Timestamp: 0}
14 | assert.True(t, subject.IsOlderThan(&common.Stamp{ReplicaID: 0, Timestamp: 1}))
15 | assert.False(t, subject.IsOlderThan(&common.Stamp{ReplicaID: 0, Timestamp: 0}))
16 |
17 | assert.False(t, subject.IsOlderThan(nil))
18 | subject = nil
19 | assert.True(t, subject.IsOlderThan(&common.Stamp{ReplicaID: 0, Timestamp: 0}))
20 | })
21 |
22 | t.Run("JSON", func(t *testing.T) {
23 | subject := &common.Stamp{ReplicaID: 1, Timestamp: 2}
24 | encoded, err := json.Marshal(subject)
25 | assert.NoError(t, err)
26 | assert.Equal(t, "[1,2]", string(encoded))
27 |
28 | var decoded common.Stamp
29 | json.Unmarshal(encoded, &decoded)
30 | assert.Equal(t, subject, &decoded)
31 | })
32 | }
33 |
--------------------------------------------------------------------------------
/text/content/mod.go:
--------------------------------------------------------------------------------
1 | package content
2 |
3 | import (
4 | "encoding/json"
5 |
6 | "github.com/notebox/nb-crdt-go/common"
7 | )
8 |
9 | type MODContent struct {
10 | text string
11 | }
12 |
13 | func NewMODContent(text string) *MODContent {
14 | return &MODContent{text: text}
15 | }
16 |
17 | func (c MODContent) MarshalJSON() ([]byte, error) {
18 | return json.Marshal(c.text)
19 | }
20 |
21 | func (c *MODContent) UnmarshalJSON(data []byte) error {
22 | return json.Unmarshal(data, &c.text)
23 | }
24 |
25 | func (c *MODContent) Length() uint32 {
26 | return common.UTF16Length(c.text)
27 | }
28 |
29 | func (c *MODContent) Text() string {
30 | return c.text
31 | }
32 |
33 | func (c *MODContent) Concat(other *MODContent) *MODContent {
34 | return &MODContent{c.text + other.Text()}
35 | }
36 |
37 | func (c *MODContent) Slice(start, end uint32) *MODContent {
38 | return &MODContent{common.UTF16Slice(c.text, start, end)}
39 | }
40 |
41 | func (c *MODContent) Equals(other *MODContent) bool {
42 | return c.text == other.Text()
43 | }
44 |
--------------------------------------------------------------------------------
/text/content/del.go:
--------------------------------------------------------------------------------
1 | package content
2 |
3 | import (
4 | "encoding/json"
5 | )
6 |
7 | type DELContent struct {
8 | length uint32
9 | }
10 |
11 | func NewDELContent(length uint32) *DELContent {
12 | return &DELContent{length}
13 | }
14 |
15 | func (c DELContent) MarshalJSON() ([]byte, error) {
16 | return json.Marshal(c.length)
17 | }
18 |
19 | func (c *DELContent) UnmarshalJSON(data []byte) error {
20 | return json.Unmarshal(data, &c.length)
21 | }
22 |
23 | func (c *DELContent) Length() uint32 {
24 | return c.length
25 | }
26 |
27 | func (c *DELContent) Equals(other *DELContent) bool {
28 | return c.length == other.Length()
29 | }
30 |
31 | func (c *DELContent) Concat(other *DELContent) *DELContent {
32 | return &DELContent{c.length + other.Length()}
33 | }
34 |
35 | func (c *DELContent) Slice(start, end uint32) *DELContent {
36 | // defense code
37 | if start >= c.length {
38 | return &DELContent{}
39 | }
40 |
41 | if end >= c.length {
42 | return &DELContent{c.length - start}
43 | }
44 |
45 | return &DELContent{end - start}
46 | }
47 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
2 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
3 | github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
4 | github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
5 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
6 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
7 | github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
8 | github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
9 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
10 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
11 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
12 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
13 |
--------------------------------------------------------------------------------
/text/content/del_test.go:
--------------------------------------------------------------------------------
1 | package content
2 |
3 | import (
4 | "encoding/json"
5 | "testing"
6 |
7 | "github.com/stretchr/testify/assert"
8 | )
9 |
10 | func TestDELContent(t *testing.T) {
11 | t.Run("JSON", func(t *testing.T) {
12 | stringifiedJSON := "5"
13 | var subject DELContent
14 | err := json.Unmarshal([]byte(stringifiedJSON), &subject)
15 | assert.NoError(t, err)
16 | assert.Equal(t, DELContent{length: 5}, subject)
17 | encoded, err := json.Marshal(subject)
18 | assert.NoError(t, err)
19 | assert.Equal(t, stringifiedJSON, string(encoded))
20 | })
21 |
22 | t.Run("Slice", func(t *testing.T) {
23 | subject := DELContent{length: 5}
24 | assert.True(t, subject.Slice(1, 3).Equals(&DELContent{length: 2}))
25 | assert.True(t, subject.Slice(5, 1).Equals(&DELContent{}))
26 | assert.True(t, subject.Slice(4, 9).Equals(&DELContent{length: 1}))
27 | })
28 |
29 | t.Run("Concat", func(t *testing.T) {
30 | a := DELContent{length: 3}
31 | b := DELContent{length: 5}
32 | assert.True(t, a.Concat(&b).Equals(&DELContent{length: 8}))
33 | })
34 |
35 | t.Run("NewDELContent", func(t *testing.T) {
36 | assert.True(t, NewDELContent(5).Equals(&DELContent{length: 5}))
37 | })
38 | }
39 |
--------------------------------------------------------------------------------
/text/content/mod_test.go:
--------------------------------------------------------------------------------
1 | package content
2 |
3 | import (
4 | "encoding/json"
5 | "testing"
6 |
7 | "github.com/stretchr/testify/assert"
8 | )
9 |
10 | func TestMODContent(t *testing.T) {
11 | t.Run("JSON", func(t *testing.T) {
12 | stringifiedJSON := `"foobar"`
13 | var subject MODContent
14 | err := json.Unmarshal([]byte(stringifiedJSON), &subject)
15 | assert.NoError(t, err)
16 | assert.Equal(t, MODContent{text: "foobar"}, subject)
17 | encoded, err := json.Marshal(subject)
18 | assert.NoError(t, err)
19 | assert.Equal(t, stringifiedJSON, string(encoded))
20 | })
21 |
22 | t.Run("Slice", func(t *testing.T) {
23 | subject := MODContent{text: "foobar"}
24 | assert.True(t, subject.Slice(1, 3).Equals(&MODContent{text: "oo"}))
25 | })
26 |
27 | t.Run("Concat", func(t *testing.T) {
28 | a := MODContent{text: "foo"}
29 | b := MODContent{text: "bar"}
30 | assert.True(t, a.Concat(&b).Equals(&MODContent{text: "foobar"}))
31 | })
32 |
33 | t.Run("NewMODContent", func(t *testing.T) {
34 | assert.True(t, NewMODContent("foobar").Equals(&MODContent{text: "foobar"}))
35 | })
36 |
37 | t.Run("others", func(t *testing.T) {
38 | subject := MODContent{text: "aa😀bb🤖cc👍🏿dd강ee"}
39 | assert.Equal(t, uint32(19), subject.Length())
40 | })
41 | }
42 |
--------------------------------------------------------------------------------
/block/ctrb.go:
--------------------------------------------------------------------------------
1 | package block
2 |
3 | import (
4 | "encoding/json"
5 |
6 | "github.com/notebox/nb-crdt-go/common"
7 | "github.com/notebox/nb-crdt-go/point"
8 | "github.com/notebox/nb-crdt-go/text/span"
9 | )
10 |
11 | type Contribution struct {
12 | BlockID common.BlockID `json:"blockID"`
13 | Nonce ReplicaNonce `json:"nonce"`
14 | Stamp common.Stamp `json:"stamp"`
15 | Operations Operations `json:"ops"`
16 | }
17 |
18 | type BlockPoint struct {
19 | ParentBlockID common.BlockID
20 | Point point.Point
21 | }
22 |
23 | func (bp BlockPoint) MarshalJSON() ([]byte, error) {
24 | return json.Marshal([2]any{bp.ParentBlockID, bp.Point})
25 | }
26 |
27 | func (bp *BlockPoint) UnmarshalJSON(data []byte) error {
28 | var raw []json.RawMessage
29 | err := json.Unmarshal(data, &raw)
30 | if err != nil {
31 | return err
32 | }
33 | err = json.Unmarshal(raw[0], &bp.ParentBlockID)
34 | if err != nil {
35 | return err
36 | }
37 | err = json.Unmarshal(raw[1], &bp.Point)
38 | if err != nil {
39 | return err
40 | }
41 | return nil
42 | }
43 |
44 | type Operations struct {
45 | BINS *Block
46 | BDEL *bool
47 | BSET PropsDelta
48 | BMOV *BlockPoint
49 | TINS []*span.INSSpan
50 | TDEL []*span.DELSpan
51 | TFMT []*span.FMTSpan
52 | TMOD []*span.MODSpan
53 | }
54 |
--------------------------------------------------------------------------------
/block/version.go:
--------------------------------------------------------------------------------
1 | package block
2 |
3 | import "github.com/notebox/nb-crdt-go/common"
4 |
5 | type ReplicaNonce []common.Nonce // []common.Nonce is a tuple of [block-nonce, text-nonce]
6 | type Version map[common.ReplicaID]ReplicaNonce
7 |
8 | func (v Version) IsNewerOrEqualThan(other Version) bool {
9 | for replicaID, version := range other {
10 | curr, ok := v[replicaID]
11 | if !ok || curr[0] < version[0] {
12 | return false
13 | }
14 | }
15 | return true
16 | }
17 |
18 | func (v Version) IsNewerThanExceptFor(other Version, replicaID common.ReplicaID) bool {
19 | result := false
20 | for rid, version := range other {
21 | if rid == replicaID {
22 | continue
23 | }
24 | curr, ok := v[rid]
25 | if !ok || curr[0] < version[0] {
26 | return false
27 | }
28 | if curr[0] > version[0] {
29 | result = true
30 | }
31 | }
32 | return result
33 | }
34 |
35 | func (v Version) Add(replicaID common.ReplicaID, nonces ReplicaNonce) bool {
36 | curr, ok := v[replicaID]
37 | if ok && curr[0] >= nonces[0] {
38 | return false
39 | }
40 | v[replicaID] = nonces
41 | return true
42 | }
43 |
44 | func (v Version) Merge(other Version) bool {
45 | var updated bool
46 | for replicaID, nonces := range other {
47 | ok := v.Add(replicaID, nonces)
48 | if ok && !updated {
49 | updated = true
50 | }
51 | }
52 | return updated
53 | }
54 |
--------------------------------------------------------------------------------
/text/content/fmt_test.go:
--------------------------------------------------------------------------------
1 | package content
2 |
3 | import (
4 | "encoding/json"
5 | "testing"
6 |
7 | "github.com/notebox/nb-crdt-go/text/content/attrs"
8 | "github.com/stretchr/testify/assert"
9 | )
10 |
11 | func TestFMTContent(t *testing.T) {
12 | t.Run("JSON", func(t *testing.T) {
13 | stringifiedJSON := "[5,[[5]]]"
14 | var subject FMTContent
15 | err := json.Unmarshal([]byte(stringifiedJSON), &subject)
16 | assert.NoError(t, err)
17 | assert.Equal(t, FMTContent{length: 5, attrs: attrs.Attrs{{Length: 5}}}, subject)
18 | encoded, err := json.Marshal(subject)
19 | assert.NoError(t, err)
20 | assert.Equal(t, stringifiedJSON, string(encoded))
21 | })
22 |
23 | t.Run("Slice", func(t *testing.T) {
24 | subject := FMTContent{length: 5, attrs: attrs.Attrs{{Length: 5}}}
25 | assert.True(t, subject.Slice(1, 3).Equals(&FMTContent{length: 2, attrs: attrs.Attrs{{Length: 2}}}))
26 | assert.True(t, subject.Slice(5, 1).Equals(&FMTContent{}))
27 | assert.True(t, subject.Slice(4, 9).Equals(&FMTContent{length: 1, attrs: attrs.Attrs{{Length: 1}}}))
28 | })
29 |
30 | t.Run("Concat", func(t *testing.T) {
31 | a := FMTContent{length: 3, attrs: attrs.Attrs{{Length: 3}}}
32 | b := FMTContent{length: 5, attrs: attrs.Attrs{{Length: 5}}}
33 | assert.True(t, a.Concat(&b).Equals(&FMTContent{length: 8, attrs: attrs.Attrs{{Length: 8}}}))
34 | })
35 |
36 | t.Run("NewFMTContent", func(t *testing.T) {
37 | assert.True(t, NewFMTContent(5, attrs.TextProps{"B": true}).Equals(&FMTContent{length: 5, attrs: attrs.Attrs{{Length: 5, Props: attrs.TextProps{"B": true}}}}))
38 | })
39 | }
40 |
--------------------------------------------------------------------------------
/common/closedrange.go:
--------------------------------------------------------------------------------
1 | package common
2 |
3 | type ClosedRange struct {
4 | Lower uint32
5 | Length uint32
6 | }
7 |
8 | func (cr ClosedRange) Upper() uint32 {
9 | return cr.Lower + cr.Length - 1
10 | }
11 |
12 | func (cr ClosedRange) Compare(other ClosedRange) Order {
13 | upper := cr.Upper()
14 | otherUpper := other.Upper()
15 |
16 | if upper < other.Lower {
17 | if upper+1 == other.Lower {
18 | return Prependable
19 | }
20 |
21 | return Less
22 | }
23 |
24 | if otherUpper < cr.Lower {
25 | if otherUpper+1 == cr.Lower {
26 | return Appendable
27 | }
28 |
29 | return Greater
30 | }
31 |
32 | if cr.Lower == other.Lower {
33 | if upper == otherUpper {
34 | return Equal
35 | }
36 |
37 | if upper < otherUpper {
38 | return IncludedLeft
39 | }
40 |
41 | return IncludingLeft
42 | }
43 |
44 | if cr.Lower < other.Lower {
45 | if otherUpper == upper {
46 | return IncludingRight
47 | }
48 |
49 | if otherUpper < upper {
50 | return IncludingMiddle
51 | }
52 |
53 | return RightOverlap
54 | }
55 |
56 | if upper == otherUpper {
57 | return IncludedRight
58 | }
59 |
60 | if upper < otherUpper {
61 | return IncludedMiddle
62 | }
63 |
64 | return LeftOverlap
65 | }
66 |
67 | func (cr ClosedRange) Intersection(other ClosedRange) (ClosedRange, error) {
68 | if other.Upper() < cr.Lower || cr.Upper() < other.Lower {
69 | return ClosedRange{}, NoIntersection
70 | }
71 |
72 | lower := max(cr.Lower, other.Lower)
73 | upper := min(cr.Upper(), other.Upper())
74 |
75 | return ClosedRange{Lower: lower, Length: upper - lower + 1}, nil
76 | }
77 |
--------------------------------------------------------------------------------
/text/content/fmt.go:
--------------------------------------------------------------------------------
1 | package content
2 |
3 | import (
4 | "encoding/json"
5 | "reflect"
6 |
7 | "github.com/notebox/nb-crdt-go/text/content/attrs"
8 | )
9 |
10 | type FMTContent struct {
11 | length uint32
12 | attrs attrs.Attrs
13 | }
14 |
15 | func NewFMTContent(length uint32, props attrs.TextProps) *FMTContent {
16 | return &FMTContent{length, attrs.Attrs{attrs.Attr{length, props, nil}}}
17 | }
18 |
19 | func (c FMTContent) MarshalJSON() ([]byte, error) {
20 | return json.Marshal([]any{c.length, c.attrs})
21 | }
22 |
23 | func (c *FMTContent) UnmarshalJSON(data []byte) error {
24 | var raw []json.RawMessage
25 | err := json.Unmarshal(data, &raw)
26 | if err != nil {
27 | return err
28 | }
29 | err = json.Unmarshal(raw[0], &c.length)
30 | if err != nil {
31 | return err
32 | }
33 | err = json.Unmarshal(raw[1], &c.attrs)
34 | if err != nil {
35 | return err
36 | }
37 | return nil
38 | }
39 |
40 | func (c *FMTContent) Length() uint32 {
41 | return c.length
42 | }
43 |
44 | func (c *FMTContent) Attrs() attrs.Attrs {
45 | return c.attrs
46 | }
47 |
48 | func (c *FMTContent) Concat(other *FMTContent) *FMTContent {
49 | return &FMTContent{c.length + other.Length(), c.attrs.Concat(other.Attrs())}
50 | }
51 |
52 | func (c *FMTContent) Slice(start, end uint32) *FMTContent {
53 | // defense code
54 | if start >= c.length {
55 | return &FMTContent{}
56 | }
57 |
58 | if end >= c.length {
59 | end = c.length
60 | }
61 |
62 | return &FMTContent{end - start, c.attrs.Slice(start, end)}
63 | }
64 |
65 | func (c *FMTContent) Equals(other *FMTContent) bool {
66 | return c.length == other.Length() && reflect.DeepEqual(c.attrs, other.Attrs())
67 | }
68 |
--------------------------------------------------------------------------------
/point/tag.go:
--------------------------------------------------------------------------------
1 | package point
2 |
3 | import (
4 | "encoding/json"
5 |
6 | "github.com/notebox/nb-crdt-go/common"
7 | )
8 |
9 | type PointTag struct {
10 | Priority common.Priority
11 | ReplicaID common.ReplicaID
12 | Nonce common.Nonce
13 | }
14 |
15 | func (pt PointTag) MarshalJSON() ([]byte, error) {
16 | return json.Marshal([]uint32{pt.Priority, pt.ReplicaID, pt.Nonce})
17 | }
18 |
19 | func (pt *PointTag) UnmarshalJSON(data []byte) error {
20 | var raw []uint32
21 | err := json.Unmarshal(data, &raw)
22 | if err != nil {
23 | return err
24 | }
25 | pt.Priority = raw[0]
26 | pt.ReplicaID = raw[1]
27 | pt.Nonce = raw[2]
28 | return nil
29 | }
30 |
31 | func (pt *PointTag) WithNonce(nonce uint32) PointTag {
32 | return PointTag{
33 | Priority: pt.Priority,
34 | ReplicaID: pt.ReplicaID,
35 | Nonce: nonce,
36 | }
37 | }
38 |
39 | func (pt *PointTag) CompareBase(other PointTag) common.Order {
40 | result := common.CompareNumber(pt.Priority, other.Priority)
41 |
42 | if result == common.Equal {
43 | return common.CompareNumber(pt.ReplicaID, other.ReplicaID)
44 | }
45 |
46 | return result
47 | }
48 |
49 | func (pt *PointTag) Compare(other PointTag) common.Order {
50 | result := pt.CompareBase(other)
51 |
52 | if result == common.Equal {
53 | return common.CompareNumber(pt.Nonce, other.Nonce)
54 | }
55 |
56 | return result
57 | }
58 |
59 | var (
60 | MinTag = PointTag{
61 | Priority: common.UInt32Min,
62 | ReplicaID: 0,
63 | Nonce: 1,
64 | }
65 | MidTag = PointTag{
66 | Priority: common.UInt32Mid,
67 | ReplicaID: 0,
68 | Nonce: 3,
69 | }
70 | MaxTag = PointTag{
71 | Priority: common.UInt32Max,
72 | ReplicaID: 0,
73 | Nonce: 2,
74 | }
75 | )
76 |
--------------------------------------------------------------------------------
/text/text.go:
--------------------------------------------------------------------------------
1 | package text
2 |
3 | import (
4 | "encoding/json"
5 |
6 | "github.com/notebox/nb-crdt-go/text/span"
7 | "github.com/notebox/nb-crdt-go/text/tree"
8 | )
9 |
10 | type Text struct {
11 | Node *tree.Node
12 | }
13 |
14 | func (t *Text) Spans() []*span.INSSpan {
15 | if t.Node == nil {
16 | return nil
17 | }
18 | return t.Node.Spans()
19 | }
20 |
21 | func (t Text) MarshalJSON() ([]byte, error) {
22 | spans := t.Spans()
23 | if spans == nil {
24 | return []byte("[]"), nil
25 | }
26 | return json.Marshal(t.Spans())
27 | }
28 |
29 | func (t *Text) UnmarshalJSON(data []byte) error {
30 | var spans []*span.INSSpan
31 | err := json.Unmarshal(data, &spans)
32 | if err != nil {
33 | return err
34 | }
35 | if len(spans) == 0 {
36 | return nil
37 | }
38 | t.Node = tree.NewFromSpans(spans)
39 | return nil
40 | }
41 |
42 | // assuming content is not meta
43 | func (t *Text) String() string {
44 | result := ""
45 | for _, span := range t.Spans() {
46 | result += span.Content.Text()
47 | }
48 | return result
49 | }
50 |
51 | func (t *Text) INS(span *span.INSSpan) error {
52 | if t.Node != nil {
53 | err := t.Node.INS(span, 0)
54 | if err != nil {
55 | return err
56 | }
57 | t.Node = t.Node.Balance()
58 | } else {
59 | t.Node = tree.New(*span, nil, nil)
60 | }
61 | return nil
62 | }
63 |
64 | func (t *Text) DEL(span *span.DELSpan) error {
65 | if t.Node != nil {
66 | err := t.Node.DEL(span, 0)
67 | if err != nil {
68 | return err
69 | }
70 | t.Node = t.Node.Balance()
71 | }
72 | return nil
73 | }
74 |
75 | func (t *Text) FMT(span *span.FMTSpan) error {
76 | if t.Node != nil {
77 | err := t.Node.FMT(span, 0)
78 | if err != nil {
79 | return err
80 | }
81 | }
82 | return nil
83 | }
84 |
85 | func (t *Text) MOD(span *span.MODSpan) error {
86 | if t.Node != nil {
87 | err := t.Node.MOD(span, 0)
88 | if err != nil {
89 | return err
90 | }
91 | }
92 | return nil
93 | }
94 |
--------------------------------------------------------------------------------
/text/content/attrs/attr.go:
--------------------------------------------------------------------------------
1 | package attrs
2 |
3 | import (
4 | "encoding/json"
5 |
6 | "github.com/notebox/nb-crdt-go/common"
7 | )
8 |
9 | type Attr struct {
10 | Length uint32
11 | Props TextProps
12 | Stamp *common.Stamp
13 | }
14 |
15 | func (leaf Attr) MarshalJSON() ([]byte, error) {
16 | if leaf.Stamp != nil {
17 | return json.Marshal([]any{leaf.Length, leaf.Props, leaf.Stamp})
18 | } else if leaf.Props != nil && len(leaf.Props) > 0 {
19 | return json.Marshal([]any{leaf.Length, leaf.Props})
20 | }
21 | return json.Marshal([]any{leaf.Length})
22 | }
23 |
24 | func (leaf *Attr) UnmarshalJSON(data []byte) error {
25 | var raw []json.RawMessage
26 | err := json.Unmarshal(data, &raw)
27 | if err != nil {
28 | return err
29 | }
30 | err = json.Unmarshal(raw[0], &leaf.Length)
31 | if err != nil {
32 | return err
33 | }
34 | if len(raw) > 1 {
35 | err = json.Unmarshal(raw[1], &leaf.Props)
36 | if err != nil {
37 | return err
38 | }
39 | }
40 | if len(raw) > 2 {
41 | err = json.Unmarshal(raw[2], &leaf.Stamp)
42 | if err != nil {
43 | return err
44 | }
45 | }
46 | return nil
47 | }
48 |
49 | // TODO deprecated
50 | // func (l *Attr) Clone() *Attr {
51 | // props := make(TextProps)
52 | // maps.Copy(l.Props, props)
53 |
54 | // return &Attr{
55 | // Length: l.Length,
56 | // Props: props,
57 | // Stamp: l.Stamp,
58 | // }
59 | // }
60 |
61 | func (l *Attr) EqualsExceptForLength(other *Attr) bool {
62 | if (l.Stamp != nil) && (other.Stamp != nil) && *l.Stamp != *other.Stamp {
63 | return false
64 | }
65 | if len(l.Props) != len(other.Props) {
66 | return false
67 | }
68 | for k, v := range l.Props {
69 | if other.Props[k] != v {
70 | return false
71 | }
72 | }
73 | return true
74 | }
75 |
76 | func (l *Attr) Apply(props TextProps, stamp *common.Stamp) {
77 | for k, v := range props {
78 | if v == nil {
79 | delete(l.Props, k)
80 | } else {
81 | l.Props[k] = v
82 | }
83 | }
84 | l.Stamp = stamp
85 | }
86 |
87 | type TextProps = map[string]any
88 |
--------------------------------------------------------------------------------
/text/tree/ins.go:
--------------------------------------------------------------------------------
1 | package tree
2 |
3 | import (
4 | "github.com/notebox/nb-crdt-go/common"
5 | "github.com/notebox/nb-crdt-go/text/span"
6 | )
7 |
8 | func (n *Node) INS(span *span.INSSpan, minIndex uint32) error {
9 | curr := n.Span
10 | currStartIndex := minIndex + n.leftLength()
11 | nextMinIndex := currStartIndex + curr.Length()
12 | cmp, err := curr.Compare(span)
13 | if err != nil {
14 | return err
15 | }
16 |
17 | switch cmp {
18 | case common.Less:
19 | return n.insIntoRight(span, nextMinIndex)
20 | case common.Greater:
21 | return n.insIntoLeft(span, minIndex)
22 | case common.Prependable:
23 | err := n.insIntoRight(span, nextMinIndex)
24 | if err != nil {
25 | return err
26 | }
27 | n.mergeRight()
28 | return nil
29 | case common.Appendable:
30 | err := n.insIntoLeft(span, minIndex)
31 | if err != nil {
32 | return err
33 | }
34 | n.mergeLeft()
35 | return nil
36 | case common.Splitted:
37 | left, right, err := curr.SplitWith(span)
38 | if err != nil {
39 | return err
40 | }
41 | n.insertPredecessor(*left)
42 | n.Span = *span
43 | n.insertSuccessor(*right)
44 | return nil
45 | case common.Splitting:
46 | left, right, err := span.SplitWith(&curr)
47 | if err != nil {
48 | return err
49 | }
50 | err = n.insIntoRight(right, nextMinIndex)
51 | if err != nil {
52 | return err
53 | }
54 | err = n.insIntoLeft(left, minIndex)
55 | if err != nil {
56 | return err
57 | }
58 | return nil
59 | default:
60 | return common.ExistingSpanOverwrite
61 | }
62 | }
63 |
64 | func (n *Node) insIntoLeft(span *span.INSSpan, minIndex uint32) error {
65 | if n.Left != nil {
66 | err := n.Left.INS(span, minIndex)
67 | if err != nil {
68 | return err
69 | }
70 | n.Left = n.Left.Balance()
71 | return nil
72 | }
73 |
74 | n.Left = New(*span, nil, nil)
75 | return nil
76 | }
77 |
78 | func (n *Node) insIntoRight(span *span.INSSpan, minIndex uint32) error {
79 | if n.Right != nil {
80 | err := n.Right.INS(span, minIndex)
81 | if err != nil {
82 | return err
83 | }
84 | n.Right = n.Right.Balance()
85 | return nil
86 | }
87 |
88 | n.Right = New(*span, nil, nil)
89 | return nil
90 | }
91 |
--------------------------------------------------------------------------------
/text/content/ins_test.go:
--------------------------------------------------------------------------------
1 | package content
2 |
3 | import (
4 | "encoding/json"
5 | "testing"
6 |
7 | "github.com/notebox/nb-crdt-go/text/content/attrs"
8 | "github.com/stretchr/testify/assert"
9 | )
10 |
11 | func TestINSContent(t *testing.T) {
12 | t.Run("JSON", func(t *testing.T) {
13 | stringifiedJSON := `[[[6]],"foobar"]`
14 | var subject INSContent
15 | err := json.Unmarshal([]byte(stringifiedJSON), &subject)
16 | assert.NoError(t, err)
17 | assert.Equal(t, INSContent{text: "foobar", attrs: attrs.Attrs{{Length: 6}}}, subject)
18 | encoded, err := json.Marshal(subject)
19 | assert.NoError(t, err)
20 | assert.Equal(t, stringifiedJSON, string(encoded))
21 | })
22 |
23 | t.Run("Slice", func(t *testing.T) {
24 | subject := INSContent{text: "foobar", attrs: attrs.Attrs{{Length: 6}}}
25 | assert.True(t, subject.Slice(1, 3).Equals(&INSContent{text: "oo", attrs: attrs.Attrs{{Length: 2}}}))
26 | })
27 |
28 | t.Run("Concat", func(t *testing.T) {
29 | a := INSContent{text: "foo", attrs: attrs.Attrs{{Length: 3}}}
30 | b := INSContent{text: "bar", attrs: attrs.Attrs{{Length: 3}}}
31 | assert.True(t, a.Concat(&b).Equals(&INSContent{text: "foobar", attrs: attrs.Attrs{{Length: 6}}}))
32 | })
33 |
34 | t.Run("NewINSContent", func(t *testing.T) {
35 | assert.True(t, NewINSContent("foobar").Equals(&INSContent{text: "foobar", attrs: attrs.Attrs{{Length: 6}}}))
36 | })
37 |
38 | t.Run("others", func(t *testing.T) {
39 | subject := INSContent{text: "aa😀bb🤖cc👍🏿dd강ee", attrs: attrs.Attrs{{Length: 19}}}
40 | assert.Equal(t, uint32(19), subject.Length())
41 | assert.Equal(t, attrs.Attrs{{Length: 19}}, subject.Attrs())
42 | })
43 |
44 | t.Run("FMT", func(t *testing.T) {
45 | subject := INSContent{text: "foobar", attrs: attrs.Attrs{{Length: 6}}}
46 | subject.FMT(2, &FMTContent{length: 3, attrs: attrs.Attrs{{Length: 3, Props: attrs.TextProps{"B": true}}}})
47 | assert.True(t, subject.Equals(&INSContent{text: "foobar", attrs: attrs.Attrs{{Length: 2}, {Length: 3, Props: attrs.TextProps{"B": true}}, {Length: 1}}}))
48 | })
49 |
50 | t.Run("MOD", func(t *testing.T) {
51 | subject := INSContent{text: "foobar", attrs: attrs.Attrs{{Length: 6}}}
52 | subject.MOD(2, &MODContent{text: "xyz"})
53 | assert.True(t, subject.Equals(&INSContent{text: "foxyzr", attrs: attrs.Attrs{{Length: 6}}}))
54 | })
55 | }
56 |
--------------------------------------------------------------------------------
/text/content/ins.go:
--------------------------------------------------------------------------------
1 | package content
2 |
3 | import (
4 | "encoding/json"
5 | "reflect"
6 |
7 | "github.com/notebox/nb-crdt-go/common"
8 | "github.com/notebox/nb-crdt-go/text/content/attrs"
9 | )
10 |
11 | type Meta map[string]*string
12 |
13 | type INSContent struct {
14 | text string
15 | attrs attrs.Attrs
16 | }
17 |
18 | func NewINSContent(text string) *INSContent {
19 | return &INSContent{text, attrs.Attrs{{Length: common.UTF16Length(text)}}}
20 | }
21 |
22 | func (c INSContent) MarshalJSON() ([]byte, error) {
23 | return json.Marshal([]any{c.attrs, c.text})
24 | }
25 |
26 | func (c *INSContent) UnmarshalJSON(data []byte) error {
27 | var raw []json.RawMessage
28 | err := json.Unmarshal(data, &raw)
29 | if err != nil {
30 | return err
31 | }
32 | err = json.Unmarshal(raw[0], &c.attrs)
33 | if err != nil {
34 | return err
35 | }
36 | err = json.Unmarshal(raw[1], &c.text)
37 | if err != nil {
38 | return err
39 | }
40 | return nil
41 | }
42 |
43 | func (c *INSContent) Length() uint32 {
44 | return common.UTF16Length(c.text)
45 | }
46 |
47 | func (c *INSContent) Text() string {
48 | return c.text
49 | }
50 |
51 | func (c *INSContent) Attrs() attrs.Attrs {
52 | return c.attrs
53 | }
54 |
55 | // assuming content is not meta
56 | func (c *INSContent) Concat(other *INSContent) *INSContent {
57 | return &INSContent{c.text + other.Text(), c.attrs.Concat(other.Attrs())}
58 | }
59 |
60 | // assuming content is not meta
61 | func (c *INSContent) Slice(start uint32, end uint32) *INSContent {
62 | return &INSContent{common.UTF16Slice(c.text, start, end), c.attrs.Slice(start, end)}
63 | }
64 |
65 | func (c *INSContent) Equals(other *INSContent) bool {
66 | return c.text == other.Text() && reflect.DeepEqual(c.attrs, other.Attrs())
67 | }
68 |
69 | func (c *INSContent) FMT(index uint32, other *FMTContent) {
70 | left := c.attrs.Slice(0, index)
71 | affected := c.attrs.Slice(index, index+other.Length())
72 | right := c.attrs.Slice(index+other.Length(), c.Length())
73 |
74 | affected.Merge(other.Attrs())
75 |
76 | n := left.Concat(affected).Concat(right)
77 | c.attrs = n
78 | }
79 |
80 | // assuming content is not meta
81 | func (c *INSContent) MOD(index uint32, other *MODContent) {
82 | c.text = common.UTF16Slice(c.text, 0, index) +
83 | other.Text() +
84 | common.UTF16Slice(c.text, index+other.Length(), c.Length())
85 | }
86 |
--------------------------------------------------------------------------------
/text/test/cases.go:
--------------------------------------------------------------------------------
1 | package test
2 |
3 | import (
4 | "github.com/notebox/nb-crdt-go/common"
5 | "github.com/notebox/nb-crdt-go/point"
6 | "github.com/notebox/nb-crdt-go/text/content"
7 | "github.com/notebox/nb-crdt-go/text/content/attrs"
8 | "github.com/notebox/nb-crdt-go/text/span"
9 | )
10 |
11 | type RawCase struct {
12 | Point [][3]uint32
13 | Text string
14 | }
15 |
16 | var Cases = map[common.Order]RawCase{
17 | common.Splitted: {[][3]uint32{{1, 1, 1}, {5, 5, 5}, {8, 8, 8}}, "ghi"},
18 | common.Less: {[][3]uint32{{1, 1, 1}, {5, 5, 9}}, "89a"},
19 | common.Prependable: {[][3]uint32{{1, 1, 1}, {5, 5, 8}}, "789"},
20 | common.RightOverlap: {[][3]uint32{{1, 1, 1}, {5, 5, 7}}, "678"},
21 | common.IncludingRight: {[][3]uint32{{1, 1, 1}, {5, 5, 7}}, "6"},
22 | common.IncludingMiddle: {[][3]uint32{{1, 1, 1}, {5, 5, 6}}, "5"},
23 | common.IncludingLeft: {[][3]uint32{{1, 1, 1}, {5, 5, 5}}, "4"},
24 | common.Equal: {[][3]uint32{{1, 1, 1}, {5, 5, 5}}, "456"},
25 | common.IncludedLeft: {[][3]uint32{{1, 1, 1}, {5, 5, 5}}, "4567"},
26 | common.IncludedMiddle: {[][3]uint32{{1, 1, 1}, {5, 5, 4}}, "34567"},
27 | common.IncludedRight: {[][3]uint32{{1, 1, 1}, {5, 5, 4}}, "3456"},
28 | common.LeftOverlap: {[][3]uint32{{1, 1, 1}, {5, 5, 3}}, "234"},
29 | common.Appendable: {[][3]uint32{{1, 1, 1}, {5, 5, 2}}, "123"},
30 | common.Greater: {[][3]uint32{{1, 1, 1}, {5, 5, 1}}, "012"},
31 | common.Splitting: {[][3]uint32{{1, 1, 1}}, "jkl"},
32 | }
33 |
34 | func PointFrom(raw [][3]uint32) point.Point {
35 | var pts []point.PointTag
36 | for _, pt := range raw {
37 | pts = append(pts, point.PointTag{Priority: pt[0], ReplicaID: pt[1], Nonce: pt[2]})
38 | }
39 | return pts
40 | }
41 |
42 | func INSSpanFrom(raw RawCase) *span.INSSpan {
43 | s := span.New(PointFrom(raw.Point), content.NewINSContent(raw.Text))
44 | return &s
45 | }
46 |
47 | func MODSpanFrom(raw RawCase) *span.MODSpan {
48 | s := span.New(PointFrom(raw.Point), content.NewMODContent(raw.Text))
49 | return &s
50 | }
51 |
52 | func DELSpanFrom(raw RawCase) *span.DELSpan {
53 | s := span.New(PointFrom(raw.Point), content.NewDELContent(common.UTF16Length(raw.Text)))
54 | return &s
55 | }
56 |
57 | func FMTSpanFrom(raw RawCase, props attrs.TextProps) *span.FMTSpan {
58 | s := span.New(PointFrom(raw.Point), content.NewFMTContent(common.UTF16Length(raw.Text), props))
59 | return &s
60 | }
61 |
--------------------------------------------------------------------------------
/block/version_test.go:
--------------------------------------------------------------------------------
1 | package block_test
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/notebox/nb-crdt-go/block"
7 | "github.com/stretchr/testify/assert"
8 | )
9 |
10 | func TestBlockVersion(t *testing.T) {
11 | newSubject := func() block.Version {
12 | return block.Version{59: block.ReplicaNonce{8, 7}, 1: block.ReplicaNonce{5, 9}, 2: block.ReplicaNonce{5, 9}, 3: block.ReplicaNonce{5, 9}}
13 | }
14 |
15 | t.Run("Merge", func(t *testing.T) {
16 | subject := newSubject()
17 | assert.True(t, subject.Merge(block.Version{59: block.ReplicaNonce{7, 6}, 1: block.ReplicaNonce{5, 10}, 2: block.ReplicaNonce{6, 9}, 19: block.ReplicaNonce{1, 1}}))
18 | assert.Equal(t, subject, block.Version{59: block.ReplicaNonce{8, 7}, 1: block.ReplicaNonce{5, 9}, 2: block.ReplicaNonce{6, 9}, 3: block.ReplicaNonce{5, 9}, 19: block.ReplicaNonce{1, 1}})
19 | assert.False(t, newSubject().Merge(block.Version{59: block.ReplicaNonce{8, 7}, 1: block.ReplicaNonce{5, 9}, 2: block.ReplicaNonce{5, 9}}))
20 | })
21 |
22 | t.Run("Add", func(t *testing.T) {
23 | subject := newSubject()
24 | assert.True(t, subject.Add(59, block.ReplicaNonce{9, 7}))
25 | assert.Equal(t, subject, block.Version{59: block.ReplicaNonce{9, 7}, 1: block.ReplicaNonce{5, 9}, 2: block.ReplicaNonce{5, 9}, 3: block.ReplicaNonce{5, 9}})
26 | assert.True(t, subject.Add(4, block.ReplicaNonce{1, 0}))
27 | assert.Equal(t, subject, block.Version{59: block.ReplicaNonce{9, 7}, 1: block.ReplicaNonce{5, 9}, 2: block.ReplicaNonce{5, 9}, 3: block.ReplicaNonce{5, 9}, 4: block.ReplicaNonce{1, 0}})
28 | assert.False(t, subject.Add(59, block.ReplicaNonce{8, 8}))
29 | })
30 |
31 | t.Run("IsNewerOrEqualThan", func(t *testing.T) {
32 | subject := newSubject()
33 | assert.True(t, subject.IsNewerOrEqualThan(nil))
34 | assert.True(t, subject.IsNewerOrEqualThan(subject))
35 | assert.True(t, subject.IsNewerOrEqualThan(block.Version{59: block.ReplicaNonce{8, 8}}))
36 | assert.True(t, subject.IsNewerOrEqualThan(block.Version{59: block.ReplicaNonce{7, 7}}))
37 | assert.True(t, subject.IsNewerOrEqualThan(block.Version{59: block.ReplicaNonce{7, 6}, 1: block.ReplicaNonce{5, 9}}))
38 | assert.False(t, subject.IsNewerOrEqualThan(block.Version{59: block.ReplicaNonce{9, 0}}))
39 | assert.False(t, subject.IsNewerOrEqualThan(block.Version{59: block.ReplicaNonce{7, 6}, 1: block.ReplicaNonce{6, 8}}))
40 | assert.False(t, subject.IsNewerOrEqualThan(block.Version{4: block.ReplicaNonce{1, 0}}))
41 | })
42 | }
43 |
--------------------------------------------------------------------------------
/block/block_test.go:
--------------------------------------------------------------------------------
1 | package block_test
2 |
3 | import (
4 | "encoding/json"
5 | "testing"
6 |
7 | "github.com/notebox/nb-crdt-go/block"
8 | "github.com/notebox/nb-crdt-go/common"
9 | "github.com/stretchr/testify/assert"
10 | )
11 |
12 | func TestNode(t *testing.T) {
13 | t.Run("JSON", func(t *testing.T) {
14 | cases := []string{
15 | `["86905c41-46bc-402e-8e72-f298be4e72e9",{},[[0,0,1]],{"TYPE":[null,"NOTE"]},false,[[[[2147483648,9777,1]],[[[1]],"1"]]],"8aa83876-57ca-422b-a290-b070dd07d2f7"]`,
16 | `["86905c41-46bc-402e-8e72-f298be4e72e9",{},[[0,0,1]],{"TYPE":[null,"NOTE"]},false,null,"8aa83876-57ca-422b-a290-b070dd07d2f7"]`,
17 | `["86905c41-46bc-402e-8e72-f298be4e72e9",{},[[0,0,1]],{"TYPE":[null,"NOTE"]},false]`,
18 | }
19 | for _, stringifiedJSON := range cases {
20 | var subject block.Block
21 | err := json.Unmarshal([]byte(stringifiedJSON), &subject)
22 | assert.NoError(t, err)
23 | encoded, err := json.Marshal(subject)
24 | assert.NoError(t, err)
25 | assert.Equal(t, stringifiedJSON, string(encoded))
26 | }
27 | })
28 |
29 | t.Run("Apply", func(t *testing.T) {
30 | stringifiedBlock := `["86905C41-46BC-402E-8E72-F298BE4E72E9",{},[[0,0,1]],{"TYPE":[null,"NOTE"]},false,[[[[2147483648,9777,1]],[[[1]],"1"]]],"8AA83876-57CA-422B-A290-B070DD07D2F7"]`
31 | var subject block.Block
32 | err := json.Unmarshal([]byte(stringifiedBlock), &subject)
33 | assert.NoError(t, err)
34 |
35 | stringifiedOPs := `{"bDEL":false,"bINS":["76905C41-46BC-402E-8E72-F298BE4E72E9",{},[[2147483647,0,3]],{},false,null,null],"bMOV":["66905C41-46BC-402E-8E72-F298BE4E72E9",[[1,2,3]]],"bSET":{"TYPE":"LINE","SRC":"null"},"tDEL":[[[[1,2,3]],9]],"tFMT":[[[[1,2,3]],[1,[[1,{"B":true},[8,7]]]]]],"tINS":[[[[1,2,3]],[[[3,null,null]],"abc"]]],"tMOD":[[[[1,2,3]],"abc"]]}`
36 | var ops block.Operations
37 | err = json.Unmarshal([]byte(stringifiedOPs), &ops)
38 | assert.NoError(t, err)
39 | ctrb := block.Contribution{
40 | BlockID: subject.BlockID,
41 | Nonce: block.ReplicaNonce{87, 59},
42 | Stamp: common.Stamp{ReplicaID: 11, Timestamp: 12},
43 | Operations: ops,
44 | }
45 | err = subject.Apply(ctrb)
46 | assert.NoError(t, err)
47 | assert.Equal(t, block.ReplicaNonce{87, 59}, subject.Version[11])
48 | })
49 |
50 | t.Run("BlockPoint JSON", func(t *testing.T) {
51 | stringifiedJSON := `["86905c41-46bc-402e-8e72-f298be4e72e9",[[1,2,3]]]`
52 | var subject block.BlockPoint
53 | err := json.Unmarshal([]byte(stringifiedJSON), &subject)
54 | assert.NoError(t, err)
55 | encoded, err := json.Marshal(subject)
56 | assert.NoError(t, err)
57 | assert.Equal(t, stringifiedJSON, string(encoded))
58 | })
59 | }
60 |
--------------------------------------------------------------------------------
/block/props.go:
--------------------------------------------------------------------------------
1 | package block
2 |
3 | import (
4 | "encoding/json"
5 |
6 | "github.com/notebox/nb-crdt-go/common"
7 | )
8 |
9 | type Props map[string]Prop
10 | type Prop struct {
11 | Nested map[string]Prop
12 | Stamp *common.Stamp
13 | Value any
14 | }
15 |
16 | func (prop *Prop) IsNotLeaf() bool {
17 | return prop.Nested != nil && prop.Nested["LEAF"].Value != true
18 | }
19 |
20 | // assuming LEAF flagged nested is not used
21 | func (prop Prop) MarshalJSON() ([]byte, error) {
22 | if prop.IsNotLeaf() {
23 | return json.Marshal(prop.Nested)
24 | }
25 | if prop.Value != nil {
26 | return json.Marshal([]any{prop.Stamp, prop.Value})
27 | }
28 | return json.Marshal([]any{prop.Stamp})
29 | }
30 |
31 | // assuming LEAF flagged nested is not used
32 | func (prop *Prop) UnmarshalJSON(data []byte) error {
33 | if data[0] == '{' {
34 | return json.Unmarshal(data, &prop.Nested)
35 | }
36 | var raw []json.RawMessage
37 | err := json.Unmarshal(data, &raw)
38 | if err != nil {
39 | return err
40 | }
41 | err = json.Unmarshal(raw[0], &prop.Stamp)
42 | if err != nil {
43 | return err
44 | }
45 | if len(raw) == 2 {
46 | return json.Unmarshal(raw[1], &prop.Value)
47 | }
48 | return nil
49 | }
50 |
51 | type PropsDelta = map[string]PropDelta
52 | type PropDelta struct {
53 | Nested map[string]PropDelta
54 | Value any
55 | }
56 |
57 | func (prop *PropDelta) IsNotLeaf() bool {
58 | return prop.Nested != nil && prop.Nested["LEAF"].Value != true
59 | }
60 |
61 | // assuming LEAF flagged nested is not used
62 | func (prop PropDelta) MarshalJSON() ([]byte, error) {
63 | if prop.IsNotLeaf() {
64 | return json.Marshal(prop.Nested)
65 | }
66 | return json.Marshal(prop.Value)
67 | }
68 |
69 | // assuming LEAF flagged nested is not used
70 | func (prop *PropDelta) UnmarshalJSON(data []byte) error {
71 | if data[0] == '{' {
72 | return json.Unmarshal(data, &prop.Nested)
73 | }
74 | return json.Unmarshal(data, &prop.Value)
75 | }
76 |
77 | // assuming LEAF flagged nested is not used and delta is not nil
78 | func UpdateProps(props Props, delta PropsDelta, stamp common.Stamp) Props {
79 | if props == nil {
80 | props = make(Props)
81 | }
82 |
83 | for key, d := range delta {
84 | if d.IsNotLeaf() {
85 | props[key] = Prop{
86 | Nested: UpdateProps(props[key].Nested, d.Nested, stamp),
87 | Stamp: &stamp,
88 | }
89 | } else if props[key].Stamp.IsOlderThan(&stamp) {
90 | props[key] = Prop{
91 | Value: d.Value,
92 | Stamp: &stamp,
93 | }
94 | }
95 | }
96 |
97 | return props
98 | }
99 |
100 | const (
101 | DEL_PROP_KEY = "DEL"
102 | MOV_PROP_KEY = "MOV"
103 | )
104 |
--------------------------------------------------------------------------------
/common/closedrange_test.go:
--------------------------------------------------------------------------------
1 | package common_test
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/notebox/nb-crdt-go/common"
7 | "github.com/stretchr/testify/assert"
8 | )
9 |
10 | func TestClosedRange(t *testing.T) {
11 | subject := common.ClosedRange{Lower: 5, Length: 3}
12 |
13 | t.Run("Upper", func(t *testing.T) {
14 | assert.Equal(t, uint32(7), subject.Upper())
15 | })
16 |
17 | cases := map[common.Order]common.ClosedRange{
18 | common.Less: {Lower: 9, Length: 2},
19 | common.Prependable: {Lower: 8, Length: 1},
20 | common.RightOverlap: {Lower: 7, Length: 2},
21 | common.IncludingRight: {Lower: 7, Length: 1},
22 | common.IncludingMiddle: {Lower: 6, Length: 1},
23 | common.IncludingLeft: {Lower: 5, Length: 1},
24 | common.Equal: {Lower: 5, Length: 3},
25 | common.IncludedLeft: {Lower: 5, Length: 5},
26 | common.IncludedMiddle: {Lower: 4, Length: 5},
27 | common.IncludedRight: {Lower: 3, Length: 5},
28 | common.LeftOverlap: {Lower: 4, Length: 2},
29 | common.Appendable: {Lower: 4, Length: 1},
30 | common.Greater: {Lower: 2, Length: 2},
31 | }
32 |
33 | t.Run("Compare", func(t *testing.T) {
34 | for expected, c := range cases {
35 | assert.Equal(t, expected, subject.Compare(c))
36 | }
37 | })
38 |
39 | t.Run("Intersection", func(t *testing.T) {
40 | // right overlap
41 | c := cases[common.RightOverlap]
42 | result, err := subject.Intersection(c)
43 | assert.NoError(t, err)
44 | assert.Equal(t, c.Lower, result.Lower)
45 | assert.Equal(t, subject.Lower+subject.Length-c.Lower, result.Length)
46 |
47 | // including
48 | for _, order := range []common.Order{common.IncludingRight, common.IncludingMiddle, common.IncludingLeft} {
49 | c = cases[order]
50 | result, err = subject.Intersection(c)
51 | assert.NoError(t, err)
52 | assert.Equal(t, c.Lower, result.Lower)
53 | assert.Equal(t, c.Length, result.Length)
54 | }
55 |
56 | // included
57 | for _, order := range []common.Order{common.IncludedRight, common.IncludedMiddle, common.IncludedLeft} {
58 | c = cases[order]
59 | result, err = subject.Intersection(c)
60 | assert.NoError(t, err)
61 | assert.Equal(t, subject.Lower, result.Lower)
62 | assert.Equal(t, subject.Length, result.Length)
63 | }
64 |
65 | // left overlap
66 | c = cases[common.LeftOverlap]
67 | result, err = subject.Intersection(c)
68 | assert.NoError(t, err)
69 | assert.Equal(t, subject.Lower, result.Lower)
70 | assert.Equal(t, c.Lower+c.Length-subject.Lower, result.Length)
71 | })
72 |
73 | t.Run("NoIntersection", func(t *testing.T) {
74 | other := common.ClosedRange{Lower: 10, Length: 3}
75 | _, err := subject.Intersection(other)
76 | assert.ErrorIs(t, err, common.NoIntersection)
77 | })
78 | }
79 |
--------------------------------------------------------------------------------
/point/point.go:
--------------------------------------------------------------------------------
1 | package point
2 |
3 | import (
4 | "slices"
5 |
6 | "github.com/notebox/nb-crdt-go/common"
7 | )
8 |
9 | // assuming no empty case
10 | type Point []PointTag
11 |
12 | func (p Point) Depth() int {
13 | return len(p)
14 | }
15 |
16 | func (p Point) ReplicaID() common.ReplicaID {
17 | return p[len(p)-1].ReplicaID
18 | }
19 |
20 | func (p Point) Nonce() uint32 {
21 | return p[len(p)-1].Nonce
22 | }
23 |
24 | func (p Point) Clone() Point {
25 | return slices.Clone(p)
26 | }
27 |
28 | func (p Point) WithNonce(nonce common.Nonce) Point {
29 | lastIDX := len(p) - 1
30 | return append(slices.Clone(p[:lastIDX]), p[lastIDX].WithNonce(nonce))
31 | }
32 |
33 | func (p Point) Offset(offset uint32) Point {
34 | return p.WithNonce(p.Nonce() + offset)
35 | }
36 |
37 | func (p Point) Equals(other Point) bool {
38 | return p.ReplicaID() == other.ReplicaID() && p.Nonce() == other.Nonce()
39 | }
40 |
41 | func (p Point) CompareBase(other Point) common.Order {
42 | if p.Equals(other) {
43 | return common.Equal
44 | }
45 |
46 | i := 0
47 | baseCmp := common.Equal
48 | for i < min(p.Depth(), other.Depth())-1 && baseCmp == common.Equal {
49 | baseCmp = p[i].Compare(other[i])
50 | i++
51 | }
52 | if baseCmp == common.Equal {
53 | baseCmp = p[i].CompareBase(other[i])
54 | }
55 |
56 | switch baseCmp {
57 | case common.Equal:
58 | if p.Depth() == other.Depth() {
59 | return common.Equal
60 | }
61 |
62 | if p.Depth() > other.Depth() {
63 | return common.Tagging
64 | } else {
65 | return common.Tagged
66 | }
67 | default: // Less or Greater
68 | return baseCmp
69 | }
70 | }
71 |
72 | func (p Point) Compare(other Point) common.Order {
73 | if p.Equals(other) {
74 | return common.Equal
75 | }
76 |
77 | minimum := min(p.Depth(), other.Depth())
78 | for i := 0; i < minimum; i++ {
79 | result := p[i].Compare(other[i])
80 |
81 | if result != common.Equal {
82 | return result
83 | }
84 | }
85 |
86 | if p.Depth() < other.Depth() {
87 | return common.Less
88 | } else {
89 | return common.Greater
90 | }
91 | }
92 |
93 | func (p Point) DistanceFrom(other Point) (uint32, common.Order, error) {
94 | cmpBase := p.CompareBase(other)
95 | if cmpBase == common.Less || cmpBase == common.Greater {
96 | return 0, common.Equal, common.InvalidDistanceBetweenNoRelation
97 | }
98 |
99 | depth := min(other.Depth(), p.Depth())
100 | nonce := p[depth-1].Nonce
101 | otherNonce := other[depth-1].Nonce
102 |
103 | var distance uint32
104 | if nonce > otherNonce {
105 | distance = nonce - otherNonce
106 | } else {
107 | distance = otherNonce - nonce
108 | }
109 |
110 | return uint32(distance), common.CompareNumber(nonce, otherNonce), nil
111 | }
112 |
--------------------------------------------------------------------------------
/text/content/attrs/attr_test.go:
--------------------------------------------------------------------------------
1 | package attrs_test
2 |
3 | import (
4 | "encoding/json"
5 | "testing"
6 |
7 | "github.com/notebox/nb-crdt-go/common"
8 | "github.com/notebox/nb-crdt-go/text/content/attrs"
9 | "github.com/stretchr/testify/assert"
10 | )
11 |
12 | func TestAttr(t *testing.T) {
13 | t.Run("JSON", func(t *testing.T) {
14 | cases := []struct {
15 | expected attrs.Attr
16 | stringifiedJSON string
17 | }{
18 | {
19 | attrs.Attr{Length: 5, Props: map[string]any{"B": true}, Stamp: &common.Stamp{ReplicaID: 3, Timestamp: 9}},
20 | `[5,{"B":true},[3,9]]`,
21 | },
22 | {
23 | attrs.Attr{Length: 5, Stamp: &common.Stamp{ReplicaID: 3, Timestamp: 9}},
24 | `[5,null,[3,9]]`,
25 | },
26 | {
27 | attrs.Attr{Length: 5, Props: map[string]any{"B": true}},
28 | `[5,{"B":true}]`,
29 | },
30 | {
31 | attrs.Attr{Length: 5},
32 | `[5]`,
33 | },
34 | }
35 |
36 | for _, c := range cases {
37 | var leaf attrs.Attr
38 | err := json.Unmarshal([]byte(c.stringifiedJSON), &leaf)
39 | assert.NoError(t, err)
40 | assert.Equal(t, c.expected, leaf)
41 | encoded, err := json.Marshal(leaf)
42 | assert.NoError(t, err)
43 | assert.Equal(t, c.stringifiedJSON, string(encoded))
44 | }
45 | })
46 |
47 | t.Run("EqualsExceptForLength", func(t *testing.T) {
48 | subject := attrs.Attr{Length: 5, Props: map[string]any{"B": true}, Stamp: &common.Stamp{ReplicaID: 3, Timestamp: 9}}
49 |
50 | assert.True(t, subject.EqualsExceptForLength(&attrs.Attr{Length: 5, Props: map[string]any{"B": true}, Stamp: &common.Stamp{ReplicaID: 3, Timestamp: 9}}))
51 | assert.True(t, subject.EqualsExceptForLength(&attrs.Attr{Length: 3, Props: map[string]any{"B": true}, Stamp: &common.Stamp{ReplicaID: 3, Timestamp: 9}}))
52 | assert.False(t, subject.EqualsExceptForLength(&attrs.Attr{Length: 5, Props: map[string]any{"B": true}, Stamp: &common.Stamp{ReplicaID: 4, Timestamp: 9}}))
53 | assert.False(t, subject.EqualsExceptForLength(&attrs.Attr{Length: 5, Props: map[string]any{"B": false}, Stamp: &common.Stamp{ReplicaID: 3, Timestamp: 9}}))
54 | assert.False(t, subject.EqualsExceptForLength(&attrs.Attr{Length: 5, Stamp: &common.Stamp{ReplicaID: 3, Timestamp: 9}}))
55 | })
56 |
57 | t.Run("Apply", func(t *testing.T) {
58 | subject := attrs.Attr{
59 | Length: 5,
60 | Props: map[string]any{"B": true, "S": true, "COLOR": "red"},
61 | Stamp: &common.Stamp{ReplicaID: 3, Timestamp: 9},
62 | }
63 | stamp := common.Stamp{ReplicaID: 0, Timestamp: 0}
64 |
65 | subject.Apply(map[string]any{"COLOR": "blue", "S": nil}, &stamp)
66 | assert.Equal(t, map[string]any{"COLOR": "blue", "B": true}, subject.Props)
67 | assert.Equal(t, stamp, *subject.Stamp)
68 |
69 | subject.Apply(map[string]any{"COLOR": nil, "B": nil}, &stamp)
70 | assert.Equal(t, 0, len(subject.Props))
71 | assert.Equal(t, stamp, *subject.Stamp)
72 | })
73 | }
74 |
--------------------------------------------------------------------------------
/text/tree/mod.go:
--------------------------------------------------------------------------------
1 | package tree
2 |
3 | import (
4 | "github.com/notebox/nb-crdt-go/common"
5 | "github.com/notebox/nb-crdt-go/text/span"
6 | )
7 |
8 | func (n *Node) MOD(span *span.MODSpan, minIndex uint32) error {
9 | curr := n.Span
10 | currIndex := minIndex + n.leftLength()
11 | nextMinIndex := currIndex + curr.Length()
12 | cmp, err := curr.Compare(span)
13 | if err != nil {
14 | return err
15 | }
16 |
17 | switch cmp {
18 | case common.Less, common.Prependable:
19 | return n.modRight(span, nextMinIndex)
20 | case common.Greater, common.Appendable:
21 | return n.modLeft(span, minIndex)
22 | case common.IncludingLeft, common.IncludingRight, common.IncludingMiddle, common.Equal:
23 | subIndex := span.LowerPoint().Nonce() - curr.LowerPoint().Nonce()
24 | curr.Content.MOD(subIndex, span.Content)
25 | return nil
26 | case common.RightOverlap:
27 | err := n.modRight(span, nextMinIndex)
28 | if err != nil {
29 | return err
30 | }
31 | subIndex := span.LowerPoint().Nonce() - curr.LowerPoint().Nonce()
32 | content := span.Content.Slice(
33 | 0,
34 | curr.UpperPoint().Nonce()-span.LowerPoint().Nonce()+1,
35 | )
36 | curr.Content.MOD(subIndex, content)
37 | return nil
38 | case common.LeftOverlap:
39 | err := n.modLeft(span, minIndex)
40 | if err != nil {
41 | return err
42 | }
43 | content := span.Content.Slice(
44 | curr.LowerPoint().Nonce()-span.LowerPoint().Nonce(),
45 | span.Content.Length(),
46 | )
47 | curr.Content.MOD(0, content)
48 | return nil
49 | case common.IncludedLeft:
50 | err := n.modRight(span, nextMinIndex)
51 | if err != nil {
52 | return err
53 | }
54 | content := span.Content.Slice(0, curr.Length())
55 | curr.Content.MOD(0, content)
56 | return nil
57 | case common.IncludedRight:
58 | err := n.modLeft(span, minIndex)
59 | if err != nil {
60 | return err
61 | }
62 | content := span.Content.Slice(
63 | span.Length()-curr.Length(),
64 | span.Length(),
65 | )
66 | curr.Content.MOD(0, content)
67 | return nil
68 | case common.IncludedMiddle:
69 | err := n.modLeft(span, minIndex)
70 | if err != nil {
71 | return err
72 | }
73 | err = n.modRight(span, nextMinIndex)
74 | if err != nil {
75 | return err
76 | }
77 | startIndex := curr.LowerPoint().Nonce() - span.LowerPoint().Nonce()
78 | content := span.Content.Slice(
79 | startIndex,
80 | startIndex+curr.Length(),
81 | )
82 | curr.Content.MOD(0, content)
83 | return nil
84 | case common.Splitting, common.Splitted:
85 | return nil
86 | }
87 | return nil
88 | }
89 |
90 | func (n *Node) modLeft(span *span.MODSpan, minIndex uint32) error {
91 | if n.Left == nil {
92 | return nil
93 | }
94 |
95 | return n.Left.MOD(span, minIndex)
96 | }
97 |
98 | func (n *Node) modRight(span *span.MODSpan, minIndex uint32) error {
99 | if n.Right == nil {
100 | return nil
101 | }
102 |
103 | return n.Right.MOD(span, minIndex)
104 | }
105 |
--------------------------------------------------------------------------------
/text/tree/fmt.go:
--------------------------------------------------------------------------------
1 | package tree
2 |
3 | import (
4 | "github.com/notebox/nb-crdt-go/common"
5 | "github.com/notebox/nb-crdt-go/text/span"
6 | )
7 |
8 | func (n *Node) FMT(span *span.FMTSpan, minIndex uint32) error {
9 | curr := n.Span
10 | currIndex := minIndex + n.leftLength()
11 | nextMinIndex := currIndex + curr.Length()
12 | cmp, err := curr.Compare(span)
13 | if err != nil {
14 | return err
15 | }
16 |
17 | switch cmp {
18 | case common.Less, common.Prependable:
19 | err := n.fmtRight(span, nextMinIndex)
20 | if err != nil {
21 | return err
22 | }
23 | return nil
24 | case common.Greater, common.Appendable:
25 | err := n.fmtLeft(span, minIndex)
26 | if err != nil {
27 | return err
28 | }
29 | return nil
30 | case common.IncludingLeft, common.IncludingRight, common.IncludingMiddle, common.Equal:
31 | subIndex := span.LowerPoint().Nonce() - curr.LowerPoint().Nonce()
32 | curr.Content.FMT(subIndex, span.Content)
33 | return nil
34 | case common.RightOverlap:
35 | err := n.fmtRight(span, nextMinIndex)
36 | if err != nil {
37 | return err
38 | }
39 | subIndex := span.LowerPoint().Nonce() - curr.LowerPoint().Nonce()
40 | content := span.Content.Slice(
41 | 0,
42 | curr.UpperPoint().Nonce()-span.LowerPoint().Nonce()+1,
43 | )
44 | n.Span.Content.FMT(subIndex, content)
45 | return nil
46 | case common.LeftOverlap:
47 | err := n.fmtLeft(span, minIndex)
48 | if err != nil {
49 | return err
50 | }
51 | content := span.Content.Slice(
52 | curr.LowerPoint().Nonce()-span.LowerPoint().Nonce(),
53 | span.Content.Length(),
54 | )
55 | n.Span.Content.FMT(0, content)
56 | return nil
57 | case common.IncludedLeft:
58 | err := n.fmtRight(span, nextMinIndex)
59 | if err != nil {
60 | return err
61 | }
62 | content := span.Content.Slice(0, curr.Length())
63 | n.Span.Content.FMT(0, content)
64 | return nil
65 | case common.IncludedRight:
66 | err := n.fmtLeft(span, minIndex)
67 | if err != nil {
68 | return err
69 | }
70 | content := span.Content.Slice(
71 | span.Length()-curr.Length(),
72 | span.Length(),
73 | )
74 | n.Span.Content.FMT(0, content)
75 | return nil
76 | case common.IncludedMiddle:
77 | err := n.fmtLeft(span, minIndex)
78 | if err != nil {
79 | return err
80 | }
81 | err = n.fmtRight(span, nextMinIndex)
82 | if err != nil {
83 | return err
84 | }
85 | startIndex := curr.LowerPoint().Nonce() - span.LowerPoint().Nonce()
86 | content := span.Content.Slice(
87 | startIndex,
88 | startIndex+curr.Length(),
89 | )
90 | n.Span.Content.FMT(0, content)
91 | return nil
92 | case common.Splitting, common.Splitted:
93 | return nil
94 | }
95 | return nil
96 | }
97 |
98 | func (n *Node) fmtLeft(span *span.FMTSpan, minIndex uint32) error {
99 | if n.Left == nil {
100 | return nil
101 | }
102 |
103 | return n.Left.FMT(span, minIndex)
104 | }
105 |
106 | func (n *Node) fmtRight(span *span.FMTSpan, minIndex uint32) error {
107 | if n.Right == nil {
108 | return nil
109 | }
110 |
111 | return n.Right.FMT(span, minIndex)
112 | }
113 |
--------------------------------------------------------------------------------
/block/block.go:
--------------------------------------------------------------------------------
1 | package block
2 |
3 | import (
4 | "encoding/json"
5 |
6 | "github.com/notebox/nb-crdt-go/common"
7 | "github.com/notebox/nb-crdt-go/point"
8 | "github.com/notebox/nb-crdt-go/text"
9 | )
10 |
11 | type Block struct {
12 | BlockID common.BlockID
13 | Version Version
14 | Props Props
15 | Text *text.Text
16 | ParentBlockID *common.BlockID
17 | Point point.Point
18 | IsDeleted bool
19 | }
20 |
21 | func (block Block) MarshalJSON() ([]byte, error) {
22 | arr := []any{block.BlockID, block.Version, block.Point, block.Props, block.IsDeleted}
23 | if block.ParentBlockID != nil {
24 | arr = append(arr, block.Text, block.ParentBlockID)
25 | } else if block.Text != nil {
26 | arr = append(arr, block.Text)
27 | }
28 | return json.Marshal(arr)
29 | }
30 |
31 | func (block *Block) UnmarshalJSON(data []byte) error {
32 | var raw []json.RawMessage
33 | err := json.Unmarshal(data, &raw)
34 | if err != nil {
35 | return err
36 | }
37 | err = json.Unmarshal(raw[0], &block.BlockID)
38 | if err != nil {
39 | return err
40 | }
41 | err = json.Unmarshal(raw[1], &block.Version)
42 | if err != nil {
43 | return err
44 | }
45 | err = json.Unmarshal(raw[2], &block.Point)
46 | if err != nil {
47 | return err
48 | }
49 | err = json.Unmarshal(raw[3], &block.Props)
50 | if err != nil {
51 | return err
52 | }
53 | err = json.Unmarshal(raw[4], &block.IsDeleted)
54 | if err != nil {
55 | return err
56 | }
57 | switch len(raw) {
58 | case 7:
59 | err = json.Unmarshal(raw[6], &block.ParentBlockID)
60 | if err != nil {
61 | return err
62 | }
63 | fallthrough
64 | case 6:
65 | err = json.Unmarshal(raw[5], &block.Text)
66 | if err != nil {
67 | return err
68 | }
69 | }
70 | return nil
71 | }
72 |
73 | func (block *Block) Apply(ctrb Contribution) error {
74 | if ctrb.Operations.BDEL != nil {
75 | block.IsDeleted = *ctrb.Operations.BDEL
76 | block.updateProp(DEL_PROP_KEY, &ctrb.Stamp)
77 | }
78 |
79 | if ctrb.Operations.BSET != nil {
80 | block.Props = UpdateProps(block.Props, ctrb.Operations.BSET, ctrb.Stamp)
81 | }
82 |
83 | if ctrb.Operations.BMOV != nil {
84 | block.ParentBlockID = &ctrb.Operations.BMOV.ParentBlockID
85 | block.Point = ctrb.Operations.BMOV.Point
86 | block.updateProp(MOV_PROP_KEY, &ctrb.Stamp)
87 | }
88 |
89 | if block.Text != nil {
90 | for _, ins := range ctrb.Operations.TINS {
91 | err := block.Text.INS(ins)
92 | if err != nil {
93 | return err
94 | }
95 | }
96 |
97 | for _, del := range ctrb.Operations.TDEL {
98 | err := block.Text.DEL(del)
99 | if err != nil {
100 | return err
101 | }
102 | }
103 |
104 | for _, fmt := range ctrb.Operations.TFMT {
105 | err := block.Text.FMT(fmt)
106 | if err != nil {
107 | return err
108 | }
109 | }
110 |
111 | for _, mod := range ctrb.Operations.TMOD {
112 | err := block.Text.MOD(mod)
113 | if err != nil {
114 | return err
115 | }
116 | }
117 | }
118 |
119 | block.Version[ctrb.Stamp.ReplicaID] = ctrb.Nonce
120 | return nil
121 | }
122 |
123 | func (block *Block) updateProp(key string, stamp *common.Stamp) {
124 | if block.Props == nil {
125 | block.Props = make(Props)
126 | }
127 | block.Props[key] = Prop{Stamp: stamp}
128 | }
129 |
--------------------------------------------------------------------------------
/text/tree/del.go:
--------------------------------------------------------------------------------
1 | package tree
2 |
3 | import (
4 | "github.com/notebox/nb-crdt-go/common"
5 | "github.com/notebox/nb-crdt-go/text/span"
6 | )
7 |
8 | func (n *Node) DEL(span *span.DELSpan, minIndex uint32) error {
9 | curr := n.Span
10 | currIndex := minIndex + n.leftLength()
11 | nextMinIndex := currIndex + curr.Length()
12 | cmp, err := curr.Compare(span)
13 | if err != nil {
14 | return err
15 | }
16 |
17 | switch cmp {
18 | case common.Less, common.Prependable:
19 | return n.delRight(span, nextMinIndex)
20 | case common.Greater, common.Appendable:
21 | return n.delLeft(span, minIndex)
22 | case common.IncludingLeft:
23 | seg, err := curr.AppendableSegmentTo(span)
24 | if err != nil {
25 | return err
26 | }
27 | n.Span = *seg
28 | return err
29 | case common.IncludingRight:
30 | seg, err := curr.PrependableSegmentTo(span)
31 | if err != nil {
32 | return err
33 | }
34 | n.Span = *seg
35 | case common.IncludingMiddle:
36 | seg, err := curr.PrependableSegmentTo(span)
37 | if err != nil {
38 | return err
39 | }
40 | n.Span = *seg
41 | seg, err = curr.AppendableSegmentTo(span)
42 | if err != nil {
43 | return err
44 | }
45 | n.insertSuccessor(*seg)
46 | return nil
47 | case common.RightOverlap:
48 | err := n.delRight(span, nextMinIndex)
49 | if err != nil {
50 | return err
51 | }
52 | overlapped, err := span.Intersection(&curr)
53 | if err != nil {
54 | return err
55 | }
56 | return n.DEL(overlapped, minIndex)
57 | case common.LeftOverlap:
58 | overlapped, err := span.Intersection(&curr)
59 | if err != nil {
60 | return err
61 | }
62 | err = n.DEL(overlapped, minIndex)
63 | if err != nil {
64 | return err
65 | }
66 | return n.delLeft(span, minIndex)
67 | case common.Equal:
68 | n.deleteSelf()
69 | return nil
70 | case common.IncludedLeft:
71 | err := n.delRight(span, nextMinIndex)
72 | if err != nil {
73 | return err
74 | }
75 | n.deleteSelf()
76 | return nil
77 | case common.IncludedRight:
78 | err := n.delLeft(span, minIndex)
79 | if err != nil {
80 | return err
81 | }
82 | n.deleteSelf()
83 | return nil
84 | case common.IncludedMiddle:
85 | err := n.delRight(span, nextMinIndex)
86 | if err != nil {
87 | return err
88 | }
89 | err = n.delLeft(span, minIndex)
90 | if err != nil {
91 | return err
92 | }
93 | n.deleteSelf()
94 | return nil
95 | case common.Splitting:
96 | left, right, err := span.SplitWith(&curr)
97 | if err != nil {
98 | return err
99 | }
100 | err = n.DEL(right, minIndex)
101 | if err != nil {
102 | return err
103 | }
104 | err = n.DEL(left, minIndex)
105 | if err != nil {
106 | return err
107 | }
108 | return nil
109 | case common.Splitted:
110 | return nil
111 | }
112 | return nil
113 | }
114 |
115 | func (n *Node) delLeft(span *span.DELSpan, minIndex uint32) error {
116 | if n.Left == nil {
117 | return nil
118 | }
119 |
120 | err := n.Left.DEL(span, minIndex)
121 | if err != nil {
122 | return err
123 | }
124 | n.Left = n.Left.Balance()
125 | return nil
126 | }
127 |
128 | func (n *Node) delRight(span *span.DELSpan, minIndex uint32) error {
129 | if n.Right == nil {
130 | return nil
131 | }
132 |
133 | err := n.Right.DEL(span, minIndex)
134 | if err != nil {
135 | return err
136 | }
137 | n.Right = n.Right.Balance()
138 | return nil
139 | }
140 |
--------------------------------------------------------------------------------
/block/props_test.go:
--------------------------------------------------------------------------------
1 | package block_test
2 |
3 | import (
4 | "encoding/json"
5 | "testing"
6 |
7 | "github.com/notebox/nb-crdt-go/block"
8 | "github.com/notebox/nb-crdt-go/common"
9 | "github.com/stretchr/testify/assert"
10 | )
11 |
12 | func TestBlockProps(t *testing.T) {
13 | t.Run("JSON", func(t *testing.T) {
14 | stringifiedJSON := `{"DB_RECORD":{"0-0":{"VALUE":[null,"go"]}},"MOV":[null],"SRC":[[5,9],"notebox.cloud"],"TYPE":[null,"NOTE"]}`
15 | var props block.Props
16 | err := json.Unmarshal([]byte(stringifiedJSON), &props)
17 | assert.NoError(t, err)
18 | assert.Equal(t, block.Props{
19 | "TYPE": block.Prop{Nested: nil, Stamp: nil, Value: "NOTE"},
20 | "MOV": block.Prop{Nested: nil, Stamp: nil, Value: nil},
21 | "SRC": block.Prop{Nested: nil, Stamp: &common.Stamp{ReplicaID: 5, Timestamp: 9}, Value: "notebox.cloud"},
22 | "DB_RECORD": block.Prop{
23 | Nested: map[string]block.Prop{
24 | "0-0": {
25 | Nested: map[string]block.Prop{
26 | "VALUE": {Nested: nil, Stamp: nil, Value: "go"},
27 | },
28 | },
29 | },
30 | Stamp: nil,
31 | Value: nil,
32 | },
33 | }, props)
34 | encoded, err := json.Marshal(props)
35 | assert.NoError(t, err)
36 | assert.Equal(t, stringifiedJSON, string(encoded))
37 | })
38 |
39 | t.Run("IsLeaf", func(t *testing.T) {
40 | var subject block.Prop
41 | subject = block.Prop{}
42 | assert.False(t, subject.IsNotLeaf())
43 | subject = block.Prop{Nested: map[string]block.Prop{}}
44 | assert.True(t, subject.IsNotLeaf())
45 | subject = block.Prop{Nested: map[string]block.Prop{"LEAF": {}}}
46 | assert.True(t, subject.IsNotLeaf())
47 | subject = block.Prop{Nested: map[string]block.Prop{"LEAF": {Value: true}}}
48 | assert.False(t, subject.IsNotLeaf())
49 | })
50 |
51 | t.Run("UpdateProps", func(t *testing.T) {
52 | cases := []struct {
53 | stamp common.Stamp
54 | delta string
55 | expected string
56 | }{
57 | {common.Stamp{ReplicaID: 1, Timestamp: 2}, `{"X":{"Y":{"Z":"A"}}}`, `{"TYPE":[null,"T"],"X":{"Y":{"Z":[[1,2],"A"]}}}`},
58 | {common.Stamp{ReplicaID: 2, Timestamp: 3}, `{"X":{"Y":{"Z":"B"}}}`, `{"TYPE":[null,"T"],"X":{"Y":{"Z":[[2,3],"B"]}}}`},
59 | {common.Stamp{ReplicaID: 3, Timestamp: 4}, `{"X":{"Y":{"Z":null}}}`, `{"TYPE":[null,"T"],"X":{"Y":{"Z":[[3,4]]}}}`},
60 | }
61 | for _, c := range cases {
62 | subject := block.Props{
63 | "TYPE": block.Prop{Nested: nil, Stamp: nil, Value: "T"},
64 | }
65 | var delta block.PropsDelta
66 | err := json.Unmarshal([]byte(c.delta), &delta)
67 | assert.NoError(t, err)
68 | updated := block.UpdateProps(subject, delta, c.stamp)
69 | encoded, err := json.Marshal(updated)
70 | assert.NoError(t, err)
71 | assert.Equal(t, c.expected, string(encoded))
72 | }
73 | })
74 | }
75 |
76 | func TestBlockPropsDelta(t *testing.T) {
77 | t.Run("JSON", func(t *testing.T) {
78 | stringifiedJSON := `{"X":{"Y":{"Z":"A"}}}`
79 | var delta block.PropsDelta
80 | err := json.Unmarshal([]byte(stringifiedJSON), &delta)
81 | assert.NoError(t, err)
82 | assert.Equal(t, block.PropsDelta{
83 | "X": block.PropDelta{
84 | Nested: map[string]block.PropDelta{
85 | "Y": {
86 | Nested: map[string]block.PropDelta{
87 | "Z": {Nested: nil, Value: "A"},
88 | },
89 | },
90 | },
91 | },
92 | }, delta)
93 | encoded, err := json.Marshal(delta)
94 | assert.NoError(t, err)
95 | assert.Equal(t, stringifiedJSON, string(encoded))
96 | })
97 | }
98 |
--------------------------------------------------------------------------------
/text/content/attrs/attrs.go:
--------------------------------------------------------------------------------
1 | package attrs
2 |
3 | import (
4 | "slices"
5 |
6 | "github.com/notebox/nb-crdt-go/common"
7 | )
8 |
9 | type Attrs []Attr
10 |
11 | func (attrs Attrs) Clone() Attrs {
12 | return slices.Clone(attrs)
13 | }
14 |
15 | func (attrs Attrs) Concat(other Attrs) Attrs {
16 | boundaryIndex := len(attrs)
17 | leaves := append(attrs, other...)
18 |
19 | if boundaryIndex < 1 || boundaryIndex >= len(leaves) {
20 | return leaves
21 | }
22 |
23 | if leaves[boundaryIndex-1].EqualsExceptForLength(&leaves[boundaryIndex]) {
24 | leaves[boundaryIndex-1].Length += leaves[boundaryIndex].Length
25 | leaves = append(leaves[:boundaryIndex], leaves[boundaryIndex+1:]...)
26 | }
27 |
28 | return leaves
29 | }
30 |
31 | func (attrs Attrs) Slice(start, end uint32) Attrs {
32 | if end-start < 1 {
33 | return make(Attrs, 0)
34 | }
35 |
36 | leaves := attrs.Clone()
37 | nextIndex := leaves[0].Length
38 |
39 | for nextIndex <= start {
40 | leaves = leaves[1:]
41 | nextIndex += leaves[0].Length
42 | }
43 | leaves[0].Length = nextIndex - start
44 |
45 | index := 0
46 | for nextIndex < end {
47 | index++
48 | nextIndex += leaves[index].Length
49 | }
50 |
51 | if nextIndex > end {
52 | leaves[index].Length -= (nextIndex - end)
53 | }
54 |
55 | return leaves[:index+1]
56 | }
57 |
58 | // TODO deprecated
59 | // func (attrs *Attrs) Apply(props TextProps, stamp common.Stamp) {
60 | // beforeIDX := -1
61 | // newLeaves := make([]Attr, 0)
62 | // for idx, leaf := range *attrs {
63 | // leaf.Apply(props, &stamp)
64 | // if beforeIDX > -1 && newLeaves[beforeIDX].EqualsExceptForLength(&leaf) {
65 | // newLeaves[beforeIDX].Length += leaf.Length
66 | // } else {
67 | // newLeaves = append(newLeaves, leaf)
68 | // }
69 | // beforeIDX = idx
70 | // }
71 | // *attrs = newLeaves
72 | // }
73 |
74 | func (attrs *Attrs) Merge(other Attrs) {
75 | newLeaves := make([]Attr, 0)
76 | count := len(*attrs)
77 | otherCount := len(other)
78 | if count == 0 {
79 | return
80 | }
81 |
82 | idx := 0
83 | otherIDX := 0
84 | leaf := (*attrs)[idx]
85 | otherAttr := other[otherIDX]
86 | leafLength := leaf.Length
87 | otherAttrLength := otherAttr.Length
88 |
89 | for leafLength > 0 {
90 | var newProps *TextProps
91 | var newStamp *common.Stamp
92 | var newLength uint32
93 |
94 | if leaf.Stamp.IsOlderThan(otherAttr.Stamp) {
95 | newProps = &otherAttr.Props
96 | newStamp = otherAttr.Stamp
97 | } else {
98 | newProps = &leaf.Props
99 | newStamp = leaf.Stamp
100 | }
101 |
102 | if leafLength < otherAttrLength {
103 | newLength = leafLength
104 | } else {
105 | newLength = otherAttrLength
106 | }
107 |
108 | newAttr := Attr{Length: newLength, Props: *newProps, Stamp: newStamp}
109 | lastNewAttrIndex := len(newLeaves) - 1
110 | if lastNewAttrIndex > -1 && newLeaves[lastNewAttrIndex].EqualsExceptForLength(&newAttr) {
111 | newLeaves[lastNewAttrIndex].Length += newAttr.Length
112 | } else {
113 | newLeaves = append(newLeaves, newAttr)
114 | }
115 |
116 | leafLength -= newLength
117 | otherAttrLength -= newLength
118 |
119 | if leafLength < 1 {
120 | idx++
121 | if idx < count {
122 | leaf = (*attrs)[idx]
123 | leafLength = leaf.Length
124 | } else {
125 | leafLength = 0
126 | }
127 | }
128 |
129 | if otherAttrLength < 1 {
130 | otherIDX++
131 | if otherIDX < otherCount {
132 | otherAttr = other[otherIDX]
133 | otherAttrLength = otherAttr.Length
134 | } else {
135 | otherAttrLength = 0
136 | }
137 | }
138 | }
139 | *attrs = newLeaves
140 | }
141 |
--------------------------------------------------------------------------------
/point/tag_test.go:
--------------------------------------------------------------------------------
1 | package point_test
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/notebox/nb-crdt-go/common" // Replace with the correct package path
7 | "github.com/notebox/nb-crdt-go/point"
8 | "github.com/stretchr/testify/assert"
9 | )
10 |
11 | func TestPointTag(t *testing.T) {
12 | var subject point.PointTag
13 |
14 | t.Run("MinTag", func(t *testing.T) {
15 | subject = point.MinTag
16 | assert.Equal(t, common.Priority(common.UInt32Min), subject.Priority)
17 | assert.Equal(t, common.ReplicaID(0), subject.ReplicaID)
18 | assert.Equal(t, uint32(1), subject.Nonce)
19 | })
20 |
21 | t.Run("MidTag", func(t *testing.T) {
22 | subject = point.MidTag
23 | assert.Equal(t, common.Priority(common.UInt32Mid), subject.Priority)
24 | assert.Equal(t, common.ReplicaID(0), subject.ReplicaID)
25 | assert.Equal(t, uint32(3), subject.Nonce)
26 | })
27 |
28 | t.Run("MaxTag", func(t *testing.T) {
29 | subject = point.MaxTag
30 | assert.Equal(t, common.Priority(common.UInt32Max), subject.Priority)
31 | assert.Equal(t, common.ReplicaID(0), subject.ReplicaID)
32 | assert.Equal(t, uint32(2), subject.Nonce)
33 | })
34 |
35 | subject = point.PointTag{
36 | Priority: 1,
37 | ReplicaID: 2,
38 | Nonce: 3,
39 | }
40 |
41 | t.Run("WithNonce", func(t *testing.T) {
42 | target := subject.WithNonce(4)
43 | assert.Equal(t, subject.Priority, target.Priority)
44 | assert.Equal(t, subject.ReplicaID, target.ReplicaID)
45 | assert.Equal(t, uint32(4), target.Nonce)
46 | assert.NotEqual(t, subject.Nonce, target.Nonce)
47 | })
48 |
49 | t.Run("CompareBase", func(t *testing.T) {
50 | cases := []struct {
51 | expected common.Order
52 | tag point.PointTag
53 | }{
54 | {common.Equal, point.PointTag{Priority: subject.Priority, ReplicaID: subject.ReplicaID, Nonce: subject.Nonce}},
55 | {common.Equal, point.PointTag{Priority: subject.Priority, ReplicaID: subject.ReplicaID, Nonce: subject.Nonce + 1}},
56 | {common.Greater, point.PointTag{Priority: subject.Priority - 1, ReplicaID: subject.ReplicaID, Nonce: subject.Nonce + 1}},
57 | {common.Greater, point.PointTag{Priority: subject.Priority, ReplicaID: subject.ReplicaID - 1, Nonce: subject.Nonce + 1}},
58 | {common.Less, point.PointTag{Priority: subject.Priority + 1, ReplicaID: subject.ReplicaID, Nonce: subject.Nonce - 1}},
59 | {common.Less, point.PointTag{Priority: subject.Priority, ReplicaID: subject.ReplicaID + 1, Nonce: subject.Nonce - 1}},
60 | }
61 | for _, c := range cases {
62 | assert.Equal(t, c.expected, subject.CompareBase(c.tag))
63 | }
64 | })
65 |
66 | t.Run("Compare", func(t *testing.T) {
67 | cases := []struct {
68 | expected common.Order
69 | tag point.PointTag
70 | }{
71 | {common.Equal, point.PointTag{Priority: subject.Priority, ReplicaID: subject.ReplicaID, Nonce: subject.Nonce}},
72 | {common.Less, point.PointTag{Priority: subject.Priority, ReplicaID: subject.ReplicaID, Nonce: subject.Nonce + 1}},
73 | {common.Greater, point.PointTag{Priority: subject.Priority, ReplicaID: subject.ReplicaID, Nonce: subject.Nonce - 1}},
74 | {common.Greater, point.PointTag{Priority: subject.Priority - 1, ReplicaID: subject.ReplicaID, Nonce: subject.Nonce + 1}},
75 | {common.Greater, point.PointTag{Priority: subject.Priority, ReplicaID: subject.ReplicaID - 1, Nonce: subject.Nonce + 1}},
76 | {common.Less, point.PointTag{Priority: subject.Priority + 1, ReplicaID: subject.ReplicaID, Nonce: subject.Nonce - 1}},
77 | {common.Less, point.PointTag{Priority: subject.Priority, ReplicaID: subject.ReplicaID + 1, Nonce: subject.Nonce - 1}},
78 | }
79 | for _, c := range cases {
80 | assert.Equal(t, c.expected, subject.Compare(c.tag))
81 | }
82 | })
83 | }
84 |
--------------------------------------------------------------------------------
/text/text_test.go:
--------------------------------------------------------------------------------
1 | package text_test
2 |
3 | import (
4 | "encoding/json"
5 | "testing"
6 |
7 | "github.com/notebox/nb-crdt-go/common"
8 | "github.com/notebox/nb-crdt-go/text"
9 | "github.com/notebox/nb-crdt-go/text/content/attrs"
10 | "github.com/notebox/nb-crdt-go/text/span"
11 | "github.com/notebox/nb-crdt-go/text/test"
12 | "github.com/notebox/nb-crdt-go/text/tree"
13 | "github.com/stretchr/testify/assert"
14 | )
15 |
16 | func TestText(t *testing.T) {
17 | t.Run("JSON", func(t *testing.T) {
18 | stringifiedJSON := "[[[[1,2,3]],[[[6]],\"foobar\"]],[[[4,5,6]],[[[4]],\"kang\"]]]"
19 | var subject text.Text
20 | err := json.Unmarshal([]byte(stringifiedJSON), &subject)
21 | assert.NoError(t, err)
22 | assert.Equal(t, text.Text{Node: tree.NewFromSpans([]*span.INSSpan{
23 | test.INSSpanFrom(test.RawCase{Point: [][3]uint32{{1, 2, 3}}, Text: "foobar"}),
24 | test.INSSpanFrom(test.RawCase{Point: [][3]uint32{{4, 5, 6}}, Text: "kang"}),
25 | })}, subject)
26 | encoded, err := json.Marshal(subject)
27 | assert.NoError(t, err)
28 | assert.Equal(t, stringifiedJSON, string(encoded))
29 | })
30 |
31 | t.Run("JSON Empty Node", func(t *testing.T) {
32 | stringifiedJSON := "[]"
33 | var subject text.Text
34 | err := json.Unmarshal([]byte(stringifiedJSON), &subject)
35 | assert.NoError(t, err)
36 | assert.Equal(t, text.Text{}, subject)
37 | encoded, err := json.Marshal(subject)
38 | assert.NoError(t, err)
39 | assert.Equal(t, stringifiedJSON, string(encoded))
40 | })
41 |
42 | t.Run("String, Spans", func(t *testing.T) {
43 | ls := test.INSSpanFrom(test.Cases[common.Greater])
44 | s := test.INSSpanFrom(test.Cases[common.Equal])
45 | rs := test.INSSpanFrom(test.Cases[common.Less])
46 | subject := text.Text{Node: tree.NewFromSpans([]*span.INSSpan{ls, s, rs})}
47 |
48 | assert.Equal(t, "01245689a", subject.String())
49 |
50 | spans := subject.Spans()
51 | assert.Equal(t, []*span.INSSpan{ls, s, rs}, spans)
52 | })
53 |
54 | t.Run("INS", func(t *testing.T) {
55 | subject := text.Text{}
56 |
57 | subject.INS(test.INSSpanFrom(test.RawCase{Point: [][3]uint32{{5, 5, 3}}, Text: "a"}))
58 | assert.Equal(t, "a", subject.String())
59 |
60 | subject.INS(test.INSSpanFrom(test.RawCase{Point: [][3]uint32{{5, 5, 4}}, Text: "b"}))
61 | assert.Equal(t, "ab", subject.String())
62 | })
63 |
64 | t.Run("DEL", func(t *testing.T) {
65 | subject := text.Text{Node: tree.NewFromSpans([]*span.INSSpan{
66 | test.INSSpanFrom(test.RawCase{Point: [][3]uint32{{5, 5, 1}}, Text: "a"}),
67 | test.INSSpanFrom(test.RawCase{Point: [][3]uint32{{5, 5, 3}}, Text: "b"}),
68 | test.INSSpanFrom(test.RawCase{Point: [][3]uint32{{5, 5, 5}}, Text: "c"}),
69 | })}
70 |
71 | subject.DEL(test.DELSpanFrom(test.RawCase{Point: [][3]uint32{{5, 5, 3}}, Text: "b"}))
72 | assert.Equal(t, "ac", subject.String())
73 | })
74 |
75 | t.Run("MOD", func(t *testing.T) {
76 | subject := text.Text{Node: tree.NewFromSpans([]*span.INSSpan{
77 | test.INSSpanFrom(test.RawCase{Point: [][3]uint32{{5, 5, 1}}, Text: "a"}),
78 | test.INSSpanFrom(test.RawCase{Point: [][3]uint32{{5, 5, 3}}, Text: "b"}),
79 | test.INSSpanFrom(test.RawCase{Point: [][3]uint32{{5, 5, 5}}, Text: "c"}),
80 | })}
81 |
82 | subject.MOD(test.MODSpanFrom(test.RawCase{Point: [][3]uint32{{5, 5, 3}}, Text: "x"}))
83 | assert.Equal(t, "axc", subject.String())
84 | })
85 |
86 | t.Run("FMT", func(t *testing.T) {
87 | subject := text.Text{Node: tree.NewFromSpans([]*span.INSSpan{
88 | test.INSSpanFrom(test.RawCase{Point: [][3]uint32{{5, 5, 1}}, Text: "a"}),
89 | test.INSSpanFrom(test.RawCase{Point: [][3]uint32{{5, 5, 3}}, Text: "b"}),
90 | test.INSSpanFrom(test.RawCase{Point: [][3]uint32{{5, 5, 5}}, Text: "c"}),
91 | })}
92 |
93 | subject.FMT(test.FMTSpanFrom(test.RawCase{Point: [][3]uint32{{5, 5, 3}}, Text: "x"}, attrs.TextProps{"B": true}))
94 | encoded, err := subject.MarshalJSON()
95 | assert.NoError(t, err)
96 | assert.Equal(t, `[[[[5,5,1]],[[[1]],"a"]],[[[5,5,3]],[[[1,{"B":true}]],"b"]],[[[5,5,5]],[[[1]],"c"]]]`, string(encoded))
97 | })
98 | }
99 |
--------------------------------------------------------------------------------
/text/tree/ins_test.go:
--------------------------------------------------------------------------------
1 | package tree_test
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/notebox/nb-crdt-go/common"
7 | "github.com/notebox/nb-crdt-go/text/test"
8 | "github.com/notebox/nb-crdt-go/text/tree"
9 | "github.com/stretchr/testify/assert"
10 | )
11 |
12 | func TestNodeINS(t *testing.T) {
13 | t.Run("less", func(t *testing.T) {
14 | subject := tree.New(
15 | *test.INSSpanFrom(test.Cases[common.Equal]),
16 | nil,
17 | tree.New(*test.INSSpanFrom(test.Cases[common.Less]), nil, nil),
18 | )
19 | span := test.INSSpanFrom(test.RawCase{Point: [][3]uint32{{1, 1, 1}, {5, 6, 9}}, Text: "x"})
20 | err := subject.INS(span, 0)
21 | assert.NoError(t, err)
22 | assert.Nil(t, subject.Left)
23 | assert.True(t, subject.Right.Right.Span.Equals(span))
24 | assert.True(t, subject.Right.Span.Equals(test.INSSpanFrom(test.Cases[common.Less])))
25 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.Cases[common.Equal])))
26 | })
27 |
28 | t.Run("prependable", func(t *testing.T) {
29 | subject := tree.New(
30 | *test.INSSpanFrom(test.Cases[common.Equal]),
31 | nil,
32 | nil,
33 | )
34 | err := subject.INS(test.INSSpanFrom(test.Cases[common.Prependable]), 0)
35 | assert.NoError(t, err)
36 | assert.Nil(t, subject.Left)
37 | assert.Nil(t, subject.Right)
38 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.RawCase{Point: test.Cases[common.Equal].Point, Text: "456789"})))
39 | })
40 |
41 | t.Run("greater", func(t *testing.T) {
42 | subject := tree.New(
43 | *test.INSSpanFrom(test.Cases[common.Equal]),
44 | tree.New(*test.INSSpanFrom(test.Cases[common.Greater]), nil, nil),
45 | nil,
46 | )
47 | span := test.INSSpanFrom(test.RawCase{Point: [][3]uint32{{1, 1, 1}, {5, 4, 1}}, Text: "x"})
48 | err := subject.INS(span, 0)
49 | assert.NoError(t, err)
50 | assert.True(t, subject.Left.Left.Span.Equals(span))
51 | assert.True(t, subject.Left.Span.Equals(test.INSSpanFrom(test.Cases[common.Greater])))
52 | assert.Nil(t, subject.Right)
53 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.Cases[common.Equal])))
54 | })
55 |
56 | t.Run("appendable", func(t *testing.T) {
57 | subject := tree.New(
58 | *test.INSSpanFrom(test.Cases[common.Equal]),
59 | nil,
60 | nil,
61 | )
62 | err := subject.INS(test.INSSpanFrom(test.Cases[common.Appendable]), 0)
63 | assert.NoError(t, err)
64 | assert.Nil(t, subject.Left)
65 | assert.Nil(t, subject.Right)
66 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.RawCase{Point: test.Cases[common.Appendable].Point, Text: "123456"})))
67 | })
68 |
69 | t.Run("splitted", func(t *testing.T) {
70 | subject := tree.New(
71 | *test.INSSpanFrom(test.Cases[common.Equal]),
72 | nil,
73 | nil,
74 | )
75 | err := subject.INS(test.INSSpanFrom(test.Cases[common.Splitted]), 0)
76 | assert.NoError(t, err)
77 | assert.True(t, subject.Left.Span.Equals(test.INSSpanFrom(test.RawCase{Point: test.Cases[common.Equal].Point, Text: "4"})))
78 | assert.True(t, subject.Right.Span.Equals(test.INSSpanFrom(test.RawCase{Point: [][3]uint32{{1, 1, 1}, {5, 5, 6}}, Text: "56"})))
79 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.Cases[common.Splitted])))
80 | })
81 |
82 | t.Run("splitting", func(t *testing.T) {
83 | subject := tree.New(
84 | *test.INSSpanFrom(test.Cases[common.Equal]),
85 | nil,
86 | nil,
87 | )
88 | err := subject.INS(test.INSSpanFrom(test.Cases[common.Splitting]), 0)
89 | assert.NoError(t, err)
90 | assert.True(t, subject.Left.Span.Equals(test.INSSpanFrom(test.RawCase{Point: test.Cases[common.Splitting].Point, Text: "j"})))
91 | assert.True(t, subject.Right.Span.Equals(test.INSSpanFrom(test.RawCase{Point: [][3]uint32{{1, 1, 2}}, Text: "kl"})))
92 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.Cases[common.Equal])))
93 | })
94 |
95 | t.Run("right overlap, left overlap, including left, including middle, including right, included left, included middle, included right, equal", func(t *testing.T) {
96 | for _, order := range []common.Order{common.RightOverlap, common.LeftOverlap, common.IncludingLeft, common.IncludingMiddle, common.IncludingRight, common.IncludedLeft, common.IncludedMiddle, common.IncludedRight, common.Equal} {
97 | subject := tree.New(
98 | *test.INSSpanFrom(test.Cases[common.Equal]),
99 | nil,
100 | nil,
101 | )
102 | err := subject.INS(test.INSSpanFrom(test.Cases[order]), 0)
103 | assert.ErrorIs(t, err, common.ExistingSpanOverwrite)
104 | }
105 | })
106 | }
107 |
--------------------------------------------------------------------------------
/text/content/attrs/attrs_test.go:
--------------------------------------------------------------------------------
1 | package attrs_test
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/notebox/nb-crdt-go/common"
7 | "github.com/notebox/nb-crdt-go/text/content/attrs"
8 | "github.com/stretchr/testify/assert"
9 | )
10 |
11 | func TestAttributes(t *testing.T) {
12 | t.Run("Concat", func(t *testing.T) {
13 | var subject attrs.Attrs
14 | leaves := []attrs.Attr{
15 | {
16 | Length: 5,
17 | Props: attrs.TextProps{"B": true},
18 | Stamp: &common.Stamp{ReplicaID: 3, Timestamp: 9},
19 | },
20 | {
21 | Length: 10,
22 | Props: attrs.TextProps{"S": true},
23 | Stamp: &common.Stamp{ReplicaID: 3, Timestamp: 9},
24 | },
25 | }
26 | subject = subject.Concat(leaves)
27 | assert.Equal(t, attrs.Attrs(leaves), subject)
28 |
29 | concatenated := subject.Concat(leaves)
30 | assert.Equal(t, concatenated, attrs.Attrs(append(leaves, leaves...)))
31 |
32 | optimized := subject.Concat([]attrs.Attr{{Length: 2, Props: leaves[1].Props, Stamp: leaves[1].Stamp}})
33 | assert.Equal(t, len(optimized), 2)
34 | assert.Equal(t, optimized[1].Length, uint32(12))
35 | assert.True(t, optimized[1].EqualsExceptForLength(&leaves[1]))
36 | })
37 |
38 | t.Run("Slice", func(t *testing.T) {
39 | leaves := []attrs.Attr{
40 | {
41 | Length: 5,
42 | Props: attrs.TextProps{"B": true},
43 | Stamp: &common.Stamp{ReplicaID: 3, Timestamp: 9},
44 | },
45 | {
46 | Length: 10,
47 | Props: attrs.TextProps{"S": true},
48 | Stamp: &common.Stamp{ReplicaID: 3, Timestamp: 9},
49 | },
50 | }
51 | subject := attrs.Attrs(leaves)
52 |
53 | assert.Equal(t, 0, len(subject.Slice(3, 3)))
54 | assert.Equal(t, attrs.Attrs{leaves[0]}, subject.Slice(0, 5))
55 | assert.Equal(t, attrs.Attrs{leaves[1]}, subject.Slice(5, 15))
56 | assert.Equal(t, attrs.Attrs{
57 | {Length: 1, Props: leaves[0].Props, Stamp: leaves[0].Stamp},
58 | {Length: 1, Props: leaves[1].Props, Stamp: leaves[1].Stamp},
59 | }, subject.Slice(4, 6))
60 | })
61 |
62 | t.Run("Merge - one to nil", func(t *testing.T) {
63 | var subject attrs.Attrs
64 | subject.Merge(attrs.Attrs{{
65 | Length: 10,
66 | Props: attrs.TextProps{"B": true},
67 | Stamp: &common.Stamp{ReplicaID: 2, Timestamp: 2},
68 | }})
69 | assert.Nil(t, subject)
70 | })
71 |
72 | t.Run("Merge - one to many", func(t *testing.T) {
73 | subject := attrs.Attrs{
74 | {
75 | Length: 2,
76 | Props: attrs.TextProps{"I": true},
77 | Stamp: nil,
78 | },
79 | {
80 | Length: 2,
81 | Props: nil,
82 | Stamp: &common.Stamp{ReplicaID: 1, Timestamp: 1},
83 | },
84 | {
85 | Length: 2,
86 | Props: attrs.TextProps{"B": true},
87 | Stamp: &common.Stamp{ReplicaID: 1, Timestamp: 1},
88 | },
89 | {
90 | Length: 2,
91 | Props: attrs.TextProps{"S": true},
92 | Stamp: &common.Stamp{ReplicaID: 1, Timestamp: 1},
93 | },
94 | {
95 | Length: 2,
96 | Props: attrs.TextProps{"CODE": true},
97 | Stamp: &common.Stamp{ReplicaID: 3, Timestamp: 3},
98 | },
99 | }
100 | subject.Merge(attrs.Attrs{{
101 | Length: 10,
102 | Props: attrs.TextProps{"B": true},
103 | Stamp: &common.Stamp{ReplicaID: 2, Timestamp: 2},
104 | }})
105 | expected := attrs.Attrs{
106 | {
107 | Length: 8,
108 | Props: attrs.TextProps{"B": true},
109 | Stamp: &common.Stamp{ReplicaID: 2, Timestamp: 2},
110 | },
111 | {
112 | Length: 2,
113 | Props: attrs.TextProps{"CODE": true},
114 | Stamp: &common.Stamp{ReplicaID: 3, Timestamp: 3},
115 | },
116 | }
117 | assert.Equal(t, expected, subject)
118 | })
119 |
120 | t.Run("Merge - many to one", func(t *testing.T) {
121 | subject := attrs.Attrs{{
122 | Length: 10,
123 | Props: attrs.TextProps{"B": true},
124 | Stamp: nil,
125 | }}
126 | subject.Merge(attrs.Attrs{
127 | {
128 | Length: 2,
129 | Props: attrs.TextProps{"I": true},
130 | Stamp: &common.Stamp{ReplicaID: 1, Timestamp: 1},
131 | },
132 | {
133 | Length: 2,
134 | Props: nil,
135 | Stamp: &common.Stamp{ReplicaID: 1, Timestamp: 1},
136 | },
137 | {
138 | Length: 2,
139 | Props: attrs.TextProps{"B": true},
140 | Stamp: &common.Stamp{ReplicaID: 1, Timestamp: 1},
141 | },
142 | {
143 | Length: 2,
144 | Props: attrs.TextProps{"S": true},
145 | Stamp: &common.Stamp{ReplicaID: 1, Timestamp: 1},
146 | },
147 | {
148 | Length: 2,
149 | Props: attrs.TextProps{"CODE": true},
150 | Stamp: &common.Stamp{ReplicaID: 3, Timestamp: 3},
151 | },
152 | })
153 | expected := attrs.Attrs{
154 | {
155 | Length: 2,
156 | Props: attrs.TextProps{"I": true},
157 | Stamp: &common.Stamp{ReplicaID: 1, Timestamp: 1},
158 | },
159 | {
160 | Length: 2,
161 | Props: nil,
162 | Stamp: &common.Stamp{ReplicaID: 1, Timestamp: 1},
163 | },
164 | {
165 | Length: 2,
166 | Props: attrs.TextProps{"B": true},
167 | Stamp: &common.Stamp{ReplicaID: 1, Timestamp: 1},
168 | },
169 | {
170 | Length: 2,
171 | Props: attrs.TextProps{"S": true},
172 | Stamp: &common.Stamp{ReplicaID: 1, Timestamp: 1},
173 | },
174 | {
175 | Length: 2,
176 | Props: attrs.TextProps{"CODE": true},
177 | Stamp: &common.Stamp{ReplicaID: 3, Timestamp: 3},
178 | },
179 | }
180 | assert.Equal(t, expected, subject)
181 | })
182 | }
183 |
--------------------------------------------------------------------------------
/text/tree/node_test.go:
--------------------------------------------------------------------------------
1 | package tree
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/notebox/nb-crdt-go/common"
7 | "github.com/notebox/nb-crdt-go/text/span"
8 | "github.com/notebox/nb-crdt-go/text/test"
9 | "github.com/stretchr/testify/assert"
10 | )
11 |
12 | func TestNode(t *testing.T) {
13 | t.Run("NewFromSpans, Spans", func(t *testing.T) {
14 | ls := test.INSSpanFrom(test.Cases[common.Greater])
15 | s := test.INSSpanFrom(test.Cases[common.Equal])
16 | rs := test.INSSpanFrom(test.Cases[common.Less])
17 | subject := NewFromSpans([]*span.INSSpan{ls, s, rs})
18 |
19 | assert.Equal(t, *New(*s, New(*ls, nil, nil), New(*rs, nil, nil)), *subject)
20 |
21 | spans := subject.Spans()
22 | assert.Equal(t, []*span.INSSpan{ls, s, rs}, spans)
23 | })
24 |
25 | t.Run("deleteSelf", func(t *testing.T) {
26 | l := test.INSSpanFrom(test.RawCase{Point: [][3]uint32{{5, 5, 1}}, Text: "a"})
27 | c := test.INSSpanFrom(test.RawCase{Point: [][3]uint32{{5, 5, 3}}, Text: "b"})
28 | r := test.INSSpanFrom(test.RawCase{Point: [][3]uint32{{5, 5, 5}}, Text: "c"})
29 | subject := NewFromSpans([]*span.INSSpan{l, c, r})
30 | subject.deleteSelf()
31 | assert.Equal(t, []*span.INSSpan{l, r}, subject.Spans())
32 | subject.deleteSelf()
33 | assert.Equal(t, []*span.INSSpan{l}, subject.Spans())
34 | assert.False(t, subject.ShouldBeDeleted)
35 | subject.deleteSelf()
36 | assert.Equal(t, []*span.INSSpan{l}, subject.Spans())
37 | assert.True(t, subject.ShouldBeDeleted)
38 | })
39 |
40 | t.Run("Balance", func(t *testing.T) {
41 | // 1 / 1 + 2 = 3 / 3 + 4 = 7 / 7 + 8 = 15 /
42 |
43 | span := test.INSSpanFrom(test.Cases[common.Equal])
44 | subject := New(*span, nil, nil)
45 | assert.Equal(t, 1, subject.Rank)
46 |
47 | for i := 0; i < 2; i++ {
48 | subject.insertSuccessor(*span)
49 | }
50 | subject = subject.Balance()
51 | assert.Equal(t, 2, subject.Rank)
52 |
53 | for i := 0; i < 6; i++ {
54 | subject.insertSuccessor(*span)
55 | }
56 | subject = subject.Balance()
57 | assert.Equal(t, 3+1, subject.Rank)
58 |
59 | for i := 0; i < 14; i++ {
60 | subject.insertSuccessor(*span)
61 | }
62 | subject = subject.Balance()
63 | assert.Equal(t, 4+1, subject.Rank)
64 | })
65 |
66 | t.Run("ShouldBeDeleted", func(t *testing.T) {
67 | subject := New(*test.INSSpanFrom(test.Cases[common.Equal]), nil, nil)
68 | assert.NotNil(t, subject.Balance())
69 | subject.ShouldBeDeleted = true
70 | assert.Nil(t, subject.Balance())
71 | })
72 |
73 | t.Run("rank, length, insert, delete", func(t *testing.T) {
74 | cases := make(map[string]*span.INSSpan)
75 | for _, k := range []string{"min", "left", "pred", "mid", "succ", "right", "max"} {
76 | cases[k] = test.INSSpanFrom(test.RawCase{Point: test.Cases[common.Equal].Point, Text: k})
77 | }
78 |
79 | subject := New(*cases["mid"], nil, nil)
80 | assert.Equal(t, 1, subject.Rank)
81 | assert.Equal(t, uint32(3), subject.Length)
82 | assert.Nil(t, subject.predecessorSpan())
83 | assert.Nil(t, subject.successorSpan())
84 |
85 | key := "min"
86 | subject.insertPredecessor(*cases[key])
87 | assert.Equal(t, 2, subject.Rank)
88 | assert.Equal(t, uint32(6), subject.Length)
89 | assert.Equal(t, key, subject.predecessorSpan().Content.Text())
90 | assert.Nil(t, subject.successorSpan())
91 |
92 | key = "max"
93 | subject.insertSuccessor(*cases[key])
94 | assert.Equal(t, 2, subject.Rank)
95 | assert.Equal(t, uint32(9), subject.Length)
96 | assert.Equal(t, key, subject.successorSpan().Content.Text())
97 |
98 | key = "left"
99 | subject.insertPredecessor(*cases[key])
100 | assert.Equal(t, 3, subject.Rank)
101 | assert.Equal(t, uint32(13), subject.Length)
102 | assert.Equal(t, key, subject.predecessorSpan().Content.Text())
103 |
104 | key = "right"
105 | subject.insertSuccessor(*cases[key])
106 | assert.Equal(t, 3, subject.Rank)
107 | assert.Equal(t, uint32(18), subject.Length)
108 | assert.Equal(t, key, subject.successorSpan().Content.Text())
109 |
110 | key = "pred"
111 | subject.insertPredecessor(*cases[key])
112 | assert.Equal(t, 3, subject.Rank)
113 | assert.Equal(t, uint32(22), subject.Length)
114 | assert.Equal(t, key, subject.predecessorSpan().Content.Text())
115 |
116 | key = "succ"
117 | subject.insertSuccessor(*cases[key])
118 | assert.Equal(t, 3, subject.Rank)
119 | assert.Equal(t, uint32(26), subject.Length)
120 | assert.Equal(t, key, subject.successorSpan().Content.Text())
121 |
122 | subject.deleteSuccessor()
123 | assert.Equal(t, 3, subject.Rank)
124 | assert.Equal(t, uint32(22), subject.Length)
125 | assert.Equal(t, "right", subject.successorSpan().Content.Text())
126 |
127 | subject.deletePredecessor()
128 | assert.Equal(t, 3, subject.Rank)
129 | assert.Equal(t, uint32(18), subject.Length)
130 | assert.Equal(t, "left", subject.predecessorSpan().Content.Text())
131 |
132 | subject.deleteSuccessor()
133 | assert.Equal(t, 3, subject.Rank)
134 | assert.Equal(t, uint32(13), subject.Length)
135 | assert.Equal(t, "max", subject.successorSpan().Content.Text())
136 |
137 | subject.deletePredecessor()
138 | assert.Equal(t, 2, subject.Rank)
139 | assert.Equal(t, uint32(9), subject.Length)
140 | assert.Equal(t, "min", subject.predecessorSpan().Content.Text())
141 |
142 | subject.deleteSuccessor()
143 | assert.Equal(t, 2, subject.Rank)
144 | assert.Equal(t, uint32(6), subject.Length)
145 | assert.Nil(t, subject.successorSpan())
146 |
147 | subject.deletePredecessor()
148 | assert.Equal(t, 1, subject.Rank)
149 | assert.Equal(t, uint32(3), subject.Length)
150 | assert.Nil(t, subject.predecessorSpan())
151 | })
152 | }
153 |
--------------------------------------------------------------------------------
/text/tree/del_test.go:
--------------------------------------------------------------------------------
1 | package tree_test
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/notebox/nb-crdt-go/common"
7 | "github.com/notebox/nb-crdt-go/text/test"
8 | "github.com/notebox/nb-crdt-go/text/tree"
9 | "github.com/stretchr/testify/assert"
10 | )
11 |
12 | func TestNodeDEL(t *testing.T) {
13 | t.Run("less", func(t *testing.T) {
14 | subject := tree.New(
15 | *test.INSSpanFrom(test.Cases[common.Equal]),
16 | nil,
17 | tree.New(*test.INSSpanFrom(test.Cases[common.Less]), nil, nil),
18 | )
19 | err := subject.DEL(test.DELSpanFrom(test.Cases[common.Less]), 0)
20 | assert.NoError(t, err)
21 | assert.Nil(t, subject.Left)
22 | assert.Nil(t, subject.Right)
23 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.Cases[common.Equal])))
24 | })
25 |
26 | t.Run("prependable", func(t *testing.T) {
27 | subject := tree.New(
28 | *test.INSSpanFrom(test.Cases[common.Equal]),
29 | nil,
30 | tree.New(*test.INSSpanFrom(test.Cases[common.Prependable]), nil, nil),
31 | )
32 | err := subject.DEL(test.DELSpanFrom(test.Cases[common.Prependable]), 0)
33 | assert.NoError(t, err)
34 | assert.Nil(t, subject.Left)
35 | assert.Nil(t, subject.Right)
36 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.Cases[common.Equal])))
37 | })
38 |
39 | t.Run("greater", func(t *testing.T) {
40 | subject := tree.New(
41 | *test.INSSpanFrom(test.Cases[common.Equal]),
42 | tree.New(*test.INSSpanFrom(test.Cases[common.Greater]), nil, nil),
43 | nil,
44 | )
45 | err := subject.DEL(test.DELSpanFrom(test.Cases[common.Greater]), 0)
46 | assert.NoError(t, err)
47 | assert.Nil(t, subject.Left)
48 | assert.Nil(t, subject.Right)
49 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.Cases[common.Equal])))
50 | })
51 |
52 | t.Run("appendable", func(t *testing.T) {
53 | subject := tree.New(
54 | *test.INSSpanFrom(test.Cases[common.Equal]),
55 | tree.New(*test.INSSpanFrom(test.Cases[common.Appendable]), nil, nil),
56 | nil,
57 | )
58 | err := subject.DEL(test.DELSpanFrom(test.Cases[common.Appendable]), 0)
59 | assert.NoError(t, err)
60 | assert.Nil(t, subject.Left)
61 | assert.Nil(t, subject.Right)
62 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.Cases[common.Equal])))
63 | })
64 |
65 | t.Run("includingLeft", func(t *testing.T) {
66 | subject := tree.New(
67 | *test.INSSpanFrom(test.Cases[common.Equal]),
68 | nil,
69 | nil,
70 | )
71 | err := subject.DEL(test.DELSpanFrom(test.Cases[common.IncludingLeft]), 0)
72 | assert.NoError(t, err)
73 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.RawCase{Point: [][3]uint32{{1, 1, 1}, {5, 5, 6}}, Text: "56"})))
74 | })
75 |
76 | t.Run("includingRight", func(t *testing.T) {
77 | subject := tree.New(
78 | *test.INSSpanFrom(test.Cases[common.Equal]),
79 | nil,
80 | nil,
81 | )
82 | err := subject.DEL(test.DELSpanFrom(test.Cases[common.IncludingRight]), 0)
83 | assert.NoError(t, err)
84 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.RawCase{Point: [][3]uint32{{1, 1, 1}, {5, 5, 5}}, Text: "45"})))
85 | })
86 |
87 | t.Run("includingMiddle", func(t *testing.T) {
88 | subject := tree.New(
89 | *test.INSSpanFrom(test.Cases[common.Equal]),
90 | nil,
91 | nil,
92 | )
93 | err := subject.DEL(test.DELSpanFrom(test.Cases[common.IncludingMiddle]), 0)
94 | assert.NoError(t, err)
95 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.RawCase{Point: [][3]uint32{{1, 1, 1}, {5, 5, 5}}, Text: "4"})))
96 | assert.True(t, subject.Right.Span.Equals(test.INSSpanFrom(test.RawCase{Point: [][3]uint32{{1, 1, 1}, {5, 5, 7}}, Text: "6"})))
97 | })
98 |
99 | t.Run("rightOverlap", func(t *testing.T) {
100 | subject := tree.New(
101 | *test.INSSpanFrom(test.Cases[common.Equal]),
102 | nil,
103 | nil,
104 | )
105 | err := subject.DEL(test.DELSpanFrom(test.Cases[common.RightOverlap]), 0)
106 | assert.NoError(t, err)
107 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.RawCase{Point: [][3]uint32{{1, 1, 1}, {5, 5, 5}}, Text: "45"})))
108 | })
109 |
110 | t.Run("leftOverlap", func(t *testing.T) {
111 | subject := tree.New(
112 | *test.INSSpanFrom(test.Cases[common.Equal]),
113 | nil,
114 | nil,
115 | )
116 | err := subject.DEL(test.DELSpanFrom(test.Cases[common.LeftOverlap]), 0)
117 | assert.NoError(t, err)
118 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.RawCase{Point: [][3]uint32{{1, 1, 1}, {5, 5, 6}}, Text: "56"})))
119 | })
120 |
121 | t.Run("splitted", func(t *testing.T) {
122 | subject := tree.New(
123 | *test.INSSpanFrom(test.Cases[common.Equal]),
124 | nil,
125 | nil,
126 | )
127 | err := subject.DEL(test.DELSpanFrom(test.Cases[common.Splitted]), 0)
128 | assert.NoError(t, err)
129 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.Cases[common.Equal])))
130 | })
131 |
132 | t.Run("splitting", func(t *testing.T) {
133 | subject := tree.New(
134 | *test.INSSpanFrom(test.Cases[common.Equal]),
135 | nil,
136 | nil,
137 | )
138 | err := subject.DEL(test.DELSpanFrom(test.Cases[common.Splitting]), 0)
139 | assert.NoError(t, err)
140 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.Cases[common.Equal])))
141 | })
142 |
143 | t.Run("equal, included left, included right, included middle", func(t *testing.T) {
144 | for _, order := range []common.Order{common.Equal, common.IncludedLeft, common.IncludedRight, common.IncludedMiddle} {
145 | subject := tree.New(
146 | *test.INSSpanFrom(test.Cases[common.Equal]),
147 | nil,
148 | nil,
149 | )
150 | err := subject.DEL(test.DELSpanFrom(test.Cases[order]), 0)
151 | assert.NoError(t, err)
152 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.Cases[common.Equal])))
153 | assert.True(t, subject.ShouldBeDeleted)
154 | }
155 | })
156 | }
157 |
--------------------------------------------------------------------------------
/text/span/span.go:
--------------------------------------------------------------------------------
1 | package span
2 |
3 | import (
4 | "encoding/json"
5 |
6 | "github.com/notebox/nb-crdt-go/common"
7 | "github.com/notebox/nb-crdt-go/point"
8 | "github.com/notebox/nb-crdt-go/text/content"
9 | )
10 |
11 | type Span[C content.Content[C]] struct {
12 | Content C
13 |
14 | lowerPoint point.Point
15 | }
16 |
17 | func New[C content.Content[C]](lowerPoint point.Point, content C) Span[C] {
18 | return Span[C]{lowerPoint: lowerPoint, Content: content}
19 | }
20 |
21 | func (s Span[C]) MarshalJSON() ([]byte, error) {
22 | return json.Marshal([]any{s.lowerPoint, s.Content})
23 | }
24 |
25 | func (s *Span[C]) UnmarshalJSON(data []byte) error {
26 | var raw []json.RawMessage
27 | err := json.Unmarshal(data, &raw)
28 | if err != nil {
29 | return err
30 | }
31 | err = json.Unmarshal(raw[0], &s.lowerPoint)
32 | if err != nil {
33 | return err
34 | }
35 | err = json.Unmarshal(raw[1], &s.Content)
36 | if err != nil {
37 | return err
38 | }
39 | return nil
40 | }
41 |
42 | func (s *Span[C]) Equals(other *Span[C]) bool {
43 | return s.lowerPoint.Equals(other.LowerPoint()) && s.Content.Equals(other.Content)
44 | }
45 |
46 | func (s *Span[C]) LowerPoint() point.Point {
47 | return s.lowerPoint
48 | }
49 |
50 | func (s *Span[C]) ReplicaID() common.ReplicaID {
51 | return s.lowerPoint.ReplicaID()
52 | }
53 |
54 | func (s *Span[C]) Length() uint32 {
55 | return s.Content.Length()
56 | }
57 |
58 | func (s *Span[C]) UpperPoint() point.Point {
59 | return s.NthPoint(s.Length() - 1)
60 | }
61 |
62 | func (s *Span[C]) NthPoint(nth uint32) point.Point {
63 | return s.lowerPoint.Offset(nth)
64 | }
65 |
66 | func (s *Span[C]) NonceRange() common.ClosedRange {
67 | return common.ClosedRange{
68 | Lower: uint32(s.lowerPoint.Nonce()),
69 | Length: s.Length(),
70 | }
71 | }
72 |
73 | func (s *Span[C]) Compare(other AnySpan) (common.Order, error) {
74 | baseCmp := s.lowerPoint.CompareBase(other.LowerPoint())
75 | if baseCmp == common.Less {
76 | return common.Less, nil
77 | }
78 | if baseCmp == common.Greater {
79 | return common.Greater, nil
80 | }
81 |
82 | // EQUAL - only diff nonces
83 | if baseCmp == common.Equal {
84 | return s.NonceRange().Compare(other.NonceRange()), nil
85 | }
86 |
87 | dist, order, err := s.lowerPoint.DistanceFrom(other.LowerPoint())
88 | if err != nil {
89 | return common.Order(-1), err
90 | }
91 |
92 | // TAGGED
93 | if baseCmp == common.Tagged {
94 | if order == common.Greater {
95 | return common.Greater, nil
96 | }
97 |
98 | if dist >= s.Length()-1 {
99 | return common.Less, nil
100 | }
101 |
102 | return common.Splitted, nil
103 | }
104 |
105 | // TAGGING
106 | if order == common.Less {
107 | return common.Less, nil
108 | }
109 | if dist >= other.Length()-1 {
110 | return common.Greater, nil
111 | }
112 |
113 | return common.Splitting, nil
114 | }
115 |
116 | func (s *Span[C]) Append(other *Span[C]) *Span[C] {
117 | return &Span[C]{
118 | lowerPoint: s.lowerPoint,
119 | Content: s.Content.Concat(other.Content),
120 | }
121 | }
122 |
123 | func (s *Span[C]) LeftSplitAt(index uint32) *Span[C] {
124 | return &Span[C]{
125 | lowerPoint: s.lowerPoint,
126 | Content: s.Content.Slice(0, index),
127 | }
128 | }
129 |
130 | func (s *Span[C]) RightSplitAt(index uint32) *Span[C] {
131 | return &Span[C]{
132 | lowerPoint: s.NthPoint(index),
133 | Content: s.Content.Slice(index, s.Length()),
134 | }
135 | }
136 |
137 | func (s *Span[C]) SplitAt(index uint32) (*Span[C], *Span[C], error) {
138 | return s.LeftSplitAt(index), s.RightSplitAt(index), nil
139 | }
140 |
141 | func (s *Span[C]) SplitWith(other AnySpan) (*Span[C], *Span[C], error) {
142 | dist, _, err := s.lowerPoint.DistanceFrom(other.LowerPoint())
143 | if err != nil {
144 | return nil, nil, err
145 | }
146 |
147 | return s.SplitAt(dist + 1)
148 | }
149 |
150 | func (s *Span[C]) AppendableSegmentTo(other AnySpan) (*Span[C], error) {
151 | dist, order, err := s.lowerPoint.DistanceFrom(other.LowerPoint())
152 | if err != nil {
153 | return nil, err
154 | }
155 | if order == common.Less {
156 | return s.RightSplitAt(other.Length() + dist), nil
157 | }
158 |
159 | if other.Length() < dist {
160 | return nil, common.UnAppendable
161 | }
162 | index := other.Length() - dist
163 | return s.RightSplitAt(index), nil
164 | }
165 |
166 | func (s *Span[C]) PrependableSegmentTo(other AnySpan) (*Span[C], error) {
167 | dist, order, err := s.lowerPoint.DistanceFrom(other.LowerPoint())
168 | if err != nil {
169 | return nil, err
170 | }
171 | if order != common.Less || dist > s.Length() {
172 | return nil, common.UnPrependable
173 | }
174 | return s.LeftSplitAt(dist), nil
175 | }
176 |
177 | func (s *Span[C]) Intersection(other AnySpan) (*Span[C], error) {
178 | cmp, err := s.Compare(other)
179 | if err != nil {
180 | return nil, err
181 | }
182 | switch cmp {
183 | case common.Splitted, common.Less, common.Prependable, common.Appendable, common.Greater, common.Splitting:
184 | return nil, common.NoIntersection
185 | default:
186 | break
187 | }
188 |
189 | dist, order, err := s.lowerPoint.DistanceFrom(other.LowerPoint())
190 | if err != nil {
191 | return nil, err
192 | }
193 | if order == common.Less {
194 | end := dist + min(s.Length()-dist, other.Length())
195 | return &Span[C]{
196 | lowerPoint: other.LowerPoint(),
197 | Content: s.Content.Slice(dist, end),
198 | }, nil
199 | }
200 |
201 | end := min(s.Length(), other.Length()-dist)
202 | return &Span[C]{
203 | lowerPoint: s.lowerPoint,
204 | Content: s.Content.Slice(0, end),
205 | }, nil
206 | }
207 |
208 | type INSSpan = Span[*content.INSContent]
209 | type DELSpan = Span[*content.DELContent]
210 | type FMTSpan = Span[*content.FMTContent]
211 | type MODSpan = Span[*content.MODContent]
212 | type AnySpan interface {
213 | LowerPoint() point.Point
214 | NonceRange() common.ClosedRange
215 | Length() uint32
216 | }
217 |
--------------------------------------------------------------------------------
/text/tree/node.go:
--------------------------------------------------------------------------------
1 | package tree
2 |
3 | import (
4 | "github.com/notebox/nb-crdt-go/common"
5 | "github.com/notebox/nb-crdt-go/text/span"
6 | )
7 |
8 | // base AVL Node
9 | type Node struct {
10 | Span span.INSSpan
11 | Left *Node
12 | Right *Node
13 | Length uint32
14 | Rank int
15 |
16 | ShouldBeDeleted bool
17 | }
18 |
19 | func NewFromSpans(spans []*span.INSSpan) *Node {
20 | var left, right *Node
21 | c := len(spans)
22 | midIDX := c / 2
23 | if midIDX > 0 {
24 | left = NewFromSpans(spans[0:midIDX])
25 | }
26 | if midIDX < c-1 {
27 | right = NewFromSpans(spans[midIDX+1:])
28 | }
29 | return New(*spans[midIDX], left, right)
30 | }
31 |
32 | func New(span span.INSSpan, left *Node, right *Node) *Node {
33 | node := &Node{
34 | Span: span,
35 | Left: left,
36 | Right: right,
37 | }
38 | node.update()
39 | return node
40 | }
41 |
42 | func (n *Node) Spans() []*span.INSSpan {
43 | spans := make([]*span.INSSpan, 0)
44 | if n.Left != nil {
45 | spans = append(spans, n.Left.Spans()...)
46 | }
47 | spans = append(spans, &n.Span)
48 | if n.Right != nil {
49 | spans = append(spans, n.Right.Spans()...)
50 | }
51 | return spans
52 | }
53 |
54 | func (n *Node) Balance() *Node {
55 | if n.ShouldBeDeleted {
56 | return nil
57 | }
58 |
59 | node := n
60 | for node.isRightUnbalanced() {
61 | node = node.rotateLeft()
62 | }
63 |
64 | for node.isLeftUnbalanced() {
65 | if node.Left.isRightOriented() {
66 | node.Left = node.Left.rotateLeft()
67 | node.update()
68 | }
69 | node = node.rotateRight()
70 | }
71 |
72 | return node
73 | }
74 |
75 | func (n *Node) predecessorSpan() *span.INSSpan {
76 | if n.Left != nil {
77 | return n.Left.maxSpan()
78 | }
79 | return nil
80 | }
81 |
82 | func (n *Node) successorSpan() *span.INSSpan {
83 | if n.Right != nil {
84 | return n.Right.minSpan()
85 | }
86 | return nil
87 | }
88 |
89 | func (n *Node) insertPredecessor(span span.INSSpan) {
90 | if n.Left != nil {
91 | n.Left = n.Left.insertMax(span)
92 | } else {
93 | n.Left = New(span, nil, nil)
94 | }
95 | n.update()
96 | }
97 |
98 | func (n *Node) insertSuccessor(span span.INSSpan) {
99 | if n.Right != nil {
100 | n.Right = n.Right.insertMin(span)
101 | } else {
102 | n.Right = New(span, nil, nil)
103 | }
104 | n.update()
105 | }
106 |
107 | func (n *Node) deletePredecessor() {
108 | if n.Left != nil {
109 | n.Left = n.Left.deleteMax()
110 | n.update()
111 | }
112 | }
113 |
114 | func (n *Node) deleteSuccessor() {
115 | if n.Right != nil {
116 | n.Right = n.Right.deleteMin()
117 | n.update()
118 | }
119 | }
120 |
121 | func (n *Node) deleteSelf() {
122 | if succ := n.successorSpan(); succ != nil {
123 | n.deleteSuccessor()
124 | n.Span = *succ
125 | n.mergeLeft()
126 | return
127 | }
128 |
129 | if prev := n.predecessorSpan(); prev != nil {
130 | n.deletePredecessor()
131 | n.Span = *prev
132 | n.mergeRight()
133 | return
134 | }
135 |
136 | n.ShouldBeDeleted = true
137 | }
138 |
139 | // assuming content is not meta
140 | func (n *Node) mergeLeft() {
141 | curr := n.Span
142 | if prev := n.predecessorSpan(); prev != nil {
143 | if cmp, err := prev.Compare(&curr); err == nil && cmp == common.Prependable {
144 | n.deletePredecessor()
145 | span := prev.Append(&curr)
146 | n.Span = *span
147 | }
148 | }
149 | }
150 |
151 | // assuming content is not meta
152 | func (n *Node) mergeRight() {
153 | curr := n.Span
154 | if succ := n.successorSpan(); succ != nil {
155 | if cmp, err := succ.Compare(&curr); err == nil && cmp == common.Appendable {
156 | n.deleteSuccessor()
157 | span := curr.Append(succ)
158 | n.Span = *span
159 | }
160 | }
161 | }
162 |
163 | func (n *Node) leftRank() int {
164 | if n.Left == nil {
165 | return 0
166 | }
167 | return n.Left.Rank
168 | }
169 |
170 | func (n *Node) rightRank() int {
171 | if n.Right == nil {
172 | return 0
173 | }
174 | return n.Right.Rank
175 | }
176 |
177 | func (n *Node) leftLength() uint32 {
178 | if n.Left == nil {
179 | return 0
180 | }
181 | return n.Left.Length
182 | }
183 |
184 | func (n *Node) rightLength() uint32 {
185 | if n.Right == nil {
186 | return 0
187 | }
188 | return n.Right.Length
189 | }
190 |
191 | func (n *Node) update() {
192 | n.Rank = 1 + max(n.leftRank(), n.rightRank())
193 | n.Length = n.leftLength() + n.Span.Length() + n.rightLength()
194 | }
195 |
196 | func (n *Node) balanceFactor() int {
197 | return n.rightRank() - n.leftRank()
198 | }
199 |
200 | func (n *Node) isRightUnbalanced() bool {
201 | return n.balanceFactor() > 1
202 | }
203 |
204 | func (n *Node) isLeftUnbalanced() bool {
205 | return n.balanceFactor() < -1
206 | }
207 |
208 | func (n *Node) isRightOriented() bool {
209 | return n.balanceFactor() == 1
210 | }
211 |
212 | func (n *Node) rotateLeft() *Node {
213 | right := n.Right
214 | n.Right = right.Left
215 | n.update()
216 | right.Left = n
217 | right.update()
218 | return right
219 | }
220 |
221 | func (n *Node) rotateRight() *Node {
222 | left := n.Left
223 | n.Left = left.Right
224 | n.update()
225 | left.Right = n
226 | left.update()
227 | return left
228 | }
229 |
230 | func (n *Node) minSpan() *span.INSSpan {
231 | if n.Left != nil {
232 | return n.Left.minSpan()
233 | }
234 | return &n.Span
235 | }
236 |
237 | func (n *Node) maxSpan() *span.INSSpan {
238 | if n.Right != nil {
239 | return n.Right.maxSpan()
240 | }
241 | return &n.Span
242 | }
243 |
244 | func (n *Node) insertMin(span span.INSSpan) *Node {
245 | if n.Left != nil {
246 | n.Left = n.Left.insertMin(span)
247 | } else {
248 | n.Left = New(span, nil, nil)
249 | }
250 | n.update()
251 | return n.Balance()
252 | }
253 |
254 | func (n *Node) insertMax(span span.INSSpan) *Node {
255 | if n.Right != nil {
256 | n.Right = n.Right.insertMax(span)
257 | } else {
258 | n.Right = New(span, nil, nil)
259 | }
260 | n.update()
261 | return n.Balance()
262 | }
263 |
264 | func (n *Node) deleteMin() *Node {
265 | if n.Left == nil {
266 | return n.Right
267 | }
268 | n.Left = n.Left.deleteMin()
269 | n.update()
270 | return n.Balance()
271 | }
272 |
273 | func (n *Node) deleteMax() *Node {
274 | if n.Right == nil {
275 | return n.Left
276 | }
277 | n.Right = n.Right.deleteMax()
278 | n.update()
279 | return n.Balance()
280 | }
281 |
--------------------------------------------------------------------------------
/point/point_test.go:
--------------------------------------------------------------------------------
1 | package point_test
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/notebox/nb-crdt-go/common"
7 | "github.com/notebox/nb-crdt-go/point"
8 | "github.com/stretchr/testify/assert"
9 | )
10 |
11 | func TestPoint(t *testing.T) {
12 | t.Run("Clone", func(t *testing.T) {
13 | subject := &point.Point{{}}
14 | cloned := subject.Clone()
15 | cloned[0].Nonce = 1
16 | assert.NotEqual(t, (*subject)[0].Nonce, cloned[0].Nonce)
17 | })
18 |
19 | t.Run("WithNonce", func(t *testing.T) {
20 | subject := point.Point{point.MidTag, point.MinTag}
21 | withNonce := subject.WithNonce(point.MinTag.Nonce + 1)
22 | assert.Equal(t, subject[0], withNonce[0])
23 | assert.Equal(t, subject[1].Priority, withNonce[1].Priority)
24 | assert.Equal(t, subject[1].ReplicaID, withNonce[1].ReplicaID)
25 | assert.Equal(t, subject[1].Nonce, withNonce[1].Nonce-1)
26 | })
27 |
28 | t.Run("Offset", func(t *testing.T) {
29 | subject := point.Point{point.MidTag, point.MinTag}
30 | withNonce := subject.Offset(59)
31 | assert.Equal(t, subject[0], withNonce[0])
32 | assert.Equal(t, subject[1].Priority, withNonce[1].Priority)
33 | assert.Equal(t, subject[1].ReplicaID, withNonce[1].ReplicaID)
34 | assert.Equal(t, subject[1].Nonce, withNonce[1].Nonce-59)
35 | })
36 |
37 | t.Run("CompareBase", func(t *testing.T) {
38 | testCases := []struct {
39 | name string
40 | point point.Point
41 | other point.Point
42 | expected common.Order
43 | }{
44 | {
45 | name: "Equal points",
46 | point: point.Point{point.MidTag},
47 | other: point.Point{point.MidTag},
48 | expected: common.Equal,
49 | },
50 | {
51 | name: "Different points",
52 | point: point.Point{point.MidTag},
53 | other: point.Point{point.MaxTag},
54 | expected: common.Less,
55 | },
56 | }
57 |
58 | for _, tc := range testCases {
59 | t.Run(tc.name, func(t *testing.T) {
60 | result := tc.point.CompareBase(tc.other)
61 | assert.Equal(t, tc.expected, result)
62 | })
63 | }
64 | })
65 |
66 | t.Run("CompareBase", func(t *testing.T) {
67 | t.Run("Equal points", func(t *testing.T) {
68 | a := point.Point{{5, 5, 5}}
69 | b := point.Point{{6, 5, 5}}
70 | result := a.CompareBase(b)
71 | assert.Equal(t, common.Equal, result)
72 |
73 | a = point.Point{{5, 5, 5}}
74 | b = point.Point{{5, 6, 5}, {1, 5, 5}}
75 | result = a.CompareBase(b)
76 | assert.Equal(t, common.Equal, result)
77 |
78 | a = point.Point{{5, 5, 5}, {3, 3, 3}}
79 | b = point.Point{{5, 5, 5}, {3, 3, 6}}
80 | result = a.CompareBase(b)
81 | assert.Equal(t, common.Equal, result)
82 | })
83 |
84 | t.Run("Less and Greater", func(t *testing.T) {
85 | a := point.Point{{5, 5, 5}}
86 | b := point.Point{{6, 5, 4}}
87 | assert.Equal(t, common.Less, a.CompareBase(b))
88 | assert.Equal(t, common.Greater, b.CompareBase(a))
89 |
90 | a = point.Point{{5, 5, 5}}
91 | b = point.Point{{5, 6, 5}, {1, 2, 3}}
92 | assert.Equal(t, common.Less, a.CompareBase(b))
93 | assert.Equal(t, common.Greater, b.CompareBase(a))
94 |
95 | a = point.Point{{5, 5, 5}, {3, 3, 3}}
96 | b = point.Point{{5, 5, 5}, {4, 4, 4}}
97 | assert.Equal(t, common.Less, a.CompareBase(b))
98 | assert.Equal(t, common.Greater, b.CompareBase(a))
99 | })
100 |
101 | t.Run("Tagging and Tagged", func(t *testing.T) {
102 | a := point.Point{{5, 5, 5}}
103 | b := point.Point{{5, 5, 5}, {1, 2, 3}}
104 | assert.Equal(t, common.Tagged, a.CompareBase(b))
105 | assert.Equal(t, common.Tagging, b.CompareBase(a))
106 |
107 | a = point.Point{{5, 5, 5}}
108 | b = point.Point{{5, 5, 1}, {1, 2, 3}}
109 | assert.Equal(t, common.Tagged, a.CompareBase(b))
110 | assert.Equal(t, common.Tagging, b.CompareBase(a))
111 |
112 | a = point.Point{{5, 5, 5}}
113 | b = point.Point{{5, 5, 9}, {1, 2, 3}}
114 | assert.Equal(t, common.Tagged, a.CompareBase(b))
115 | assert.Equal(t, common.Tagging, b.CompareBase(a))
116 |
117 | a = point.Point{{5, 5, 5}, {3, 3, 3}}
118 | b = point.Point{{5, 5, 5}, {3, 3, 3}, {1, 2, 3}}
119 | assert.Equal(t, common.Tagged, a.CompareBase(b))
120 | assert.Equal(t, common.Tagging, b.CompareBase(a))
121 |
122 | a = point.Point{{5, 5, 5}, {3, 3, 3}}
123 | b = point.Point{{5, 5, 5}, {3, 3, 1}, {1, 2, 3}}
124 | assert.Equal(t, common.Tagged, a.CompareBase(b))
125 | assert.Equal(t, common.Tagging, b.CompareBase(a))
126 |
127 | a = point.Point{{5, 5, 5}, {3, 3, 3}}
128 | b = point.Point{{5, 5, 5}, {3, 3, 9}, {1, 2, 3}}
129 | assert.Equal(t, common.Tagged, a.CompareBase(b))
130 | assert.Equal(t, common.Tagging, b.CompareBase(a))
131 | })
132 | })
133 |
134 | t.Run("Compare", func(t *testing.T) {
135 | subject := point.Point{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
136 |
137 | t.Run("Equal", func(t *testing.T) {
138 | a := point.Point{{5, 5, 5}}
139 | b := point.Point{{6, 5, 5}}
140 | result := a.Compare(b)
141 | assert.Equal(t, common.Equal, result)
142 |
143 | a = point.Point{{5, 5, 5}}
144 | b = point.Point{{5, 6, 5}, {1, 5, 5}}
145 | result = a.Compare(b)
146 | assert.Equal(t, common.Equal, result)
147 |
148 | a = point.Point{{5, 5, 5}, {3, 3, 3}}
149 | b = point.Point{{5, 5, 5}, {4, 3, 3}}
150 | result = a.Compare(b)
151 | assert.Equal(t, common.Equal, result)
152 | })
153 |
154 | t.Run("Less and Greater", func(t *testing.T) {
155 | a := point.Point{{5, 5, 5}}
156 | b := point.Point{{5, 5, 5}, {3, 3, 3}}
157 | assert.Equal(t, common.Less, a.Compare(b))
158 | assert.Equal(t, common.Greater, b.Compare(a))
159 | })
160 |
161 | t.Run("CompareFromTheFirst", func(t *testing.T) {
162 | other := point.Point{{1, 2, 2}, {5, 6, 7}}
163 | assert.Equal(t, common.Greater, subject.Compare(other))
164 | assert.Equal(t, common.Less, other.Compare(subject))
165 | })
166 |
167 | t.Run("TaggingReturnsLess", func(t *testing.T) {
168 | other := point.Point{{1, 2, 3}, {4, 5, 6}}
169 | assert.Equal(t, common.Greater, subject.Compare(other))
170 | assert.Equal(t, common.Less, other.Compare(subject))
171 | })
172 | })
173 |
174 | t.Run("DistanceFrom", func(t *testing.T) {
175 | subject := point.Point{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
176 |
177 | t.Run("BaseTaggingTagged", func(t *testing.T) {
178 | other := point.Point{{1, 2, 3}, {4, 5, 3}}
179 | dist, order, err := subject.DistanceFrom(other)
180 |
181 | assert.Equal(t, uint32(3), dist)
182 | assert.Equal(t, common.Greater, order)
183 | assert.NoError(t, err)
184 | })
185 |
186 | t.Run("BaseEqual", func(t *testing.T) {
187 | other := point.Point{{1, 2, 3}, {4, 5, 6}, {7, 8, 120}}
188 | dist, order, err := subject.DistanceFrom(other)
189 |
190 | assert.Equal(t, uint32(111), dist)
191 | assert.Equal(t, common.Less, order)
192 | assert.NoError(t, err)
193 | })
194 |
195 | t.Run("ErrorIfPointBasesAreNotEqual", func(t *testing.T) {
196 | other := point.Point{{1, 2, 3}, {4, 5, 6}, {7, 9, 9}}
197 | _, _, err := subject.DistanceFrom(other)
198 | assert.ErrorIs(t, common.InvalidDistanceBetweenNoRelation, err)
199 | _, _, err = other.DistanceFrom(subject)
200 | assert.ErrorIs(t, common.InvalidDistanceBetweenNoRelation, err)
201 | })
202 | })
203 | }
204 |
--------------------------------------------------------------------------------
/text/tree/mod_test.go:
--------------------------------------------------------------------------------
1 | package tree_test
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/notebox/nb-crdt-go/common"
7 | "github.com/notebox/nb-crdt-go/text/test"
8 | "github.com/notebox/nb-crdt-go/text/tree"
9 | "github.com/stretchr/testify/assert"
10 | )
11 |
12 | func TestNodeMOD(t *testing.T) {
13 | t.Run("less", func(t *testing.T) {
14 | subject := tree.New(
15 | *test.INSSpanFrom(test.Cases[common.Equal]),
16 | nil,
17 | tree.New(*test.INSSpanFrom(test.RawCase{Point: test.Cases[common.Less].Point, Text: "000"}), nil, nil),
18 | )
19 | err := subject.MOD(test.MODSpanFrom(test.Cases[common.Less]), 0)
20 | assert.NoError(t, err)
21 | assert.Nil(t, subject.Left)
22 | assert.True(t, subject.Right.Span.Equals(test.INSSpanFrom(test.Cases[common.Less])))
23 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.Cases[common.Equal])))
24 | })
25 |
26 | t.Run("prependable", func(t *testing.T) {
27 | subject := tree.New(
28 | *test.INSSpanFrom(test.Cases[common.Equal]),
29 | nil,
30 | nil,
31 | )
32 | err := subject.MOD(test.MODSpanFrom(test.Cases[common.Prependable]), 0)
33 | assert.NoError(t, err)
34 | assert.Nil(t, subject.Left)
35 | assert.Nil(t, subject.Right)
36 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.Cases[common.Equal])))
37 | })
38 |
39 | t.Run("greater", func(t *testing.T) {
40 | subject := tree.New(
41 | *test.INSSpanFrom(test.Cases[common.Equal]),
42 | tree.New(*test.INSSpanFrom(test.RawCase{Point: test.Cases[common.Greater].Point, Text: "000"}), nil, nil),
43 | nil,
44 | )
45 | err := subject.MOD(test.MODSpanFrom(test.Cases[common.Greater]), 0)
46 | assert.NoError(t, err)
47 | assert.True(t, subject.Left.Span.Equals(test.INSSpanFrom(test.Cases[common.Greater])))
48 | assert.Nil(t, subject.Right)
49 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.Cases[common.Equal])))
50 | })
51 |
52 | t.Run("appendable", func(t *testing.T) {
53 | subject := tree.New(
54 | *test.INSSpanFrom(test.Cases[common.Equal]),
55 | nil,
56 | nil,
57 | )
58 | err := subject.MOD(test.MODSpanFrom(test.Cases[common.Appendable]), 0)
59 | assert.NoError(t, err)
60 | assert.Nil(t, subject.Left)
61 | assert.Nil(t, subject.Right)
62 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.Cases[common.Equal])))
63 | })
64 |
65 | t.Run("includingLeft", func(t *testing.T) {
66 | subject := tree.New(
67 | *test.INSSpanFrom(test.Cases[common.Equal]),
68 | nil,
69 | nil,
70 | )
71 | err := subject.MOD(test.MODSpanFrom(test.RawCase{Point: test.Cases[common.IncludingLeft].Point, Text: "x"}), 0)
72 | assert.NoError(t, err)
73 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.RawCase{Point: test.Cases[common.Equal].Point, Text: "x56"})))
74 | })
75 |
76 | t.Run("includingRight", func(t *testing.T) {
77 | subject := tree.New(
78 | *test.INSSpanFrom(test.Cases[common.Equal]),
79 | nil,
80 | nil,
81 | )
82 | err := subject.MOD(test.MODSpanFrom(test.RawCase{Point: test.Cases[common.IncludingRight].Point, Text: "x"}), 0)
83 | assert.NoError(t, err)
84 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.RawCase{Point: test.Cases[common.Equal].Point, Text: "45x"})))
85 | })
86 |
87 | t.Run("includingMiddle", func(t *testing.T) {
88 | subject := tree.New(
89 | *test.INSSpanFrom(test.Cases[common.Equal]),
90 | nil,
91 | nil,
92 | )
93 | err := subject.MOD(test.MODSpanFrom(test.RawCase{Point: test.Cases[common.IncludingMiddle].Point, Text: "x"}), 0)
94 | assert.NoError(t, err)
95 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.RawCase{Point: test.Cases[common.Equal].Point, Text: "4x6"})))
96 | })
97 |
98 | t.Run("rightOverlap", func(t *testing.T) {
99 | subject := tree.New(
100 | *test.INSSpanFrom(test.Cases[common.Equal]),
101 | nil,
102 | nil,
103 | )
104 | err := subject.MOD(test.MODSpanFrom(test.RawCase{Point: test.Cases[common.RightOverlap].Point, Text: "xyz"}), 0)
105 | assert.NoError(t, err)
106 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.RawCase{Point: test.Cases[common.Equal].Point, Text: "45x"})))
107 | })
108 |
109 | t.Run("leftOverlap", func(t *testing.T) {
110 | subject := tree.New(
111 | *test.INSSpanFrom(test.Cases[common.Equal]),
112 | nil,
113 | nil,
114 | )
115 | err := subject.MOD(test.MODSpanFrom(test.RawCase{Point: test.Cases[common.LeftOverlap].Point, Text: "xyz"}), 0)
116 | assert.NoError(t, err)
117 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.RawCase{Point: test.Cases[common.Equal].Point, Text: "z56"})))
118 | })
119 |
120 | t.Run("splitted", func(t *testing.T) {
121 | subject := tree.New(
122 | *test.INSSpanFrom(test.Cases[common.Equal]),
123 | nil,
124 | nil,
125 | )
126 | err := subject.MOD(test.MODSpanFrom(test.RawCase{Point: test.Cases[common.Splitted].Point, Text: "xyz"}), 0)
127 | assert.NoError(t, err)
128 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.Cases[common.Equal])))
129 | })
130 |
131 | t.Run("splitting", func(t *testing.T) {
132 | subject := tree.New(
133 | *test.INSSpanFrom(test.Cases[common.Equal]),
134 | nil,
135 | nil,
136 | )
137 | err := subject.MOD(test.MODSpanFrom(test.RawCase{Point: test.Cases[common.Splitting].Point, Text: "xyz"}), 0)
138 | assert.NoError(t, err)
139 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.Cases[common.Equal])))
140 | })
141 |
142 | t.Run("includedLeft", func(t *testing.T) {
143 | subject := tree.New(
144 | *test.INSSpanFrom(test.Cases[common.Equal]),
145 | nil,
146 | nil,
147 | )
148 | err := subject.MOD(test.MODSpanFrom(test.RawCase{Point: test.Cases[common.IncludedLeft].Point, Text: "vwxy"}), 0)
149 | assert.NoError(t, err)
150 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.RawCase{Point: test.Cases[common.Equal].Point, Text: "vwx"})))
151 | })
152 |
153 | t.Run("includedMiddle", func(t *testing.T) {
154 | subject := tree.New(
155 | *test.INSSpanFrom(test.Cases[common.Equal]),
156 | nil,
157 | nil,
158 | )
159 | err := subject.MOD(test.MODSpanFrom(test.RawCase{Point: test.Cases[common.IncludedRight].Point, Text: "vwxyz"}), 0)
160 | assert.NoError(t, err)
161 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.RawCase{Point: test.Cases[common.Equal].Point, Text: "wxy"})))
162 | })
163 |
164 | t.Run("includedRight", func(t *testing.T) {
165 | subject := tree.New(
166 | *test.INSSpanFrom(test.Cases[common.Equal]),
167 | nil,
168 | nil,
169 | )
170 | err := subject.MOD(test.MODSpanFrom(test.RawCase{Point: test.Cases[common.IncludedRight].Point, Text: "wxyz"}), 0)
171 | assert.NoError(t, err)
172 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.RawCase{Point: test.Cases[common.Equal].Point, Text: "xyz"})))
173 | })
174 |
175 | t.Run("equal", func(t *testing.T) {
176 | subject := tree.New(
177 | *test.INSSpanFrom(test.Cases[common.Equal]),
178 | nil,
179 | nil,
180 | )
181 | err := subject.MOD(test.MODSpanFrom(test.RawCase{Point: test.Cases[common.Equal].Point, Text: "xyz"}), 0)
182 | assert.NoError(t, err)
183 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.RawCase{Point: test.Cases[common.Equal].Point, Text: "xyz"})))
184 | })
185 | }
186 |
--------------------------------------------------------------------------------
/text/tree/fmt_test.go:
--------------------------------------------------------------------------------
1 | package tree_test
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/notebox/nb-crdt-go/common"
7 | "github.com/notebox/nb-crdt-go/text/content/attrs"
8 | "github.com/notebox/nb-crdt-go/text/test"
9 | "github.com/notebox/nb-crdt-go/text/tree"
10 | "github.com/stretchr/testify/assert"
11 | )
12 |
13 | func TestNodeFMT(t *testing.T) {
14 | props := attrs.TextProps{"COL": "green"}
15 |
16 | t.Run("less", func(t *testing.T) {
17 | subject := tree.New(
18 | *test.INSSpanFrom(test.Cases[common.Equal]),
19 | nil,
20 | tree.New(*test.INSSpanFrom(test.Cases[common.Less]), nil, nil),
21 | )
22 | err := subject.FMT(test.FMTSpanFrom(test.Cases[common.Less], props), 0)
23 | assert.NoError(t, err)
24 | assert.Nil(t, subject.Left)
25 | assert.Equal(t, attrs.Attrs{{Length: 3, Props: props}}, subject.Right.Span.Content.Attrs())
26 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.Cases[common.Equal])))
27 | })
28 |
29 | t.Run("prependable", func(t *testing.T) {
30 | subject := tree.New(
31 | *test.INSSpanFrom(test.Cases[common.Equal]),
32 | nil,
33 | nil,
34 | )
35 | err := subject.FMT(test.FMTSpanFrom(test.Cases[common.Prependable], props), 0)
36 | assert.NoError(t, err)
37 | assert.Nil(t, subject.Left)
38 | assert.Nil(t, subject.Right)
39 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.Cases[common.Equal])))
40 | })
41 |
42 | t.Run("greater", func(t *testing.T) {
43 | subject := tree.New(
44 | *test.INSSpanFrom(test.Cases[common.Equal]),
45 | tree.New(*test.INSSpanFrom(test.Cases[common.Greater]), nil, nil),
46 | nil,
47 | )
48 | err := subject.FMT(test.FMTSpanFrom(test.Cases[common.Greater], props), 0)
49 | assert.NoError(t, err)
50 | assert.Equal(t, attrs.Attrs{{Length: 3, Props: props}}, subject.Left.Span.Content.Attrs())
51 | assert.Nil(t, subject.Right)
52 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.Cases[common.Equal])))
53 | })
54 |
55 | t.Run("appendable", func(t *testing.T) {
56 | subject := tree.New(
57 | *test.INSSpanFrom(test.Cases[common.Equal]),
58 | nil,
59 | nil,
60 | )
61 | err := subject.FMT(test.FMTSpanFrom(test.Cases[common.Appendable], props), 0)
62 | assert.NoError(t, err)
63 | assert.Nil(t, subject.Left)
64 | assert.Nil(t, subject.Right)
65 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.Cases[common.Equal])))
66 | })
67 |
68 | t.Run("includingLeft", func(t *testing.T) {
69 | subject := tree.New(
70 | *test.INSSpanFrom(test.Cases[common.Equal]),
71 | nil,
72 | nil,
73 | )
74 | err := subject.FMT(test.FMTSpanFrom(test.RawCase{Point: test.Cases[common.IncludingLeft].Point, Text: "x"}, attrs.TextProps{"COL": "green"}), 0)
75 | assert.NoError(t, err)
76 | assert.Equal(t, attrs.Attrs{{Length: 1, Props: props}, {Length: 2}}, subject.Span.Content.Attrs())
77 | })
78 |
79 | t.Run("includingRight", func(t *testing.T) {
80 | subject := tree.New(
81 | *test.INSSpanFrom(test.Cases[common.Equal]),
82 | nil,
83 | nil,
84 | )
85 | err := subject.FMT(test.FMTSpanFrom(test.RawCase{Point: test.Cases[common.IncludingRight].Point, Text: "x"}, attrs.TextProps{"COL": "green"}), 0)
86 | assert.NoError(t, err)
87 | assert.Equal(t, attrs.Attrs{{Length: 2}, {Length: 1, Props: props}}, subject.Span.Content.Attrs())
88 | })
89 |
90 | t.Run("includingMiddle", func(t *testing.T) {
91 | subject := tree.New(
92 | *test.INSSpanFrom(test.Cases[common.Equal]),
93 | nil,
94 | nil,
95 | )
96 | err := subject.FMT(test.FMTSpanFrom(test.RawCase{Point: test.Cases[common.IncludingMiddle].Point, Text: "x"}, attrs.TextProps{"COL": "green"}), 0)
97 | assert.NoError(t, err)
98 | assert.Equal(t, attrs.Attrs{{Length: 1}, {Length: 1, Props: props}, {Length: 1}}, subject.Span.Content.Attrs())
99 | })
100 |
101 | t.Run("rightOverlap", func(t *testing.T) {
102 | subject := tree.New(
103 | *test.INSSpanFrom(test.Cases[common.Equal]),
104 | nil,
105 | nil,
106 | )
107 | err := subject.FMT(test.FMTSpanFrom(test.RawCase{Point: test.Cases[common.RightOverlap].Point, Text: "xyz"}, attrs.TextProps{"COL": "green"}), 0)
108 | assert.NoError(t, err)
109 | assert.Equal(t, attrs.Attrs{{Length: 2}, {Length: 1, Props: props}}, subject.Span.Content.Attrs())
110 | })
111 |
112 | t.Run("leftOverlap", func(t *testing.T) {
113 | subject := tree.New(
114 | *test.INSSpanFrom(test.Cases[common.Equal]),
115 | nil,
116 | nil,
117 | )
118 | err := subject.FMT(test.FMTSpanFrom(test.RawCase{Point: test.Cases[common.LeftOverlap].Point, Text: "xyz"}, attrs.TextProps{"COL": "green"}), 0)
119 | assert.NoError(t, err)
120 | assert.Equal(t, attrs.Attrs{{Length: 1, Props: props}, {Length: 2}}, subject.Span.Content.Attrs())
121 | })
122 |
123 | t.Run("splitted", func(t *testing.T) {
124 | subject := tree.New(
125 | *test.INSSpanFrom(test.Cases[common.Equal]),
126 | nil,
127 | nil,
128 | )
129 | err := subject.FMT(test.FMTSpanFrom(test.RawCase{Point: test.Cases[common.Splitted].Point, Text: "xyz"}, attrs.TextProps{"COL": "green"}), 0)
130 | assert.NoError(t, err)
131 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.Cases[common.Equal])))
132 | })
133 |
134 | t.Run("splitting", func(t *testing.T) {
135 | subject := tree.New(
136 | *test.INSSpanFrom(test.Cases[common.Equal]),
137 | nil,
138 | nil,
139 | )
140 | err := subject.FMT(test.FMTSpanFrom(test.RawCase{Point: test.Cases[common.Splitting].Point, Text: "xyz"}, attrs.TextProps{"COL": "green"}), 0)
141 | assert.NoError(t, err)
142 | assert.True(t, subject.Span.Equals(test.INSSpanFrom(test.Cases[common.Equal])))
143 | })
144 |
145 | t.Run("includedLeft", func(t *testing.T) {
146 | subject := tree.New(
147 | *test.INSSpanFrom(test.Cases[common.Equal]),
148 | nil,
149 | nil,
150 | )
151 | err := subject.FMT(test.FMTSpanFrom(test.RawCase{Point: test.Cases[common.IncludedLeft].Point, Text: "vwxy"}, attrs.TextProps{"COL": "green"}), 0)
152 | assert.NoError(t, err)
153 | assert.Equal(t, attrs.Attrs{{Length: 3, Props: props}}, subject.Span.Content.Attrs())
154 | })
155 |
156 | t.Run("includedMiddle", func(t *testing.T) {
157 | subject := tree.New(
158 | *test.INSSpanFrom(test.Cases[common.Equal]),
159 | nil,
160 | nil,
161 | )
162 | err := subject.FMT(test.FMTSpanFrom(test.RawCase{Point: test.Cases[common.IncludedRight].Point, Text: "vwxyz"}, attrs.TextProps{"COL": "green"}), 0)
163 | assert.NoError(t, err)
164 | assert.Equal(t, attrs.Attrs{{Length: 3, Props: props}}, subject.Span.Content.Attrs())
165 | })
166 |
167 | t.Run("includedRight", func(t *testing.T) {
168 | subject := tree.New(
169 | *test.INSSpanFrom(test.Cases[common.Equal]),
170 | nil,
171 | nil,
172 | )
173 | err := subject.FMT(test.FMTSpanFrom(test.RawCase{Point: test.Cases[common.IncludedRight].Point, Text: "wxyz"}, attrs.TextProps{"COL": "green"}), 0)
174 | assert.NoError(t, err)
175 | assert.Equal(t, attrs.Attrs{{Length: 3, Props: props}}, subject.Span.Content.Attrs())
176 | })
177 |
178 | t.Run("equal", func(t *testing.T) {
179 | subject := tree.New(
180 | *test.INSSpanFrom(test.Cases[common.Equal]),
181 | nil,
182 | nil,
183 | )
184 | err := subject.FMT(test.FMTSpanFrom(test.RawCase{Point: test.Cases[common.Equal].Point, Text: "xyz"}, attrs.TextProps{"COL": "green"}), 0)
185 | assert.NoError(t, err)
186 | assert.Equal(t, attrs.Attrs{{Length: 3, Props: props}}, subject.Span.Content.Attrs())
187 | })
188 | }
189 |
--------------------------------------------------------------------------------
/text/span/span_test.go:
--------------------------------------------------------------------------------
1 | package span_test
2 |
3 | import (
4 | "encoding/json"
5 | "testing"
6 |
7 | "github.com/notebox/nb-crdt-go/common"
8 | "github.com/notebox/nb-crdt-go/point"
9 | "github.com/notebox/nb-crdt-go/text/span"
10 | "github.com/notebox/nb-crdt-go/text/test"
11 | "github.com/stretchr/testify/assert"
12 | )
13 |
14 | func TestSpan(t *testing.T) {
15 | subject := test.MODSpanFrom(test.Cases[common.Equal])
16 |
17 | t.Run("JSON", func(t *testing.T) {
18 | stringifiedJSON := "[[[1,2,3]],5]"
19 | var subject span.DELSpan
20 | err := json.Unmarshal([]byte(stringifiedJSON), &subject)
21 | assert.NoError(t, err)
22 | assert.Equal(t, point.Point{{Priority: 1, ReplicaID: 2, Nonce: 3}}, subject.LowerPoint())
23 | assert.Equal(t, uint32(5), subject.Content.Length())
24 | encoded, err := json.Marshal(subject)
25 | assert.NoError(t, err)
26 | assert.Equal(t, stringifiedJSON, string(encoded))
27 | })
28 |
29 | t.Run("getters", func(t *testing.T) {
30 | other := test.MODSpanFrom(test.Cases[common.Equal])
31 | assert.True(t, subject.Equals(other))
32 | assert.Equal(t, uint32(5), subject.ReplicaID())
33 | assert.Equal(t, uint32(3), subject.Length())
34 | assert.True(t, subject.UpperPoint().Equals(test.PointFrom([][3]uint32{{1, 1, 1}, {5, 5, 7}})))
35 | assert.True(t, subject.NthPoint(5).Equals(test.PointFrom([][3]uint32{{1, 1, 1}, {5, 5, 10}})))
36 | assert.Equal(t, subject.NonceRange(), common.ClosedRange{Lower: 5, Length: 3})
37 | })
38 |
39 | t.Run("Append", func(t *testing.T) {
40 | assert.Equal(t, "456789", subject.Append(test.MODSpanFrom(test.Cases[common.Prependable])).Content.Text())
41 | })
42 |
43 | t.Run("splitting", func(t *testing.T) {
44 | assert.Equal(t, "4", subject.LeftSplitAt(1).Content.Text())
45 | assert.Equal(t, "56", subject.RightSplitAt(1).Content.Text())
46 |
47 | l, r, err := subject.SplitAt(1)
48 | assert.NoError(t, err)
49 | assert.Equal(t, "4", l.Content.Text())
50 | assert.Equal(t, "56", r.Content.Text())
51 |
52 | l, r, err = subject.SplitWith(test.MODSpanFrom(test.Cases[common.Splitted]))
53 | assert.NoError(t, err)
54 | assert.Equal(t, "4", l.Content.Text())
55 | assert.Equal(t, "56", r.Content.Text())
56 | })
57 |
58 | t.Run("AppendableSegmentTo", func(t *testing.T) {
59 | subject := test.MODSpanFrom(test.Cases[common.Equal])
60 |
61 | for _, c := range []struct {
62 | order common.Order
63 | text string
64 | point [][3]uint32
65 | err error
66 | }{
67 | {common.Appendable, "456", [][3]uint32{{1, 1, 1}, {5, 5, 5}}, nil},
68 | {common.LeftOverlap, "56", [][3]uint32{{1, 1, 1}, {5, 5, 6}}, nil},
69 | {common.IncludingLeft, "56", [][3]uint32{{1, 1, 1}, {5, 5, 6}}, nil},
70 | {common.IncludingMiddle, "6", [][3]uint32{{1, 1, 1}, {5, 5, 7}}, nil},
71 | {common.Greater, "", nil, common.UnAppendable},
72 | } {
73 | seg, err := subject.AppendableSegmentTo(test.MODSpanFrom(test.Cases[c.order]))
74 | if c.err != nil {
75 | assert.ErrorIs(t, err, c.err)
76 | continue
77 | }
78 | assert.NoError(t, err)
79 | assert.True(t, seg.LowerPoint().Equals(test.PointFrom(c.point)))
80 | assert.Equal(t, c.text, seg.Content.Text())
81 | }
82 | })
83 |
84 | t.Run("PrependableSegmentTo", func(t *testing.T) {
85 | subject := test.MODSpanFrom(test.Cases[common.Equal])
86 |
87 | for _, c := range []struct {
88 | order common.Order
89 | text string
90 | point [][3]uint32
91 | err error
92 | }{
93 | {common.Prependable, "456", [][3]uint32{{1, 1, 1}, {5, 5, 5}}, nil},
94 | {common.RightOverlap, "45", [][3]uint32{{1, 1, 1}, {5, 5, 5}}, nil},
95 | {common.IncludingRight, "45", [][3]uint32{{1, 1, 1}, {5, 5, 5}}, nil},
96 | {common.IncludingMiddle, "4", [][3]uint32{{1, 1, 1}, {5, 5, 5}}, nil},
97 | {common.Less, "", nil, common.UnPrependable},
98 | } {
99 | seg, err := subject.PrependableSegmentTo(test.MODSpanFrom(test.Cases[c.order]))
100 | if c.err != nil {
101 | assert.ErrorIs(t, err, c.err)
102 | continue
103 | }
104 | assert.NoError(t, err)
105 | assert.True(t, seg.LowerPoint().Equals(test.PointFrom(c.point)))
106 | assert.Equal(t, c.text, seg.Content.Text())
107 | }
108 | })
109 |
110 | t.Run("Intersection", func(t *testing.T) {
111 | subject := test.MODSpanFrom(test.Cases[common.Equal])
112 |
113 | for _, c := range []struct {
114 | order common.Order
115 | text string
116 | point [][3]uint32
117 | err error
118 | }{
119 | {common.RightOverlap, "6", test.Cases[common.RightOverlap].Point, nil},
120 | {common.IncludingRight, "6", test.Cases[common.IncludingRight].Point, nil},
121 | {common.IncludingMiddle, "5", test.Cases[common.IncludingMiddle].Point, nil},
122 | {common.IncludingLeft, "4", test.Cases[common.IncludingLeft].Point, nil},
123 | {common.Equal, "456", test.Cases[common.Equal].Point, nil},
124 | {common.IncludedLeft, "456", test.Cases[common.Equal].Point, nil},
125 | {common.IncludedMiddle, "456", test.Cases[common.Equal].Point, nil},
126 | {common.IncludedRight, "456", test.Cases[common.Equal].Point, nil},
127 | {common.LeftOverlap, "4", test.Cases[common.Equal].Point, nil},
128 | {common.Splitted, "", nil, common.NoIntersection},
129 | {common.Less, "", nil, common.NoIntersection},
130 | {common.Prependable, "", nil, common.NoIntersection},
131 | {common.Appendable, "", nil, common.NoIntersection},
132 | {common.Greater, "", nil, common.NoIntersection},
133 | {common.Splitting, "", nil, common.NoIntersection},
134 | } {
135 | seg, err := subject.Intersection(test.MODSpanFrom(test.Cases[c.order]))
136 | if c.err != nil {
137 | assert.ErrorIs(t, err, c.err)
138 | continue
139 | }
140 | assert.NoError(t, err)
141 | assert.True(t, seg.LowerPoint().Equals(test.PointFrom(c.point)))
142 | assert.Equal(t, c.text, seg.Content.Text())
143 | }
144 | })
145 |
146 | t.Run("Compare", func(t *testing.T) {
147 | subject := test.MODSpanFrom(test.Cases[common.Equal])
148 |
149 | var order common.Order
150 | var err error
151 | for k := range test.Cases {
152 | order, err = subject.Compare(test.MODSpanFrom(test.Cases[k]))
153 | assert.NoError(t, err)
154 | assert.Equal(t, k, order)
155 | }
156 |
157 | order, err = subject.Compare(test.MODSpanFrom(test.RawCase{Point: [][3]uint32{{1, 1, 1}, {5, 6, 5}}, Text: "456"}))
158 | assert.NoError(t, err)
159 | assert.Equal(t, common.Less, order)
160 |
161 | order, err = subject.Compare(test.MODSpanFrom(test.RawCase{Point: [][3]uint32{{1, 1, 1}, {5, 4, 5}}, Text: "456"}))
162 | assert.NoError(t, err)
163 | assert.Equal(t, common.Greater, order)
164 |
165 | order, err = subject.Compare(test.MODSpanFrom(test.RawCase{Point: [][3]uint32{{1, 1, 1}, {5, 5, 4}, {3, 3, 3}}, Text: "456"}))
166 | assert.NoError(t, err)
167 | assert.Equal(t, common.Greater, order)
168 |
169 | order, err = subject.Compare(test.MODSpanFrom(test.RawCase{Point: [][3]uint32{{1, 1, 1}, {5, 5, 8}, {3, 3, 3}}, Text: "456"}))
170 | assert.NoError(t, err)
171 | assert.Equal(t, common.Less, order)
172 |
173 | order, err = subject.Compare(test.MODSpanFrom(test.RawCase{Point: [][3]uint32{{1, 1, 1}}, Text: "456"}))
174 | assert.NoError(t, err)
175 | assert.Equal(t, common.Splitting, order)
176 |
177 | order, err = subject.Compare(test.MODSpanFrom(test.RawCase{Point: [][3]uint32{{1, 1, 1}, {5, 5, 5}, {3, 3, 3}}, Text: "456"}))
178 | assert.NoError(t, err)
179 | assert.Equal(t, common.Splitted, order)
180 |
181 | subject = test.MODSpanFrom(test.RawCase{Point: [][3]uint32{{5, 5, 5}, {7, 7, 7}}, Text: "456"})
182 | order, err = subject.Compare(test.MODSpanFrom(test.RawCase{Point: [][3]uint32{{5, 5, 9}}, Text: "456"}))
183 | assert.NoError(t, err)
184 | assert.Equal(t, common.Less, order)
185 |
186 | order, err = subject.Compare(test.MODSpanFrom(test.RawCase{Point: [][3]uint32{{5, 5, 1}}, Text: "456"}))
187 | assert.NoError(t, err)
188 | assert.Equal(t, common.Greater, order)
189 | })
190 | }
191 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------