2
0

storage.zig 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. const std = @import("std");
  2. const hashing = @import("hashing.zig");
  3. const persistence = @import("persistence.zig");
  4. const MAX_RECORDS = 10_000_000;
  5. const Entry = struct {
  6. key: []const u8,
  7. value: []const u8,
  8. next: ?*Entry,
  9. };
  10. var buf: [MAX_RECORDS]?*Entry = undefined;
  11. var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
  12. const allocator = arena.allocator();
  13. const EMPTY = "";
  14. var mutex: std.Thread.Mutex = .{};
  15. pub fn writeVolatile(key: []const u8, value: []const u8) ?*Entry {
  16. const hash = hashing.hashKey(key);
  17. const index = hash % buf.len;
  18. var current = buf[index];
  19. while (current) |entry| {
  20. if (std.mem.eql(u8, entry.key, key)) {
  21. allocator.free(entry.value);
  22. entry.value = allocator.dupe(u8, value) catch return null;
  23. return entry;
  24. }
  25. current = entry.next;
  26. }
  27. const newEntry = allocator.create(Entry) catch return null;
  28. errdefer allocator.destroy(newEntry);
  29. newEntry.* = Entry{
  30. .key = allocator.dupe(u8, key) catch return null,
  31. .value = allocator.dupe(u8, value) catch return null,
  32. .next = buf[index],
  33. };
  34. buf[index] = newEntry;
  35. return newEntry;
  36. }
  37. pub fn write(key: []const u8, value: []const u8) bool {
  38. mutex.lock();
  39. defer mutex.unlock();
  40. const entry = writeVolatile(key, value);
  41. if (entry == null) {
  42. return false;
  43. }
  44. persistence.persist('W', entry.?.key, entry.?.value);
  45. return true;
  46. }
  47. pub fn read(key: []const u8) ?[]const u8 {
  48. mutex.lock();
  49. defer mutex.unlock();
  50. const hash = hashing.hashKey(key);
  51. var current = buf[hash % buf.len];
  52. while (current) |entry| {
  53. if (std.mem.eql(u8, entry.key, key)) {
  54. return entry.value;
  55. }
  56. current = entry.next;
  57. }
  58. return null;
  59. }
  60. pub fn deleteVolatile(key: []const u8) bool {
  61. const hash = hashing.hashKey(key);
  62. const index = hash % buf.len;
  63. var current = buf[index];
  64. var prev: ?*Entry = null;
  65. while (current) |entry| {
  66. if (std.mem.eql(u8, entry.key, key)) {
  67. if (prev) |p| {
  68. p.next = entry.next;
  69. } else {
  70. buf[index] = entry.next;
  71. }
  72. allocator.free(entry.key);
  73. allocator.free(entry.value);
  74. allocator.destroy(entry);
  75. return true;
  76. }
  77. prev = entry;
  78. current = entry.next;
  79. }
  80. return false;
  81. }
  82. pub fn delete(key: []const u8) bool {
  83. mutex.lock();
  84. defer mutex.unlock();
  85. const deleted = deleteVolatile(key);
  86. if (deleted) {
  87. persistence.persist('D', key, "");
  88. }
  89. return deleted;
  90. }