Last active
March 14, 2017 17:48
-
-
Save 3esmit/d5ecea07677c367270cc7abab3cdf0af to your computer and use it in GitHub Desktop.
This file contains 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
pragma solidity ^0.4.1; | |
contract JSONTools{ | |
//try _extractString("[\"12345678\"]",0): gas usage 5192 | |
function _extractString(bytes v, uint _start) constant returns (string val,uint i) { | |
uint start = 0; | |
uint end = 0; | |
for (i=0;v.length > i;i++) { | |
if (v[i] == '"'){ //quotation mark ---------> needed to break to reduce gas | |
if(v[i-1] != '\\'){ //not escaped <------ | |
end = start == 0 ? 0: i; | |
start = start == 0? i+1 : start; | |
if(end > 0) break; | |
} | |
} | |
} | |
bytes memory str = new bytes(end-start); | |
for(i=0; i<str.length; i++){ | |
str[i] = v[start+i]; | |
} | |
for(i=end+1; i<v.length; i++) if (v[i] == ','){ i++; break; } //end | |
val = string(str); | |
} | |
//try _extractString2("[\"12345678\"]",0): gas usage 5405 | |
function _extractString2(bytes v, uint _start) constant returns (string val,uint i) { | |
uint start = 0; | |
uint end = 0; | |
for (i=0;v.length > i;i++) { | |
if (v[i] == '"' && (v[i-1] != '\\')){ //quotation mark and is not escaped ---------> consomes more gas | |
end = start == 0 ? 0: i; | |
start = start == 0? i+1 : start; | |
if(end > 0) break; | |
} | |
} | |
bytes memory str = new bytes(end-start); | |
for(i=0; i<str.length; i++){ | |
str[i] = v[start+i]; | |
} | |
for(i=end+1; i<v.length; i++) if (v[i] == ','){ i++; break; } //end | |
val = string(str); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment