github.com/matrixorigin/matrixone@v1.2.0/pkg/fileservice/memorycache/cache.go (about) 1 // Copyright 2022 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 memorycache 16 17 import ( 18 "context" 19 20 "github.com/matrixorigin/matrixone/pkg/fileservice/memorycache/lrucache" 21 cache "github.com/matrixorigin/matrixone/pkg/pb/query" 22 ) 23 24 func NewCache( 25 capacity int64, 26 postSet func(key cache.CacheKey, value CacheData), 27 postGet func(key cache.CacheKey, value CacheData), 28 postEvict func(key cache.CacheKey, value CacheData), 29 ) *Cache { 30 var c Cache 31 32 setFunc := func(key cache.CacheKey, value *Data) { 33 var r RCBytes 34 35 value.acquire() 36 if postSet != nil { 37 r.d = value 38 r.size = &c.size 39 postSet(key, r) 40 } 41 } 42 getFunc := func(key cache.CacheKey, value *Data) { 43 var r RCBytes 44 45 value.acquire() 46 if postGet != nil { 47 r.d = value 48 r.size = &c.size 49 postGet(key, r) 50 } 51 } 52 evictFunc := func(key cache.CacheKey, value *Data) { 53 var r RCBytes 54 55 value.release(&c.size) 56 if postEvict != nil { 57 r.d = value 58 r.size = &c.size 59 postEvict(key, r) 60 } 61 } 62 c.l = lrucache.New(capacity, setFunc, getFunc, evictFunc) 63 return &c 64 } 65 66 func (c *Cache) Alloc(n int) CacheData { 67 d := newData(n, &c.size) 68 return RCBytes{d: d, size: &c.size} 69 } 70 71 func (c *Cache) Get(ctx context.Context, key cache.CacheKey) (CacheData, bool) { 72 var r RCBytes 73 74 v, ok := c.l.Get(ctx, key) 75 if ok { // find the value, set the value to the return value 76 r.d = v 77 r.size = &c.size 78 } 79 return r, ok 80 } 81 82 func (c *Cache) Set(ctx context.Context, key cache.CacheKey, value CacheData) error { 83 if r, ok := value.(RCBytes); ok { 84 c.l.Set(ctx, key, r.d) 85 } 86 return nil 87 } 88 89 func (c *Cache) Flush() { 90 c.l.Flush() 91 } 92 93 func (c *Cache) Size() int64 { 94 return c.size.Load() 95 } 96 97 func (c *Cache) Capacity() int64 { 98 return c.l.Capacity() 99 } 100 101 func (c *Cache) Used() int64 { 102 return c.l.Used() 103 } 104 105 func (c *Cache) Available() int64 { 106 return c.l.Available() 107 } 108 109 func (c *Cache) DeletePaths(_ context.Context, _ []string) { 110 //TODO 111 }