-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #9 from dylanlott/v5
v5 concurrent read and write ops
- Loading branch information
Showing
4 changed files
with
571 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |
Oops, something went wrong.