aboutsummaryrefslogtreecommitdiffstats
path: root/packages/contracts/src/contracts/current/utils/LibBytes/LibBytes.sol
blob: f0a622fe48a10a9a8424a36534655ef3094d83fd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
/*

  Copyright 2018 ZeroEx Intl.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

*/

pragma solidity ^0.4.24;

contract LibBytes {

    // Revert reasons
    string constant GT_ZERO_LENGTH_REQUIRED = "Length must be greater than 0.";
    string constant GTE_4_LENGTH_REQUIRED = "Length must be greater than or equal to 4.";
    string constant GTE_20_LENGTH_REQUIRED = "Length must be greater than or equal to 20.";
    string constant GTE_32_LENGTH_REQUIRED = "Length must be greater than or equal to 32.";
    string constant INDEX_OUT_OF_BOUNDS = "Specified array index is out of bounds.";

    /// @dev Pops the last byte off of a byte array by modifying its length.
    /// @param b Byte array that will be modified.
    /// @return The byte that was popped off.
    function popByte(bytes memory b)
        internal
        returns (byte result)
    {
        require(
            b.length > 0,
            GT_ZERO_LENGTH_REQUIRED
        );

        result = b[b.length - 1];
        assembly {
            let newLen := sub(mload(b), 1)
            mstore(b, newLen)
        }
        result;
    }

    /// @dev Pops the last 20 bytes off of a byte array by modifying its length.
    /// @param b Byte array that will be modified.
    /// @return The 20 byte address that was popped off.
    function popAddress(bytes memory b)
        internal
        returns (address result)
    {
        require(
            b.length >= 20,
            GTE_20_LENGTH_REQUIRED
        );

        result = readAddress(b, b.length - 20);

        assembly {
            let newLen := sub(mload(b), 20)
            mstore(b, newLen)
        }
        return result;
    }

    /// @dev Tests equality of two byte arrays.
    /// @param lhs First byte array to compare.
    /// @param rhs Second byte array to compare.
    /// @return True if arrays are the same. False otherwise.
    function areBytesEqual(bytes memory lhs, bytes memory rhs)
        internal
        pure
        returns (bool equal)
    {
        assembly {
            // Get the number of words occupied by <lhs>
            let lenFullWords := div(add(mload(lhs), 0x1F), 0x20)

            // Add 1 to the number of words, to account for the length field
            lenFullWords := add(lenFullWords, 0x1)

            // Test equality word-by-word.
            // Terminates early if there is a mismatch.
            for {let i := 0} lt(i, lenFullWords) {i := add(i, 1)} {
                let lhsWord := mload(add(lhs, mul(i, 0x20)))
                let rhsWord := mload(add(rhs, mul(i, 0x20)))
                equal := eq(lhsWord, rhsWord)
                if eq(equal, 0) {
                    // Break
                    i := lenFullWords
                }
            }
       }

       return equal;
    }

    /// @dev Reads an address from a position in a byte array.
    /// @param b Byte array containing an address.
    /// @param index Index in byte array of address.
    /// @return address from byte array.
    function readAddress(
        bytes memory b,
        uint256 index)
        internal
        pure
        returns (address result)
    {
        require(
            b.length >= index + 20,  // 20 is length of address
            GTE_20_LENGTH_REQUIRED
        ); 

        // Add offset to index:
        // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
        // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
        index += 20;

        // Read address from array memory
        assembly {
            // 1. Add index to address of bytes array
            // 2. Load 32-byte word from memory
            // 3. Apply 20-byte mask to obtain address
            result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff)
        }
        return result;
    }

    /// @dev Writes an address into a specific position in a byte array.
    /// @param b Byte array to insert address into.
    /// @param index Index in byte array of address.
    /// @param input Address to put into byte array.
    function writeAddress(
        bytes memory b,
        uint256 index,
        address input)
        internal
        pure
    {
        require(
            b.length >= index + 20,  // 20 is length of address
            GTE_20_LENGTH_REQUIRED
        ); 

        // Add offset to index:
        // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
        // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
        index += 20;

        // Store address into array memory
        assembly {
            // The address occupies 20 bytes and mstore stores 32 bytes.
            // First fetch the 32-byte word where we'll be storing the address, then
            // apply a mask so we have only the bytes in the word that the address will not occupy.
            // Then combine these bytes with the address and store the 32 bytes back to memory with mstore.

            // 1. Add index to address of bytes array
            // 2. Load 32-byte word from memory
            // 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address
            let neighbors := and(mload(add(b, index)), 0xffffffffffffffffffffffff0000000000000000000000000000000000000000)

            // Store the neighbors and address into memory
            mstore(add(b, index), xor(input, neighbors))
        }
    }

    /// @dev Reads a bytes32 value from a position in a byte array.
    /// @param b Byte array containing a bytes32 value.
    /// @param index Index in byte array of bytes32 value.
    /// @return bytes32 value from byte array.
    function readBytes32(
        bytes memory b,
        uint256 index)
        internal
        pure
        returns (bytes32 result)
    {
        require(
            b.length >= index + 32,
            GTE_32_LENGTH_REQUIRED
        );

        // Arrays are prefixed by a 256 bit length parameter
        index += 32;

        // Read the bytes32 from array memory
        assembly {
            result := mload(add(b, index))
        }
        return result;
    }

    /// @dev Writes a bytes32 into a specific position in a byte array.
    /// @param b Byte array to insert <input> into.
    /// @param index Index in byte array of <input>.
    /// @param input bytes32 to put into byte array.
    function writeBytes32(
        bytes memory b,
        uint256 index,
        bytes32 input)
        internal
        pure
    {
        require(
            b.length >= index + 32,
            GTE_32_LENGTH_REQUIRED
        );

        // Arrays are prefixed by a 256 bit length parameter
        index += 32;

        // Read the bytes32 from array memory
        assembly {
            mstore(add(b, index), input)
        }
    }

    /// @dev Reads a uint256 value from a position in a byte array.
    /// @param b Byte array containing a uint256 value.
    /// @param index Index in byte array of uint256 value.
    /// @return uint256 value from byte array.
    function readUint256(
        bytes memory b,
        uint256 index)
        internal
        pure
        returns (uint256 result)
    {
        return uint256(readBytes32(b, index));
    }

    /// @dev Writes a uint256 into a specific position in a byte array.
    /// @param b Byte array to insert <input> into.
    /// @param index Index in byte array of <input>.
    /// @param input uint256 to put into byte array.
    function writeUint256(
        bytes memory b,
        uint256 index,
        uint256 input)
        internal
        pure
    {
        writeBytes32(b, index, bytes32(input));
    }

    /// @dev Reads the first 4 bytes from a byte array of arbitrary length.
    /// @param b Byte array to read first 4 bytes from.
    /// @return First 4 bytes of data.
    function readFirst4(bytes memory b)
        internal
        pure
        returns (bytes4 result)
    {
        require(
            b.length >= 4,
            GTE_4_LENGTH_REQUIRED
        );
        assembly {
            result := mload(add(b, 32))
        }
        return result;
    }
}