github.com/matrixorigin/matrixone@v1.2.0/pkg/common/buffer/chunk.go (about) 1 // Copyright 2021 - 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 buffer 16 17 import ( 18 "unsafe" 19 20 "golang.org/x/sys/unix" 21 ) 22 23 func init() { 24 var c chunk 25 26 ChunkSize = int(unsafe.Sizeof(c)) 27 } 28 29 func (c *chunk) alloc(sz int) []byte { 30 c.Lock() 31 defer c.Unlock() 32 if int(c.off)+sz+int(PointerSize) >= len(c.data) { 33 c.flag |= FULL 34 return nil 35 } 36 data := c.data[c.off : int(c.off)+sz+int(PointerSize)] 37 *((*unsafe.Pointer)(unsafe.Pointer(unsafe.SliceData(data)))) = unsafe.Pointer(c) 38 c.off += uint32(sz + int(PointerSize)) 39 c.numAlloc++ 40 return data[PointerSize:] 41 } 42 43 func (c *chunk) free() { 44 c.Lock() 45 if c.numFree = c.numFree + 1; c.numFree == c.numAlloc && 46 c.flag&FULL == FULL { // this chunk is no longer needed 47 unix.Munmap(c.data) 48 return 49 } 50 c.Unlock() 51 }