file_backed_key_set.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * Copyright [2021] JD.com, Inc.
  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. * http://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. #ifndef FILE_BACKED_KEY_SET_H__
  17. #define FILE_BACKED_KEY_SET_H__
  18. #include <unistd.h>
  19. #include <stdint.h>
  20. #include <string>
  21. #include <vector>
  22. #define MIGRATE_START 1
  23. #define MIGRATE_SUCCESS 2
  24. class FileBackedKeySet {
  25. public:
  26. FileBackedKeySet(const char *file, int keySize);
  27. ~FileBackedKeySet();
  28. bool Contains(const char *key, bool checkStatus = true);
  29. bool is_migrating(const char *key);
  30. int Open();
  31. int Load();
  32. int do_insert(const char *key);
  33. int Migrated(const char *key);
  34. void Clear();
  35. private:
  36. struct hash_node {
  37. hash_node *next;
  38. uintptr_t offset;
  39. };
  40. class hash_node_allocator {
  41. public:
  42. hash_node_allocator() : m_freeNode(NULL)
  43. {
  44. }
  45. ~hash_node_allocator();
  46. hash_node *alloc();
  47. void free(hash_node *n);
  48. void reset();
  49. static const int GROW_COUNT = 4096 * 16;
  50. private:
  51. hash_node *m_freeNode;
  52. std::vector<char *> m_buffs;
  53. };
  54. hash_node_allocator m_allocator;
  55. struct meta_info {
  56. uintptr_t size;
  57. uintptr_t writePos;
  58. };
  59. //4M
  60. static const int INIT_FILE_SIZE = 4096 * 1024;
  61. static const int GROW_FILE_SIZE = 1024 * 1024;
  62. static const int BUCKET_SIZE = 1024 * 1024;
  63. meta_info *get_meta_info()
  64. {
  65. return (meta_info *)m_base;
  66. }
  67. void insert_to_set(const char *key, int len);
  68. char *insert_to_file(const char *key, int len);
  69. std::string m_filePath;
  70. int m_fd;
  71. int m_keySize;
  72. char *m_base;
  73. hash_node **m_buckets;
  74. };
  75. #endif