github.com/weaviate/weaviate@v1.24.6/adapters/repos/db/vector/flat/pools.go (about)

     1  //                           _       _
     2  // __      _____  __ ___   ___  __ _| |_ ___
     3  // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
     4  //  \ V  V /  __/ (_| |\ V /| | (_| | ||  __/
     5  //   \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
     6  //
     7  //  Copyright © 2016 - 2024 Weaviate B.V. All rights reserved.
     8  //
     9  //  CONTACT: hello@weaviate.io
    10  //
    11  
    12  package flat
    13  
    14  import (
    15  	"sync"
    16  )
    17  
    18  const defaultSize = 200
    19  
    20  type pools struct {
    21  	byteSlicePool    *slicePool[byte]
    22  	uint64SlicePool  *slicePool[uint64]
    23  	float32SlicePool *slicePool[float32]
    24  }
    25  
    26  func newPools() *pools {
    27  	return &pools{
    28  		byteSlicePool:    newSlicePool[byte](),
    29  		uint64SlicePool:  newSlicePool[uint64](),
    30  		float32SlicePool: newSlicePool[float32](),
    31  	}
    32  }
    33  
    34  type slicePool[T any] struct {
    35  	pool *sync.Pool
    36  }
    37  
    38  type SliceStruct[T any] struct {
    39  	slice []T
    40  }
    41  
    42  func newSlicePool[T any]() *slicePool[T] {
    43  	return &slicePool[T]{
    44  		pool: &sync.Pool{
    45  			New: func() interface{} {
    46  				return &SliceStruct[T]{
    47  					slice: make([]T, defaultSize),
    48  				}
    49  			},
    50  		},
    51  	}
    52  }
    53  
    54  func (p *slicePool[T]) Get(capacity int) *SliceStruct[T] {
    55  	t := p.pool.Get().(*SliceStruct[T])
    56  	if cap(t.slice) < capacity {
    57  		t.slice = make([]T, capacity)
    58  	}
    59  	t.slice = t.slice[:capacity]
    60  	return t
    61  }
    62  
    63  func (p *slicePool[T]) Put(t *SliceStruct[T]) {
    64  	p.pool.Put(t)
    65  }