Solidity 遍历mapping

以太坊基金会为我们提供了以uint为例子的遍历mapping的库(iterable_mapping)。

insert 方法

function insert(itmap storage self, uint key, uint value) returns (bool replaced)
  {
    uint keyIndex = self.data[key].keyIndex;
    self.data[key].value = value;
    if (keyIndex > 0)
      return true;
    else
    {
      keyIndex = self.keys.length++;
      self.data[key].keyIndex = keyIndex + 1;
      self.keys[keyIndex].key = key;
      self.size++;
      return false;
    }
  }

remove方法

function remove(itmap storage self, uint key) returns (bool success)
  {
    uint keyIndex = self.data[key].keyIndex;
    if (keyIndex == 0)
      return false;
    delete self.data[key];
    self.keys[keyIndex - 1].deleted = true;
    self.size --;
  }

iterate_next方法

function iterate_next(itmap storage self, uint keyIndex) returns (uint r_keyIndex)
  {
    keyIndex++;
    while (keyIndex < self.keys.length && self.keys[keyIndex].deleted)
      keyIndex++;
    return keyIndex;
  }

iterate_get方法

function iterate_get(itmap storage self, uint keyIndex) returns (uint key, uint value)
  {
    key = self.keys[keyIndex].key;
    value = self.data[key].value;
  }

在使用这些方法时,可以直接IterableMapping.itmap.insert(key,value),第一个参数itmap storage self会被自动赋值。
举栗子如下:

pragma solidity ^0.4.7;
import {IterableMapping} from 'https://github.com/ethereum/dapp-bin/library/iterable_mapping.sol';

contract MappingsIterable {
    using IterableMapping for IterableMapping.itmap;
    IterableMapping.itmap public data;

    function insertValue(uint _key, uint _value) public {
        data.insert(_key, _value);
    }
// 计算mapping中所有value的和
  function sum() returns (uint s)
  {
    for (uint i = IterableMapping.iterate_start(data); IterableMapping.iterate_valid(data, i); i = IterableMapping.iterate_next(data, i))
    {
        (uint key, uint value) = IterableMapping.iterate_get(data, i);
        s += value;
    }
  }
}

你可能感兴趣的:(Solidity)