坚固性映射使用字符串查找结构?



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

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,请告诉我该怎么做。

您可以编写一个函数将字符串转换为字节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];
}

最新更新