Files
obitools4/pkg/obiseq/pool.go

95 lines
1.7 KiB
Go
Raw Normal View History

2022-01-13 23:27:39 +01:00
package obiseq
import (
"log"
2022-01-13 23:27:39 +01:00
"sync"
2022-01-16 00:21:42 +01:00
"git.metabarcoding.org/obitools/obitools4/obitools4/pkg/obiutils"
2022-01-13 23:27:39 +01:00
)
2022-01-16 00:21:42 +01:00
var _BioSequenceByteSlicePool = sync.Pool{
2022-01-13 23:27:39 +01:00
New: func() interface{} {
2022-01-16 00:21:42 +01:00
bs := make([]byte, 0, 300)
2022-01-13 23:27:39 +01:00
return &bs
},
}
2022-02-18 22:53:09 +01:00
func RecycleSlice(s *[]byte) {
if s != nil && cap(*s) > 0 {
*s = (*s)[:0]
if cap(*s) == 0 {
log.Panicln("trying to store a NIL slice in the pool", s == nil, *s == nil, cap(*s))
}
if cap(*s) <= 1024 {
_BioSequenceByteSlicePool.Put(s)
}
}
2022-01-16 00:21:42 +01:00
}
// It returns a slice of bytes from a pool of slices.
//
// the slice can be prefilled with the provided values
func GetSlice(capacity int) []byte {
p := (*[]byte)(nil)
if capacity <= 1024 {
p = _BioSequenceByteSlicePool.Get().(*[]byte)
}
2022-01-16 00:21:42 +01:00
if p == nil || *p == nil || cap(*p) < capacity {
return make([]byte, 0, capacity)
2022-01-16 00:21:42 +01:00
}
s := *p
2022-01-16 00:21:42 +01:00
if cap(s) < capacity {
log.Panicln("Bizarre... j'aurai pourtant cru")
}
2022-01-16 00:21:42 +01:00
return s
}
func CopySlice(src []byte) []byte {
sl := GetSlice(len(src))
sl = sl[0:len(src)]
2022-10-12 23:01:47 +02:00
copy(sl, src)
return sl
}
2022-01-16 00:21:42 +01:00
var BioSequenceAnnotationPool = sync.Pool{
New: func() interface{} {
bs := make(Annotation, 5)
2022-01-16 00:21:42 +01:00
return &bs
},
2022-01-13 23:27:39 +01:00
}
2022-02-18 22:53:09 +01:00
func RecycleAnnotation(a *Annotation) {
2022-02-01 17:31:28 +01:00
if a != nil {
2022-02-18 22:53:09 +01:00
for k := range *a {
delete(*a, k)
2022-02-01 17:31:28 +01:00
}
BioSequenceAnnotationPool.Put(a)
2022-01-16 00:21:42 +01:00
}
2022-01-13 23:27:39 +01:00
}
// GetAnnotation returns an Annotation from the BioSequenceAnnotationPool.
//
// It takes as argument O or 1 Annotation annotation object.
// If an annotation object is passed, it is copied into the new Annotation.
//
// It returns an Annotation.
2022-01-16 00:21:42 +01:00
func GetAnnotation(values ...Annotation) Annotation {
a := Annotation(nil)
2022-01-16 00:21:42 +01:00
for a == nil {
a = *(BioSequenceAnnotationPool.Get().(*Annotation))
2022-01-16 00:21:42 +01:00
}
2022-02-18 22:53:09 +01:00
if len(values) > 0 {
obiutils.MustFillMap(a, values[0])
2022-02-18 22:53:09 +01:00
}
return a
2022-02-18 22:53:09 +01:00
}