From 7f86c75360072879bbdfdc61c5ea777a0eed8885 Mon Sep 17 00:00:00 2001 From: c9s Date: Wed, 19 May 2021 00:15:11 +0800 Subject: [PATCH] add CopyDepth for avoid copying the whole book --- pkg/types/orderbook.go | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/pkg/types/orderbook.go b/pkg/types/orderbook.go index e8b93fd4a..6df288aa5 100644 --- a/pkg/types/orderbook.go +++ b/pkg/types/orderbook.go @@ -38,6 +38,16 @@ func (slice PriceVolumeSlice) Trim() (pvs PriceVolumeSlice) { return pvs } +func (slice PriceVolumeSlice) CopyDepth(depth int) PriceVolumeSlice { + if depth > len(slice) { + return slice.Copy() + } + + var s = make(PriceVolumeSlice, depth, depth) + copy(s, slice[:depth]) + return s +} + func (slice PriceVolumeSlice) Copy() PriceVolumeSlice { var s = make(PriceVolumeSlice, len(slice), len(slice)) copy(s, slice) @@ -196,6 +206,13 @@ func (b *OrderBook) PriceVolumesBySide(side SideType) PriceVolumeSlice { return nil } +func (b *OrderBook) CopyDepth(depth int) (book OrderBook) { + book = *b + book.Bids = book.Bids.CopyDepth(depth) + book.Asks = book.Asks.CopyDepth(depth) + return book +} + func (b *OrderBook) Copy() (book OrderBook) { book = *b book.Bids = book.Bids.Copy() @@ -307,6 +324,12 @@ func (b *MutexOrderBook) Reset() { b.Unlock() } +func (b *MutexOrderBook) CopyDepth(depth int) OrderBook { + b.Lock() + defer b.Unlock() + return b.OrderBook.CopyDepth(depth) +} + func (b *MutexOrderBook) Get() OrderBook { b.Lock() defer b.Unlock()