gitee.com/go-spring2/spring-base@v1.1.3/cache/storage.go (about) 1 /* 2 * Copyright 2012-2019 the original author or authors. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * https://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package cache 18 19 import "sync" 20 21 // HashFunc returns the hash value of the key. 22 type HashFunc func(key string) int 23 24 var ( 25 SimpleHash HashFunc = func(key string) int { 26 const max = 20 27 n := len(key) 28 if n > max { 29 n = max 30 } 31 c := 0 32 for i := 0; i < n; i++ { 33 c += int(key[i]) 34 } 35 return c 36 } 37 ) 38 39 // Storage is a Shardable cache implementation. 40 type Storage struct { 41 n int 42 h HashFunc 43 m []*sync.Map 44 } 45 46 // NewStorage returns a new *Storage. 47 func NewStorage(size int, hash HashFunc) *Storage { 48 s := &Storage{n: size, h: hash} 49 s.Reset() 50 return s 51 } 52 53 // Reset resets the Storage. 54 func (s *Storage) Reset() { 55 s.m = make([]*sync.Map, s.n, s.n) 56 for i := 0; i < s.n; i++ { 57 s.m[i] = &sync.Map{} 58 } 59 } 60 61 // Sharding returns the shard of the key. 62 func (s *Storage) Sharding(key string) *sync.Map { 63 return s.m[s.h(key)%s.n] 64 }