github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/pingcap/tidb/util/segmentmap/segmentmap.go (about) 1 // Copyright 2015 PingCAP, 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 segmentmap 15 16 import ( 17 "hash/crc32" 18 19 "github.com/insionng/yougam/libraries/juju/errors" 20 ) 21 22 // SegmentMap is used for handle a big map slice by slice. 23 // It's not thread safe. 24 type SegmentMap struct { 25 size int64 26 maps []map[string]interface{} 27 28 crcTable *crc32.Table 29 } 30 31 // NewSegmentMap create a new SegmentMap. 32 func NewSegmentMap(size int64) (*SegmentMap, error) { 33 if size <= 0 { 34 return nil, errors.Errorf("Invalid size: %d", size) 35 } 36 37 sm := &SegmentMap{ 38 maps: make([]map[string]interface{}, size), 39 size: size, 40 } 41 for i := int64(0); i < size; i++ { 42 sm.maps[i] = make(map[string]interface{}) 43 } 44 45 sm.crcTable = crc32.MakeTable(crc32.Castagnoli) 46 return sm, nil 47 } 48 49 // Get is the same as map[k]. 50 func (sm *SegmentMap) Get(key []byte) (interface{}, bool) { 51 idx := int64(crc32.Checksum(key, sm.crcTable)) % sm.size 52 val, ok := sm.maps[idx][string(key)] 53 return val, ok 54 } 55 56 // GetSegment gets the map specific by index. 57 func (sm *SegmentMap) GetSegment(index int64) (map[string]interface{}, error) { 58 if index >= sm.size || index < 0 { 59 return nil, errors.Errorf("index out of bound: %d", index) 60 } 61 62 return sm.maps[index], nil 63 } 64 65 // Set if key not exists, returns whether already exists. 66 func (sm *SegmentMap) Set(key []byte, value interface{}, force bool) bool { 67 idx := int64(crc32.Checksum(key, sm.crcTable)) % sm.size 68 k := string(key) 69 _, exist := sm.maps[idx][k] 70 if exist && !force { 71 return exist 72 } 73 74 sm.maps[idx][k] = value 75 return exist 76 } 77 78 // SegmentCount returns how many inner segments. 79 func (sm *SegmentMap) SegmentCount() int64 { 80 return sm.size 81 }