Solidity Mapping使用字符串查找结构?

时间:2019-09-27 10:11:19

标签: solidity

我想使用映射找到结构,但是映射只能使用字节,而我需要使用字符串。

pragma solidity >=0.4.22 <0.6.0;
pragma experimental ABIEncoderV2;
contract land{

    address public owner;

    constructor() public{
        owner = msg.sender;
    }

    struct Landpaper{
        string number;
        string landaddress;
        string landnumber;
        string landpurpose;
        uint landgrades;
        uint256 landarea;
        string holdpoints;
    }

    mapping(bytes8 => Landpaper) public lp;

    modifier Permission(){
        require(msg.sender == owner);
        _;
    }

    function set(string memory rfidnumber, Landpaper memory _landpaperRecord) public Permission{
        lp[rfidnumber]=_landpaperRecord;
    }

    function get(string memory rfidnumber) view public returns(Landpaper memory){
        return lp[rfidnumber];
    }

}

因为我必须读取rfid UID并将UID转换为字符串,所以我需要使用字符串设置我的数据。我使用bytes8并输入了字符串类型,我需要将字符串更改为bytes8,请告诉我该怎么做。

1 个答案:

答案 0 :(得分:0)

您可以编写一个将字符串转换为字节的函数8

function stringToBytes8(string memory sourceStr) private pure returns(bytes8) {
    bytes8 temp = 0x0;
    assembly {
        temp := mload(add(sourceStr, 32))
    }
    return temp;
}

并通过setget函数调用它

function set(string memory rfidnumber, Landpaper memory _landpaperRecord) public Permission {
    bytes8 rfidb8 = stringToByte8(rfidnumber);
    lp[rfidb8]=_landpaperRecord;
}

function get(string memory rfidnumber) public view returns(Landpaper memory) {
    bytes8 rfidb8 = stringToByte8(rfidnumber);
    return lp[rfidb8];
}

尽管我建议避免在contract中执行转换过程,因为它会消耗不必要的gas。而是在客户端执行转换,并将bytes8作为参数传递

function set(bytes8 rfidnumber, Landpaper memory _landpaperRecord) public Permission {
    lp[rfidnumber]=_landpaperRecord;
}

function get(bytes8 rfidnumber) public view returns(Landpaper memory) {
    return lp[rfidnumber];
}