Debian Codegraph @

src/main/org/h2/mvstore/DataUtils.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.mvstore;
7
8 import java.io.EOFException;
9 import java.io.IOException;
10 import java.io.OutputStream;
11 import java.nio.ByteBuffer;
12 import java.nio.channels.FileChannel;
13 import java.nio.charset.StandardCharsets;
14 import java.text.MessageFormat;
15 import java.util.Arrays;
16 import java.util.HashMap;
17 import java.util.Map;
18
19 import org.h2.engine.Constants;
20 import org.h2.jdbc.JdbcException;
21 import org.h2.util.StringUtils;
22
23 /**
24 * Utility methods
25 */
26 public final class DataUtils {
27
28 /**
29 * An error occurred while reading from the file.
30 */
31 public static final int ERROR_READING_FAILED = 1;
32
33 /**
34 * An error occurred when trying to write to the file.
35 */
36 public static final int ERROR_WRITING_FAILED = 2;
37
38 /**
39 * An internal error occurred. This could be a bug, or a memory corruption
40 * (for example caused by out of memory).
41 */
42 public static final int ERROR_INTERNAL = 3;
43
44 /**
45 * The object is already closed.
46 */
47 public static final int ERROR_CLOSED = 4;
48
49 /**
50 * The file format is not supported.
51 */
52 public static final int ERROR_UNSUPPORTED_FORMAT = 5;
53
54 /**
55 * The file is corrupt or (for encrypted files) the encryption key is wrong.
56 */
57 public static final int ERROR_FILE_CORRUPT = 6;
58
59 /**
60 * The file is locked.
61 */
62 public static final int ERROR_FILE_LOCKED = 7;
63
64 /**
65 * An error occurred when serializing or de-serializing.
66 */
67 public static final int ERROR_SERIALIZATION = 8;
68
69 /**
70 * The application was trying to read data from a chunk that is no longer
71 * available.
72 */
73 public static final int ERROR_CHUNK_NOT_FOUND = 9;
74
75 /**
76 * The block in the stream store was not found.
77 */
78 public static final int ERROR_BLOCK_NOT_FOUND = 50;
79
80 /**
81 * The transaction store is corrupt.
82 */
83 public static final int ERROR_TRANSACTION_CORRUPT = 100;
84
85 /**
86 * An entry is still locked by another transaction.
87 */
88 public static final int ERROR_TRANSACTION_LOCKED = 101;
89
90 /**
91 * There are too many open transactions.
92 */
93 public static final int ERROR_TOO_MANY_OPEN_TRANSACTIONS = 102;
94
95 /**
96 * The transaction store is in an illegal state (for example, not yet
97 * initialized).
98 */
99 public static final int ERROR_TRANSACTION_ILLEGAL_STATE = 103;
100
101 /**
102 * The transaction contains too many changes.
103 */
104 public static final int ERROR_TRANSACTION_TOO_BIG = 104;
105
106 /**
107 * Deadlock discovered and one of transactions involved chosen as victim and rolled back.
108 */
109 public static final int ERROR_TRANSACTIONS_DEADLOCK = 105;
110
111 /**
112 * The transaction store can not be initialized because data type
113 * is not found in type registry.
114 */
115 public static final int ERROR_UNKNOWN_DATA_TYPE = 106;
116
117 /**
118 * The type for leaf page.
119 */
120 public static final int PAGE_TYPE_LEAF = 0;
121
122 /**
123 * The type for node page.
124 */
125 public static final int PAGE_TYPE_NODE = 1;
126
127 /**
128 * The bit mask for compressed pages (compression level fast).
129 */
130 public static final int PAGE_COMPRESSED = 2;
131
132 /**
133 * The bit mask for compressed pages (compression level high).
134 */
135 public static final int PAGE_COMPRESSED_HIGH = 2 + 4;
136
137 /**
138 * The maximum integer that needs less space when using variable size
139 * encoding (only 3 bytes instead of 4).
140 */
141 public static final int COMPRESSED_VAR_INT_MAX = 0x1fffff;
142
143 /**
144 * The maximum long that needs less space when using variable size
145 * encoding (only 7 bytes instead of 8).
146 */
147 public static final long COMPRESSED_VAR_LONG_MAX = 0x1ffffffffffffL;
148
149 /**
150 * The marker size of a very large page.
151 */
152 public static final int PAGE_LARGE = 2 * 1024 * 1024;
153
154 // The following are key prefixes used in layout map
155
156 /**
157 * The prefix for chunks ("chunk."). This, plus the chunk id (hex encoded)
158 * is the key, and the serialized chunk metadata is the value.
159 */
160 public static final String META_CHUNK = "chunk.";
161
162 /**
163 * The prefix for root positions of maps ("root."). This, plus the map id
164 * (hex encoded) is the key, and the position (hex encoded) is the value.
165 */
166 public static final String META_ROOT = "root.";
167
168 // The following are key prefixes used in meta map
169
170 /**
171 * The prefix for names ("name."). This, plus the name of the map, is the
172 * key, and the map id (hex encoded) is the value.
173 */
174 public static final String META_NAME = "name.";
175
176 /**
177 * The prefix for maps ("map."). This, plus the map id (hex encoded) is the
178 * key, and the serialized in the map metadata is the value.
179 */
180 public static final String META_MAP = "map.";
181
182 /**
183 * Get the length of the variable size int.
184 *
185 * @param x the value
186 * @return the length in bytes
187 */
188 public static int getVarIntLen(int x) {
189 if ((x & (-1 << 7)) == 0) {
190 return 1;
191 } else if ((x & (-1 << 14)) == 0) {
192 return 2;
193 } else if ((x & (-1 << 21)) == 0) {
194 return 3;
195 } else if ((x & (-1 << 28)) == 0) {
196 return 4;
197 }
198 return 5;
199 }
200
201 /**
202 * Get the length of the variable size long.
203 *
204 * @param x the value
205 * @return the length in bytes
206 */
207 public static int getVarLongLen(long x) {
208 int i = 1;
209 while (true) {
210 x >>>= 7;
211 if (x == 0) {
212 return i;
213 }
214 i++;
215 }
216 }
217
218 /**
219 * Read a variable size int.
220 *
221 * @param buff the source buffer
222 * @return the value
223 */
224 public static int readVarInt(ByteBuffer buff) {
225 int b = buff.get();
226 if (b >= 0) {
227 return b;
228 }
229 // a separate function so that this one can be inlined
230 return readVarIntRest(buff, b);
231 }
232
233 private static int readVarIntRest(ByteBuffer buff, int b) {
234 int x = b & 0x7f;
235 b = buff.get();
236 if (b >= 0) {
237 return x | (b << 7);
238 }
239 x |= (b & 0x7f) << 7;
240 b = buff.get();
241 if (b >= 0) {
242 return x | (b << 14);
243 }
244 x |= (b & 0x7f) << 14;
245 b = buff.get();
246 if (b >= 0) {
247 return x | b << 21;
248 }
249 x |= ((b & 0x7f) << 21) | (buff.get() << 28);
250 return x;
251 }
252
253 /**
254 * Read a variable size long.
255 *
256 * @param buff the source buffer
257 * @return the value
258 */
259 public static long readVarLong(ByteBuffer buff) {
260 long x = buff.get();
261 if (x >= 0) {
262 return x;
263 }
264 x &= 0x7f;
265 for (int s = 7; s < 64; s += 7) {
266 long b = buff.get();
267 x |= (b & 0x7f) << s;
268 if (b >= 0) {
269 break;
270 }
271 }
272 return x;
273 }
274
275 /**
276 * Write a variable size int.
277 *
278 * @param out the output stream
279 * @param x the value
280 * @throws IOException if some data could not be written
281 */
282 public static void writeVarInt(OutputStream out, int x) throws IOException {
283 while ((x & ~0x7f) != 0) {
284 out.write((byte) (x | 0x80));
285 x >>>= 7;
286 }
287 out.write((byte) x);
288 }
289
290 /**
291 * Write a variable size int.
292 *
293 * @param buff the source buffer
294 * @param x the value
295 */
296 public static void writeVarInt(ByteBuffer buff, int x) {
297 while ((x & ~0x7f) != 0) {
298 buff.put((byte) (x | 0x80));
299 x >>>= 7;
300 }
301 buff.put((byte) x);
302 }
303
304 /**
305 * Write characters from a string (without the length).
306 *
307 * @param buff the target buffer (must be large enough)
308 * @param s the string
309 * @param len the number of characters
310 */
311 public static void writeStringData(ByteBuffer buff,
312 String s, int len) {
313 for (int i = 0; i < len; i++) {
314 int c = s.charAt(i);
315 if (c < 0x80) {
316 buff.put((byte) c);
317 } else if (c >= 0x800) {
318 buff.put((byte) (0xe0 | (c >> 12)));
319 buff.put((byte) ((c >> 6) & 0x3f));
320 buff.put((byte) (c & 0x3f));
321 } else {
322 buff.put((byte) (0xc0 | (c >> 6)));
323 buff.put((byte) (c & 0x3f));
324 }
325 }
326 }
327
328 /**
329 * Read a string.
330 *
331 * @param buff the source buffer
332 * @return the value
333 */
334 public static String readString(ByteBuffer buff) {
335 return readString(buff, readVarInt(buff));
336 }
337
338 /**
339 * Read a string.
340 *
341 * @param buff the source buffer
342 * @param len the number of characters
343 * @return the value
344 */
345 public static String readString(ByteBuffer buff, int len) {
346 char[] chars = new char[len];
347 for (int i = 0; i < len; i++) {
348 int x = buff.get() & 0xff;
349 if (x < 0x80) {
350 chars[i] = (char) x;
351 } else if (x >= 0xe0) {
352 chars[i] = (char) (((x & 0xf) << 12)
353 + ((buff.get() & 0x3f) << 6) + (buff.get() & 0x3f));
354 } else {
355 chars[i] = (char) (((x & 0x1f) << 6) + (buff.get() & 0x3f));
356 }
357 }
358 return new String(chars);
359 }
360
361 /**
362 * Write a variable size long.
363 *
364 * @param buff the target buffer
365 * @param x the value
366 */
367 public static void writeVarLong(ByteBuffer buff, long x) {
368 while ((x & ~0x7f) != 0) {
369 buff.put((byte) (x | 0x80));
370 x >>>= 7;
371 }
372 buff.put((byte) x);
373 }
374
375 /**
376 * Write a variable size long.
377 *
378 * @param out the output stream
379 * @param x the value
380 * @throws IOException if some data could not be written
381 */
382 public static void writeVarLong(OutputStream out, long x)
383 throws IOException {
384 while ((x & ~0x7f) != 0) {
385 out.write((byte) (x | 0x80));
386 x >>>= 7;
387 }
388 out.write((byte) x);
389 }
390
391 /**
392 * Copy the elements of an array, with a gap.
393 *
394 * @param src the source array
395 * @param dst the target array
396 * @param oldSize the size of the old array
397 * @param gapIndex the index of the gap
398 */
399 public static void copyWithGap(Object src, Object dst, int oldSize,
400 int gapIndex) {
401 if (gapIndex > 0) {
402 System.arraycopy(src, 0, dst, 0, gapIndex);
403 }
404 if (gapIndex < oldSize) {
405 System.arraycopy(src, gapIndex, dst, gapIndex + 1, oldSize
406 - gapIndex);
407 }
408 }
409
410 /**
411 * Copy the elements of an array, and remove one element.
412 *
413 * @param src the source array
414 * @param dst the target array
415 * @param oldSize the size of the old array
416 * @param removeIndex the index of the entry to remove
417 */
418 public static void copyExcept(Object src, Object dst, int oldSize,
419 int removeIndex) {
420 if (removeIndex > 0 && oldSize > 0) {
421 System.arraycopy(src, 0, dst, 0, removeIndex);
422 }
423 if (removeIndex < oldSize) {
424 System.arraycopy(src, removeIndex + 1, dst, removeIndex, oldSize
425 - removeIndex - 1);
426 }
427 }
428
429 /**
430 * Read from a file channel until the buffer is full.
431 * The buffer is rewind after reading.
432 *
433 * @param file the file channel
434 * @param pos the absolute position within the file
435 * @param dst the byte buffer
436 * @throws MVStoreException if some data could not be read
437 */
438 public static void readFully(FileChannel file, long pos, ByteBuffer dst) {
439 try {
440 do {
441 int len = file.read(dst, pos);
442 if (len < 0) {
443 throw new EOFException();
444 }
445 pos += len;
446 } while (dst.remaining() > 0);
447 dst.rewind();
448 } catch (IOException e) {
449 long size;
450 try {
451 size = file.size();
452 } catch (IOException e2) {
453 size = -1;
454 }
455 throw newMVStoreException(
456 ERROR_READING_FAILED,
457 "Reading from file {0} failed at {1} (length {2}), " +
458 "read {3}, remaining {4}",
459 file, pos, size, dst.position(), dst.remaining(), e);
460 }
461 }
462
463 /**
464 * Write to a file channel.
465 *
466 * @param file the file channel
467 * @param pos the absolute position within the file
468 * @param src the source buffer
469 */
470 public static void writeFully(FileChannel file, long pos, ByteBuffer src) {
471 try {
472 int off = 0;
473 do {
474 int len = file.write(src, pos + off);
475 off += len;
476 } while (src.remaining() > 0);
477 } catch (IOException e) {
478 throw newMVStoreException(
479 ERROR_WRITING_FAILED,
480 "Writing to {0} failed; length {1} at {2}",
481 file, src.remaining(), pos, e);
482 }
483 }
484
485 /**
486 * Convert the length to a length code 0..31. 31 means more than 1 MB.
487 *
488 * @param len the length
489 * @return the length code
490 */
491 public static int encodeLength(int len) {
492 assert len >= 0;
493 if (len <= 32) {
494 return 0;
495 }
496 int code = Integer.numberOfLeadingZeros(len);
497 int remaining = len << (code + 1);
498 code += code;
499 if ((remaining & (1 << 31)) != 0) {
500 code--;
501 }
502 if ((remaining << 1) != 0) {
503 code--;
504 }
505 code = Math.min(31, 52 - code);
506 // alternative code (slower):
507 // int x = len;
508 // int shift = 0;
509 // while (x > 3) {
510 // shift++;
511 // x = (x >>> 1) + (x & 1);
512 // }
513 // shift = Math.max(0, shift - 4);
514 // int code = (shift << 1) + (x & 1);
515 // code = Math.min(31, code);
516 return code;
517 }
518
519 /**
520 * Get the chunk id from the position.
521 *
522 * @param pos the position
523 * @return the chunk id
524 */
525 public static int getPageChunkId(long pos) {
526 return (int) (pos >>> 38);
527 }
528
529 /**
530 * Get the map id from the chunk's table of content element.
531 *
532 * @param tocElement packed table of content element
533 * @return the map id
534 */
535 public static int getPageMapId(long tocElement) {
536 return (int) (tocElement >>> 38);
537 }
538
539 /**
540 * Get the maximum length for the given page position.
541 *
542 * @param pos the position
543 * @return the maximum length
544 */
545 public static int getPageMaxLength(long pos) {
546 int code = (int) ((pos >> 1) & 31);
547 return decodePageLength(code);
548 }
549
550 /**
551 * Get the maximum length for the given code.
552 * For the code 31, PAGE_LARGE is returned.
553 *
554 * @param code encoded page length
555 * @return the maximum length
556 */
557 public static int decodePageLength(int code) {
558 if (code == 31) {
559 return PAGE_LARGE;
560 }
561 return (2 + (code & 1)) << ((code >> 1) + 4);
562 }
563
564 /**
565 * Get the offset from the position.
566 *
567 * @param tocElement packed table of content element
568 * @return the offset
569 */
570 public static int getPageOffset(long tocElement) {
571 return (int) (tocElement >> 6);
572 }
573
574 /**
575 * Get the page type from the position.
576 *
577 * @param pos the position
578 * @return the page type (PAGE_TYPE_NODE or PAGE_TYPE_LEAF)
579 */
580 public static int getPageType(long pos) {
581 return ((int) pos) & 1;
582 }
583
584 /**
585 * Determines whether specified file position corresponds to a leaf page
586 * @param pos the position
587 * @return true if it is a leaf, false otherwise
588 */
589 public static boolean isLeafPosition(long pos) {
590 return getPageType(pos) == PAGE_TYPE_LEAF;
591 }
592
593 /**
594 * Find out if page was saved.
595 *
596 * @param pos the position
597 * @return true if page has been saved
598 */
599 public static boolean isPageSaved(long pos) {
600 return (pos & ~1L) != 0;
601 }
602
603 /**
604 * Find out if page was removed.
605 *
606 * @param pos the position
607 * @return true if page has been removed (no longer accessible from the
608 * current root of the tree)
609 */
610 static boolean isPageRemoved(long pos) {
611 return pos == 1L;
612 }
613
614 /**
615 * Get the position of this page. The following information is encoded in
616 * the position: the chunk id, the page sequential number, the maximum length, and the type
617 * (node or leaf).
618 *
619 * @param chunkId the chunk id
620 * @param offset the offset
621 * @param length the length
622 * @param type the page type (1 for node, 0 for leaf)
623 * @return the position
624 */
625 public static long composePagePos(int chunkId, int offset, int length, int type) {
626 assert offset >= 0;
627 assert type == DataUtils.PAGE_TYPE_LEAF || type == DataUtils.PAGE_TYPE_NODE;
628
629 long pos = (long) chunkId << 38;
630 pos |= (long) offset << 6;
631 pos |= (long) encodeLength(length) << 1;
632 pos |= type;
633 return pos;
634 }
635
636 /**
637 * Convert tocElement into pagePos by replacing mapId with chunkId.
638 *
639 * @param chunkId the chunk id
640 * @param tocElement the element
641 * @return the page position
642 */
643 public static long composePagePos(int chunkId, long tocElement) {
644 return (tocElement & 0x3FFFFFFFFFL) | ((long) chunkId << 38);
645 }
646
647 /**
648 * Create table of content element. The following information is encoded in it:
649 * the map id, the page offset, the maximum length, and the type
650 * (node or leaf).
651 *
652 * @param mapId the chunk id
653 * @param offset the offset
654 * @param length the length
655 * @param type the page type (1 for node, 0 for leaf)
656 * @return the position
657 */
658 public static long composeTocElement(int mapId, int offset, int length, int type) {
659 assert mapId >= 0;
660 assert offset >= 0;
661 assert type == DataUtils.PAGE_TYPE_LEAF || type == DataUtils.PAGE_TYPE_NODE;
662 long pos = (long) mapId << 38;
663 pos |= (long) offset << 6;
664 pos |= (long) encodeLength(length) << 1;
665 pos |= type;
666 return pos;
667 }
668
669 /**
670 * Calculate a check value for the given integer. A check value is mean to
671 * verify the data is consistent with a high probability, but not meant to
672 * protect against media failure or deliberate changes.
673 *
674 * @param x the value
675 * @return the check value
676 */
677 public static short getCheckValue(int x) {
678 return (short) ((x >> 16) ^ x);
679 }
680
681 /**
682 * Append a map to the string builder, sorted by key.
683 *
684 * @param buff the target buffer
685 * @param map the map
686 * @return the string builder
687 */
688 public static StringBuilder appendMap(StringBuilder buff, HashMap<String, ?> map) {
689 Object[] keys = map.keySet().toArray();
690 Arrays.sort(keys);
691 for (Object k : keys) {
692 String key = (String) k;
693 Object value = map.get(key);
694 if (value instanceof Long) {
695 appendMap(buff, key, (long) value);
696 } else if (value instanceof Integer) {
697 appendMap(buff, key, (int) value);
698 } else {
699 appendMap(buff, key, value.toString());
700 }
701 }
702 return buff;
703 }
704
705 private static StringBuilder appendMapKey(StringBuilder buff, String key) {
706 if (buff.length() > 0) {
707 buff.append(',');
708 }
709 return buff.append(key).append(':');
710 }
711
712 /**
713 * Append a key-value pair to the string builder. Keys may not contain a
714 * colon. Values that contain a comma or a double quote are enclosed in
715 * double quotes, with special characters escaped using a backslash.
716 *
717 * @param buff the target buffer
718 * @param key the key
719 * @param value the value
720 */
721 public static void appendMap(StringBuilder buff, String key, String value) {
722 appendMapKey(buff, key);
723 if (value.indexOf(',') < 0 && value.indexOf('\"') < 0) {
724 buff.append(value);
725 } else {
726 buff.append('\"');
727 for (int i = 0, size = value.length(); i < size; i++) {
728 char c = value.charAt(i);
729 if (c == '\"') {
730 buff.append('\\');
731 }
732 buff.append(c);
733 }
734 buff.append('\"');
735 }
736 }
737
738 /**
739 * Append a key-value pair to the string builder. Keys may not contain a
740 * colon.
741 *
742 * @param buff the target buffer
743 * @param key the key
744 * @param value the value
745 */
746 public static void appendMap(StringBuilder buff, String key, long value) {
747 appendMapKey(buff, key).append(Long.toHexString(value));
748 }
749
750 /**
751 * Append a key-value pair to the string builder. Keys may not contain a
752 * colon.
753 *
754 * @param buff the target buffer
755 * @param key the key
756 * @param value the value
757 */
758 public static void appendMap(StringBuilder buff, String key, int value) {
759 appendMapKey(buff, key).append(Integer.toHexString(value));
760 }
761
762 /**
763 * @param buff output buffer, should be empty
764 * @param s parsed string
765 * @param i offset to parse from
766 * @param size stop offset (exclusive)
767 * @return new offset
768 */
769 private static int parseMapValue(StringBuilder buff, String s, int i, int size) {
770 while (i < size) {
771 char c = s.charAt(i++);
772 if (c == ',') {
773 break;
774 } else if (c == '\"') {
775 while (i < size) {
776 c = s.charAt(i++);
777 if (c == '\\') {
778 if (i == size) {
779 throw newMVStoreException(ERROR_FILE_CORRUPT, "Not a map: {0}", s);
780 }
781 c = s.charAt(i++);
782 } else if (c == '\"') {
783 break;
784 }
785 buff.append(c);
786 }
787 } else {
788 buff.append(c);
789 }
790 }
791 return i;
792 }
793
794 /**
795 * Parse a key-value pair list.
796 *
797 * @param s the list
798 * @return the map
799 * @throws MVStoreException if parsing failed
800 */
801 public static HashMap<String, String> parseMap(String s) {
802 HashMap<String, String> map = new HashMap<>();
803 StringBuilder buff = new StringBuilder();
804 for (int i = 0, size = s.length(); i < size;) {
805 int startKey = i;
806 i = s.indexOf(':', i);
807 if (i < 0) {
808 throw newMVStoreException(ERROR_FILE_CORRUPT, "Not a map: {0}", s);
809 }
810 String key = s.substring(startKey, i++);
811 i = parseMapValue(buff, s, i, size);
812 map.put(key, buff.toString());
813 buff.setLength(0);
814 }
815 return map;
816 }
817
818 /**
819 * Parse a key-value pair list and checks its checksum.
820 *
821 * @param bytes encoded map
822 * @return the map without mapping for {@code "fletcher"}, or {@code null} if checksum is wrong
823 * or parameter do not represent a properly formatted map serialization
824 */
825 static HashMap<String, String> parseChecksummedMap(byte[] bytes) {
826 int start = 0, end = bytes.length;
827 while (start < end && bytes[start] <= ' ') {
828 start++;
829 }
830 while (start < end && bytes[end - 1] <= ' ') {
831 end--;
832 }
833 String s = new String(bytes, start, end - start, StandardCharsets.ISO_8859_1);
834 HashMap<String, String> map = new HashMap<>();
835 StringBuilder buff = new StringBuilder();
836 for (int i = 0, size = s.length(); i < size;) {
837 int startKey = i;
838 i = s.indexOf(':', i);
839 if (i < 0) {
840 // Corrupted map
841 return null;
842 }
843 if (i - startKey == 8 && s.regionMatches(startKey, "fletcher", 0, 8)) {
844 parseMapValue(buff, s, i + 1, size);
845 int check = (int) Long.parseLong(buff.toString(), 16);
846 if (check == getFletcher32(bytes, start, startKey - 1)) {
847 return map;
848 }
849 // Corrupted map
850 return null;
851 }
852 String key = s.substring(startKey, i++);
853 i = parseMapValue(buff, s, i, size);
854 map.put(key, buff.toString());
855 buff.setLength(0);
856 }
857 // Corrupted map
858 return null;
859 }
860
861 /**
862 * Parse a name from key-value pair list.
863 *
864 * @param s the list
865 * @return value of name item, or {@code null}
866 * @throws MVStoreException if parsing failed
867 */
868 public static String getMapName(String s) {
869 return getFromMap(s, "name");
870 }
871
872 /**
873 * Parse a specified pair from key-value pair list.
874 *
875 * @param s the list
876 * @param key the name of the key
877 * @return value of the specified item, or {@code null}
878 * @throws MVStoreException if parsing failed
879 */
880 public static String getFromMap(String s, String key) {
881 int keyLength = key.length();
882 for (int i = 0, size = s.length(); i < size;) {
883 int startKey = i;
884 i = s.indexOf(':', i);
885 if (i < 0) {
886 throw newMVStoreException(ERROR_FILE_CORRUPT, "Not a map: {0}", s);
887 }
888 if (i++ - startKey == keyLength && s.regionMatches(startKey, key, 0, keyLength)) {
889 StringBuilder buff = new StringBuilder();
890 parseMapValue(buff, s, i, size);
891 return buff.toString();
892 } else {
893 while (i < size) {
894 char c = s.charAt(i++);
895 if (c == ',') {
896 break;
897 } else if (c == '\"') {
898 while (i < size) {
899 c = s.charAt(i++);
900 if (c == '\\') {
901 if (i++ == size) {
902 throw newMVStoreException(ERROR_FILE_CORRUPT, "Not a map: {0}", s);
903 }
904 } else if (c == '\"') {
905 break;
906 }
907 }
908 }
909 }
910 }
911 }
912 return null;
913 }
914
915 /**
916 * Calculate the Fletcher32 checksum.
917 *
918 * @param bytes the bytes
919 * @param offset initial offset
920 * @param length the message length (if odd, 0 is appended)
921 * @return the checksum
922 */
923 public static int getFletcher32(byte[] bytes, int offset, int length) {
924 int s1 = 0xffff, s2 = 0xffff;
925 int i = offset, len = offset + (length & ~1);
926 while (i < len) {
927 // reduce after 360 words (each word is two bytes)
928 for (int end = Math.min(i + 720, len); i < end;) {
929 int x = ((bytes[i++] & 0xff) << 8) | (bytes[i++] & 0xff);
930 s2 += s1 += x;
931 }
932 s1 = (s1 & 0xffff) + (s1 >>> 16);
933 s2 = (s2 & 0xffff) + (s2 >>> 16);
934 }
935 if ((length & 1) != 0) {
936 // odd length: append 0
937 int x = (bytes[i] & 0xff) << 8;
938 s2 += s1 += x;
939 }
940 s1 = (s1 & 0xffff) + (s1 >>> 16);
941 s2 = (s2 & 0xffff) + (s2 >>> 16);
942 return (s2 << 16) | s1;
943 }
944
945 /**
946 * Throw an IllegalArgumentException if the argument is invalid.
947 *
948 * @param test true if the argument is valid
949 * @param message the message
950 * @param arguments the arguments
951 * @throws IllegalArgumentException if the argument is invalid
952 */
953 public static void checkArgument(boolean test, String message,
954 Object... arguments) {
955 if (!test) {
956 throw newIllegalArgumentException(message, arguments);
957 }
958 }
959
960 /**
961 * Create a new IllegalArgumentException.
962 *
963 * @param message the message
964 * @param arguments the arguments
965 * @return the exception
966 */
967 public static IllegalArgumentException newIllegalArgumentException(
968 String message, Object... arguments) {
969 return initCause(new IllegalArgumentException(
970 formatMessage(0, message, arguments)),
971 arguments);
972 }
973
974 /**
975 * Create a new UnsupportedOperationException.
976 *
977 * @param message the message
978 * @return the exception
979 */
980 public static UnsupportedOperationException
981 newUnsupportedOperationException(String message) {
982 return new UnsupportedOperationException(formatMessage(0, message));
983 }
984
985 /**
986 * Create a new MVStoreException.
987 *
988 * @param errorCode the error code
989 * @param message the message
990 * @param arguments the arguments
991 * @return the exception
992 */
993 public static MVStoreException newMVStoreException(
994 int errorCode, String message, Object... arguments) {
995 return initCause(new MVStoreException(errorCode,
996 formatMessage(errorCode, message, arguments)),
997 arguments);
998 }
999
1000 private static <T extends Exception> T initCause(T e, Object... arguments) {
1001 int size = arguments.length;
1002 if (size > 0) {
1003 Object o = arguments[size - 1];
1004 if (o instanceof Throwable) {
1005 e.initCause((Throwable) o);
1006 }
1007 }
1008 return e;
1009 }
1010
1011 /**
1012 * Format an error message.
1013 *
1014 * @param errorCode the error code
1015 * @param message the message
1016 * @param arguments the arguments
1017 * @return the formatted message
1018 */
1019 public static String formatMessage(int errorCode, String message,
1020 Object... arguments) {
1021 // convert arguments to strings, to avoid locale specific formatting
1022 arguments = arguments.clone();
1023 for (int i = 0; i < arguments.length; i++) {
1024 Object a = arguments[i];
1025 if (!(a instanceof Exception)) {
1026 String s = a == null ? "null" : a.toString();
1027 if (s.length() > 1000) {
1028 s = s.substring(0, 1000) + "...";
1029 }
1030 arguments[i] = s;
1031 }
1032 }
1033 return MessageFormat.format(message, arguments) +
1034 " [" + Constants.VERSION_MAJOR + "." +
1035 Constants.VERSION_MINOR + "." + Constants.BUILD_ID +
1036 "/" + errorCode + "]";
1037 }
1038
1039 /**
1040 * Read a hex long value from a map.
1041 *
1042 * @param map the map
1043 * @param key the key
1044 * @param defaultValue if the value is null
1045 * @return the parsed value
1046 * @throws MVStoreException if parsing fails
1047 */
1048 public static long readHexLong(Map<String, ?> map, String key, long defaultValue) {
1049 Object v = map.get(key);
1050 if (v == null) {
1051 return defaultValue;
1052 } else if (v instanceof Long) {
1053 return (Long) v;
1054 }
1055 try {
1056 return parseHexLong((String) v);
1057 } catch (NumberFormatException e) {
1058 throw newMVStoreException(ERROR_FILE_CORRUPT,
1059 "Error parsing the value {0}", v, e);
1060 }
1061 }
1062
1063 /**
1064 * Parse an unsigned, hex long.
1065 *
1066 * @param x the string
1067 * @return the parsed value
1068 * @throws MVStoreException if parsing fails
1069 */
1070 public static long parseHexLong(String x) {
1071 try {
1072 if (x.length() == 16) {
1073 // avoid problems with overflow
1074 // in Java 8, this special case is not needed
1075 return (Long.parseLong(x.substring(0, 8), 16) << 32) |
1076 Long.parseLong(x.substring(8, 16), 16);
1077 }
1078 return Long.parseLong(x, 16);
1079 } catch (NumberFormatException e) {
1080 throw newMVStoreException(ERROR_FILE_CORRUPT,
1081 "Error parsing the value {0}", x, e);
1082 }
1083 }
1084
1085 /**
1086 * Parse an unsigned, hex long.
1087 *
1088 * @param x the string
1089 * @return the parsed value
1090 * @throws MVStoreException if parsing fails
1091 */
1092 public static int parseHexInt(String x) {
1093 try {
1094 // avoid problems with overflow
1095 // in Java 8, we can use Integer.parseLong(x, 16);
1096 return (int) Long.parseLong(x, 16);
1097 } catch (NumberFormatException e) {
1098 throw newMVStoreException(ERROR_FILE_CORRUPT,
1099 "Error parsing the value {0}", x, e);
1100 }
1101 }
1102
1103 /**
1104 * Read a hex int value from a map.
1105 *
1106 * @param map the map
1107 * @param key the key
1108 * @param defaultValue if the value is null
1109 * @return the parsed value
1110 * @throws MVStoreException if parsing fails
1111 */
1112 static int readHexInt(Map<String, ?> map, String key, int defaultValue) {
1113 Object v = map.get(key);
1114 if (v == null) {
1115 return defaultValue;
1116 } else if (v instanceof Integer) {
1117 return (Integer) v;
1118 }
1119 try {
1120 // support unsigned hex value
1121 return (int) Long.parseLong((String) v, 16);
1122 } catch (NumberFormatException e) {
1123 throw newMVStoreException(ERROR_FILE_CORRUPT,
1124 "Error parsing the value {0}", v, e);
1125 }
1126 }
1127
1128 /**
1129 * Parse the hex-encoded bytes of an entry in the map.
1130 *
1131 * @param map the map
1132 * @param key the key
1133 * @return the byte array, or null if not in the map
1134 */
1135 static byte[] parseHexBytes(Map<String, ?> map, String key) {
1136 Object v = map.get(key);
1137 if (v == null) {
1138 return null;
1139 }
1140 return StringUtils.convertHexToBytes((String)v);
1141 }
1142
1143 /**
1144 * Get the configuration parameter value, or default.
1145 *
1146 * @param config the configuration
1147 * @param key the key
1148 * @param defaultValue the default
1149 * @return the configured value or default
1150 */
1151 static int getConfigParam(Map<String, ?> config, String key, int defaultValue) {
1152 Object o = config.get(key);
1153 if (o instanceof Number) {
1154 return ((Number) o).intValue();
1155 } else if (o != null) {
1156 try {
1157 return Integer.decode(o.toString());
1158 } catch (NumberFormatException e) {
1159 // ignore
1160 }
1161 }
1162 return defaultValue;
1163 }
1164
1165 /**
1166 * Convert an exception to an IO exception.
1167 *
1168 * @param e the root cause
1169 * @return the IO exception
1170 */
1171 public static IOException convertToIOException(Throwable e) {
1172 if (e instanceof IOException) {
1173 return (IOException) e;
1174 }
1175 if (e instanceof JdbcException) {
1176 if (e.getCause() != null) {
1177 e = e.getCause();
1178 }
1179 }
1180 return new IOException(e.toString(), e);
1181 }
1182 }