写合约的时候,记录某个账户的bool状态很常见,例如是否领取空投等,传统的写法mapping(uint256=>bool)中一个slot只能存储一个账户的信息,在其他语言中,我们经常会用到bitmap来表示标志位,如果我们可以将bitmap应用到合约中,可以节约很多gas;今天我们就开发一种适合solidity的bitmap;
https://github.com/XuHugo/solidityproject/tree/master/BitMap代码分析
首先我们定义一个mapping(uint256 => uint256)的变量,key表示第几个word,value表示对应word的bit情况;这样一个slot就可以表示256个key的情况,效率大大的提高了。
只有两个函数,一个读,一个写;操作逻辑都是一样的,对于给定的index,先判断位于哪个一个word,在判断在word的哪个bit;然后在进行读写操作;
foundry测试:
测试也没什么说的,比较简单;index之所以写成加法,是为了方便大家理解。
这个小功能是我读一个项目的时候发现的,觉得不错,就尝试的写了一下,结果发现openzeppelin里也有这个功能,大家用的时候,可以直接引用了,就不要自己写了;