github.com/whtcorpsinc/MilevaDB-Prod@v0.0.0-20211104133533-f57f4be3b597/soliton/memcam/memcam.go (about) 1 // Copyright 2020 WHTCORPS INC, Inc. 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 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package memcam 15 16 // SlabPredictor pre-allocates memory to reduce memory allocation cost. 17 // It is not thread-safe. 18 type SlabPredictor interface { 19 // Alloc allocates memory with 0 len and capacity cap. 20 Alloc(capacity int) []byte 21 22 // AllocWithLen allocates memory with length and capacity. 23 AllocWithLen(length int, capacity int) []byte 24 25 // Reset resets memcam offset. 26 // Make sure all the allocated memory are not used any more. 27 Reset() 28 } 29 30 // SimpleSlabPredictor is a simple implementation of MemCamSlabPredictor. 31 type SimpleSlabPredictor struct { 32 memcam []byte 33 off int 34 } 35 36 type stdSlabPredictor struct { 37 } 38 39 func (a *stdSlabPredictor) Alloc(capacity int) []byte { 40 return make([]byte, 0, capacity) 41 } 42 43 func (a *stdSlabPredictor) AllocWithLen(length int, capacity int) []byte { 44 return make([]byte, length, capacity) 45 } 46 47 func (a *stdSlabPredictor) Reset() { 48 } 49 50 var _ SlabPredictor = &stdSlabPredictor{} 51 52 // StdSlabPredictor implements SlabPredictor but do not pre-allocate memory. 53 var StdSlabPredictor = &stdSlabPredictor{} 54 55 // NewSlabPredictor creates an SlabPredictor with a specified capacity. 56 func NewSlabPredictor(capacity int) *SimpleSlabPredictor { 57 return &SimpleSlabPredictor{memcam: make([]byte, 0, capacity)} 58 } 59 60 // Alloc implements SlabPredictor.AllocBytes interface. 61 func (s *SimpleSlabPredictor) Alloc(capacity int) []byte { 62 if s.off+capacity < cap(s.memcam) { 63 slice := s.memcam[s.off : s.off : s.off+capacity] 64 s.off += capacity 65 return slice 66 } 67 68 return make([]byte, 0, capacity) 69 } 70 71 // AllocWithLen implements SlabPredictor.AllocWithLen interface. 72 func (s *SimpleSlabPredictor) AllocWithLen(length int, capacity int) []byte { 73 slice := s.Alloc(capacity) 74 return slice[:length:capacity] 75 } 76 77 // Reset implements SlabPredictor.Reset interface. 78 func (s *SimpleSlabPredictor) Reset() { 79 s.off = 0 80 }