Created
July 25, 2024 18:37
-
-
Save 0xhank/4857311a3c293add91624e0d60aa847b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity >=0.8.24; | |
import { Keys_Map, Value_Map, Meta_Map } from "codegen/index.sol"; | |
library Map { | |
function has(bytes32 key, bytes32 value) internal view returns (bool) { | |
return Meta_Map.get(key, value).stored; | |
} | |
function set(bytes32 key, uint256 value) internal { | |
if (has(key, value)) { | |
uint256 prevValue = get(key); | |
Value_Map.set(key, value); | |
} else { | |
Keys_Map.push(key); | |
Value_Map.set(key, value); | |
Meta_Map.set(key, value, true, Keys_Map.length(key) - 1); | |
} | |
} | |
function get(bytes32 key) internal view returns (uint256) { | |
return Value_Map.get(key, value); | |
} | |
function keys(bytes32 key) internal view returns (bytes32[] memory) { | |
return Keys_Map.get(key); | |
} | |
function values(bytes32 key) internal view returns (uint256[] memory _values) { | |
bytes32[] memory values = keys(key); | |
_values = new uint256[](values.length); | |
for (uint256 i = 0; i < values.length; i++) { | |
_values[i] = Value_Map.get(key, values[i]); | |
} | |
} | |
function remove(bytes32 key, bytes32 value) internal { | |
uint256 index = Meta_Map.getIndex(key, value); | |
if (Keys_Map.length(key) == 1) { | |
clear(key); | |
return; | |
} | |
// update replacement data | |
bytes32 replacement = Keys_Map.getItem(key, Keys_Map.length(key) - 1); | |
Keys_Map.update(key, index, replacement); | |
Meta_Map.set(key, replacement, true, index); | |
Keys_Map.pop(key); | |
Value_Map.deleteRecord(key, value); | |
Meta_Map.deleteRecord(key, value); | |
} | |
function size(bytes32 key) internal view returns (uint256) { | |
return Keys_Map.length(key); | |
} | |
function clear(bytes32 key) internal { | |
bytes32[] memory values = keys(key); | |
for (uint256 i = 0; i < values.length; i++) { | |
Value_Map.deleteRecord(key, values[i]); | |
Meta_Map.deleteRecord(key, values[i]); | |
} | |
Keys_Map.deleteRecord(key); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Value_Map: { | |
key: ["key"], | |
schema: { key: "bytes32", value: "uint256" }, | |
}, | |
Meta_Map: { | |
key: ["key"], | |
schema: { key: 'bytes32', stored: "bool", index: "uint256" }, | |
}, | |
Keys_Map: { | |
key: ["key"], | |
schema: { key: "bytes32", value: "uint256" }, | |
}, |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment