Skip to content

Commit

Permalink
Merge pull request #9 from dylanlott/v5
Browse files Browse the repository at this point in the history
v5 concurrent read and write ops
  • Loading branch information
dylanlott committed Mar 17, 2023
2 parents a1bfdf9 + e7b448e commit 85b5398
Show file tree
Hide file tree
Showing 4 changed files with 571 additions and 0 deletions.
56 changes: 56 additions & 0 deletions pkg/v4/v4.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package v4

import (
"fmt"
"sync"
)

type books struct {
buy *sync.Map
sell *sync.Map
}

type order struct {
ID string
Price uint64
Side bool
}

func newBooks() *books {
b := &books{
buy: &sync.Map{},
sell: &sync.Map{},
}
return b
}

// Push pushes order [ord] into the books.
func (b *books) Push(ord *order) error {
if ord.Side {
// push buy side
loaded, ok := b.buy.Load(ord.Price)
if !ok {
// nothing exists at this price, push it into map
b.buy.Store(ord.Price, []*order{ord})
return nil
}
if val, ok := loaded.([]*order); ok {
val = append(val, ord)
} else {
return fmt.Errorf("ErrNotImpl for type %T", loaded)
}
}
// push sell side
loaded, ok := b.sell.Load(ord.Price)
if !ok {
// nothing exists at this price, push it into the map at the price
b.sell.Store(ord.Price, []*order{ord})
return nil
}
if val, ok := loaded.([]*order); ok {
val = append(val, ord)
} else {
return fmt.Errorf("ErrNotImpl for type %T", loaded)
}
return nil
}
36 changes: 36 additions & 0 deletions pkg/v4/v4_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package v4

import (
"sync"
"testing"

"github.com/matryer/is"
)

func TestV4(t *testing.T) {
is := is.New(t)

b := &books{
buy: &sync.Map{},
sell: &sync.Map{},
}

err := b.Push(&order{
ID: "foo",
Price: 1000,
Side: true,
})
is.NoErr(err)
err = b.Push(&order{
ID: "bar",
Price: 1000,
Side: false,
})
is.NoErr(err)
err = b.Push(&order{
ID: "buz",
Price: 1000,
Side: true,
})
is.NoErr(err)
}

0 comments on commit 85b5398

Please sign in to comment.