Encode N bytes, as optimized as possible
(bytes []byte, saveWord bool)
| 851 | |
| 852 | // Encode N bytes, as optimized as possible |
| 853 | func (buf *Buffer) WriteBytesOptimized(bytes []byte, saveWord bool) (EncodeType, error) { |
| 854 | // Empty bytes can be represented with a no-op |
| 855 | // cost: 0 |
| 856 | if buf.Allows(FLAG_NO_OP) && len(bytes) == 0 { |
| 857 | buf.commitUint(FLAG_NO_OP) |
| 858 | buf.end(bytes, Stateless) |
| 859 | return Stateless, nil |
| 860 | } |
| 861 | |
| 862 | // 32 bytes long can be encoded as a word, it has its own set of optimizations. |
| 863 | // cost: word |
| 864 | if len(bytes) == 32 { |
| 865 | return buf.WriteWord(bytes, saveWord) |
| 866 | } |
| 867 | |
| 868 | // If all zeros it can be represented using the write-zeros flag |
| 869 | if buf.Allows(FLAG_WRITE_ZEROS) && len(bytes) <= 255 && bytesAreZero(bytes) { |
| 870 | buf.commitUint(FLAG_WRITE_ZEROS) |
| 871 | buf.commitByte(byte(len(bytes))) |
| 872 | buf.end(bytes, Stateless) |
| 873 | return Stateless, nil |
| 874 | } |
| 875 | |
| 876 | // Now we can try to find a mirror flag for the bytes |
| 877 | // cost: 2 bytes |
| 878 | bytesStr := string(bytes) |
| 879 | usedFlag := buf.Refs.usedFlags[bytesStr] |
| 880 | if buf.Allows(FLAG_MIRROR_FLAG_S) && usedFlag != 0 { |
| 881 | usedFlag -= 1 |
| 882 | |
| 883 | // We can only encode 16 bits for the mirror flag |
| 884 | // if it exceeds this value, then we can't mirror it |
| 885 | if usedFlag <= 0xffff { |
| 886 | buf.commitUint(FLAG_MIRROR_FLAG_S) |
| 887 | buf.commitBytes([]byte{byte(usedFlag >> 8), byte(usedFlag)}) |
| 888 | // end without creating a second pointer |
| 889 | // otherwise we will be creating a pointer to a pointer |
| 890 | buf.end([]byte{}, Mirror) |
| 891 | return Mirror, nil |
| 892 | } |
| 893 | } |
| 894 | |
| 895 | // Another optimization is to copy the bytes from the calldata |
| 896 | // cost: 3 bytes |
| 897 | copyIndex := buf.FindPastData(bytes) |
| 898 | if buf.Allows(FLAG_COPY_CALLDATA_S) && copyIndex != -1 && copyIndex <= 0xffffff && len(bytes) <= 0xffff { |
| 899 | if len(bytes) <= 0xff { |
| 900 | if copyIndex <= 0xffff { |
| 901 | buf.commitUint(FLAG_COPY_CALLDATA_S) |
| 902 | buf.commitBytes([]byte{byte(copyIndex >> 8), byte(copyIndex), byte(len(bytes))}) |
| 903 | buf.end([]byte{}, Stateless) |
| 904 | return Mirror, nil |
| 905 | } else { |
| 906 | buf.commitUint(FLAG_COPY_CALLDATA_L) |
| 907 | buf.commitBytes([]byte{byte(copyIndex >> 16), byte(copyIndex >> 8), byte(copyIndex), byte(len(bytes))}) |
| 908 | buf.end([]byte{}, Stateless) |
| 909 | return Mirror, nil |
| 910 | } |
no test coverage detected