You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.0 KiB

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