github.com/matrixorigin/matrixone@v1.2.0/pkg/common/reuse/mpool_based.go (about) 1 // Copyright 2023 Matrix Origin 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package reuse 16 17 import ( 18 "fmt" 19 "unsafe" 20 21 "github.com/matrixorigin/matrixone/pkg/common/mpool" 22 ) 23 24 type mpoolBased[T ReusableObject] struct { 25 pool *mpool.MPool 26 opts *Options[T] 27 c *checker[T] 28 } 29 30 func newMpoolBased[T ReusableObject]( 31 capacity int64, 32 opts *Options[T]) Pool[T] { 33 opts.adjust() 34 var v T 35 c := newChecker[T](opts.enableChecker) 36 mp, err := mpool.NewMPool(fmt.Sprintf("reuse-%s", v.TypeName()), opts.memCapacity, 0) 37 if err != nil { 38 panic(err) 39 } 40 return &mpoolBased[T]{ 41 pool: mp, 42 opts: opts, 43 c: c, 44 } 45 } 46 47 func (p *mpoolBased[T]) Alloc() *T { 48 var t T 49 data, err := p.pool.Alloc(int(unsafe.Sizeof(t))) 50 if err != nil { 51 panic(err) 52 } 53 v := (*T)(unsafe.Pointer(unsafe.SliceData(data))) 54 p.c.created(v) 55 p.c.got(v) 56 return v 57 } 58 59 func (p *mpoolBased[T]) Free(v *T) { 60 p.c.free(v) 61 p.opts.release(v) 62 p.pool.Free(unsafe.Slice((*byte)(unsafe.Pointer(v)), unsafe.Sizeof(*v))) 63 }