Puts an UTF8 string into this byte vector. The byte vector is automatically enlarged if necessary. @param stringValue a String whose UTF8 encoded length must be less than 65536. @return this byte vector.
(final String stringValue)
| 240 | * @return this byte vector. |
| 241 | */ |
| 242 | public ByteVector putUTF8(final String stringValue) { |
| 243 | int charLength = stringValue.length(); |
| 244 | if (charLength > 65535) { |
| 245 | throw new IllegalArgumentException(); |
| 246 | } |
| 247 | int currentLength = length; |
| 248 | if (currentLength + 2 + charLength > data.length) { |
| 249 | enlarge(2 + charLength); |
| 250 | } |
| 251 | byte[] currentData = data; |
| 252 | // Optimistic algorithm: instead of computing the byte length and then serializing the string |
| 253 | // (which requires two loops), we assume the byte length is equal to char length (which is the |
| 254 | // most frequent case), and we start serializing the string right away. During the |
| 255 | // serialization, if we find that this assumption is wrong, we continue with the general method. |
| 256 | currentData[currentLength++] = (byte) (charLength >>> 8); |
| 257 | currentData[currentLength++] = (byte) charLength; |
| 258 | for (int i = 0; i < charLength; ++i) { |
| 259 | char charValue = stringValue.charAt(i); |
| 260 | if (charValue >= '\u0001' && charValue <= '\u007F') { |
| 261 | currentData[currentLength++] = (byte) charValue; |
| 262 | } else { |
| 263 | length = currentLength; |
| 264 | return encodeUTF8(stringValue, i, 65535); |
| 265 | } |
| 266 | } |
| 267 | length = currentLength; |
| 268 | return this; |
| 269 | } |
| 270 | |
| 271 | /** |
| 272 | * Puts an UTF8 string into this byte vector. The byte vector is automatically enlarged if |
no test coverage detected