Debian Codegraph @

src/main/org/h2/mvstore/Page.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 static org.h2.engine.Constants.MEMORY_ARRAY;
9 import static org.h2.engine.Constants.MEMORY_OBJECT;
10 import static org.h2.engine.Constants.MEMORY_POINTER;
11 import static org.h2.mvstore.DataUtils.PAGE_TYPE_LEAF;
12 import java.nio.ByteBuffer;
13 import java.util.Arrays;
14 import java.util.concurrent.atomic.AtomicLongFieldUpdater;
15 import org.h2.compress.Compressor;
16 import org.h2.mvstore.FileStore.PageSerializationManager;
17 import org.h2.util.Utils;
18
19 /**
20 * A page (a node or a leaf).
21 * <p>
22 * For b-tree nodes, the key at a given index is larger than the largest key of
23 * the child at the same index.
24 * <p>
25 * Serialized format:
26 * length of a serialized page in bytes (including this field): int
27 * check value: short
28 * page number (0-based sequential number within a chunk): varInt
29 * map id: varInt
30 * number of keys: varInt
31 * type: byte (0: leaf, 1: node; +2: compressed)
32 * children of the non-leaf node (1 more than keys)
33 * compressed: bytes saved (varInt)
34 * keys
35 * values of the leaf node (one for each key)
36 */
37 public abstract class Page<K,V> implements Cloneable {
38
39 /**
40 * Map this page belongs to
41 */
42 public final MVMap<K,V> map;
43
44 /**
45 * Position of this page's saved image within a Chunk
46 * or 0 if this page has not been saved yet
47 * or 1 if this page has not been saved yet, but already removed
48 * This "removed" flag is to keep track of pages that concurrently
49 * changed while they are being stored, in which case the live bookkeeping
50 * needs to be aware of this fact.
51 * Field needs to be volatile to avoid races between saving thread setting it
52 * and other thread reading it to access the page.
53 * On top of this update atomicity is required so removal mark and saved position
54 * can be set concurrently.
55 *
56 * @see DataUtils#composePagePos(int, int, int, int) for field format details
57 */
58 private volatile long pos;
59
60 /**
61 * Sequential 0-based number of the page within containing chunk.
62 */
63 public int pageNo = -1;
64
65 /**
66 * The last result of a find operation is cached.
67 */
68 private int cachedCompare;
69
70 /**
71 * The estimated memory used in persistent case, IN_MEMORY marker value otherwise.
72 */
73 private int memory;
74
75 /**
76 * Amount of used disk space by this page only in persistent case.
77 */
78 private int diskSpaceUsed;
79
80 /**
81 * The keys.
82 */
83 private K[] keys;
84
85 /**
86 * Updater for pos field, which can be updated when page is saved,
87 * but can be concurrently marked as removed
88 */
89 @SuppressWarnings("rawtypes")
90 private static final AtomicLongFieldUpdater<Page> posUpdater =
91 AtomicLongFieldUpdater.newUpdater(Page.class, "pos");
92 /**
93 * The estimated number of bytes used per child entry.
94 */
95 static final int PAGE_MEMORY_CHILD = MEMORY_POINTER + 16; // 16 = two longs
96
97 /**
98 * The estimated number of bytes used per base page.
99 */
100 private static final int PAGE_MEMORY =
101 MEMORY_OBJECT + // this
102 2 * MEMORY_POINTER + // map, keys
103 MEMORY_ARRAY + // Object[] keys
104 17; // pos, cachedCompare, memory, removedInMemory
105 /**
106 * The estimated number of bytes used per empty internal page object.
107 */
108 static final int PAGE_NODE_MEMORY =
109 PAGE_MEMORY + // super
110 MEMORY_POINTER + // children
111 MEMORY_ARRAY + // Object[] children
112 8; // totalCount
113
114 /**
115 * The estimated number of bytes used per empty leaf page.
116 */
117 static final int PAGE_LEAF_MEMORY =
118 PAGE_MEMORY + // super
119 MEMORY_POINTER + // values
120 MEMORY_ARRAY; // Object[] values
121
122 /**
123 * Marker value for memory field, meaning that memory accounting is replaced by key count.
124 */
125 private static final int IN_MEMORY = Integer.MIN_VALUE;
126
127 @SuppressWarnings("rawtypes")
128 private static final PageReference[] SINGLE_EMPTY = { PageReference.EMPTY };
129
130
131 Page(MVMap<K,V> map) {
132 this.map = map;
133 }
134
135 Page(MVMap<K,V> map, Page<K,V> source) {
136 this(map, source.keys);
137 memory = source.memory;
138 }
139
140 Page(MVMap<K,V> map, K[] keys) {
141 this.map = map;
142 this.keys = keys;
143 }
144
145 /**
146 * Create a new, empty leaf page.
147 *
148 * @param <K> key type
149 * @param <V> value type
150 *
151 * @param map the map
152 * @return the new page
153 */
154 static <K,V> Page<K,V> createEmptyLeaf(MVMap<K,V> map) {
155 return createLeaf(map, map.getKeyType().createStorage(0),
156 map.getValueType().createStorage(0), PAGE_LEAF_MEMORY);
157 }
158
159 /**
160 * Create a new, empty internal node page.
161 *
162 * @param <K> key type
163 * @param <V> value type
164 *
165 * @param map the map
166 * @return the new page
167 */
168 @SuppressWarnings("unchecked")
169 static <K,V> Page<K,V> createEmptyNode(MVMap<K,V> map) {
170 return createNode(map, map.getKeyType().createStorage(0), SINGLE_EMPTY, 0,
171 PAGE_NODE_MEMORY + MEMORY_POINTER + PAGE_MEMORY_CHILD); // there is always one child
172 }
173
174 /**
175 * Create a new non-leaf page. The arrays are not cloned.
176 *
177 * @param <K> the key class
178 * @param <V> the value class
179 * @param map the map
180 * @param keys the keys
181 * @param children the child page positions
182 * @param totalCount the total number of keys
183 * @param memory the memory used in bytes
184 * @return the page
185 */
186 public static <K,V> Page<K,V> createNode(MVMap<K,V> map, K[] keys, PageReference<K,V>[] children,
187 long totalCount, int memory) {
188 assert keys != null;
189 Page<K,V> page = new NonLeaf<>(map, keys, children, totalCount);
190 page.initMemoryAccount(memory);
191 return page;
192 }
193
194 /**
195 * Create a new leaf page. The arrays are not cloned.
196 *
197 * @param <K> key type
198 * @param <V> value type
199 *
200 * @param map the map
201 * @param keys the keys
202 * @param values the values
203 * @param memory the memory used in bytes
204 * @return the page
205 */
206 static <K,V> Page<K,V> createLeaf(MVMap<K,V> map, K[] keys, V[] values, int memory) {
207 assert keys != null;
208 Page<K,V> page = new Leaf<>(map, keys, values);
209 page.initMemoryAccount(memory);
210 return page;
211 }
212
213 private void initMemoryAccount(int memoryCount) {
214 if(!map.isPersistent()) {
215 memory = IN_MEMORY;
216 } else if (memoryCount == 0) {
217 recalculateMemory();
218 } else {
219 addMemory(memoryCount);
220 assert memoryCount == getMemory();
221 }
222 }
223
224 /**
225 * Get the value for the given key, or null if not found.
226 * Search is done in the tree rooted at given page.
227 *
228 * @param <K> key type
229 * @param <V> value type
230 *
231 * @param key the key
232 * @param p the root page
233 * @return the value, or null if not found
234 */
235 static <K,V> V get(Page<K,V> p, K key) {
236 while (true) {
237 int index = p.binarySearch(key);
238 if (p.isLeaf()) {
239 return index >= 0 ? p.getValue(index) : null;
240 } else if (index++ < 0) {
241 index = -index;
242 }
243 p = p.getChildPage(index);
244 }
245 }
246
247 /**
248 * Read a page.
249 *
250 * @param <K> key type
251 * @param <V> value type
252 *
253 * @param buff ByteBuffer containing serialized page info
254 * @param pos the position
255 * @param map the map
256 * @return the page
257 */
258 static <K,V> Page<K,V> read(ByteBuffer buff, long pos, MVMap<K,V> map) {
259 boolean leaf = (DataUtils.getPageType(pos) & 1) == PAGE_TYPE_LEAF;
260 Page<K,V> p = leaf ? new Leaf<>(map) : new NonLeaf<>(map);
261 p.pos = pos;
262 p.read(buff);
263 return p;
264 }
265
266 /**
267 * Get the id of the page's owner map
268 * @return id
269 */
270 public final int getMapId() {
271 return map.getId();
272 }
273
274 /**
275 * Create a copy of this page with potentially different owning map.
276 * This is used exclusively during bulk map copying.
277 * Child page references for nodes are cleared (re-pointed to an empty page)
278 * to be filled-in later to copying procedure. This way it can be saved
279 * mid-process without tree integrity violation
280 *
281 * @param map new map to own resulting page
282 * @param eraseChildrenRefs whether cloned Page should have no child references or keep originals
283 * @return the page
284 */
285 abstract Page<K,V> copy(MVMap<K, V> map, boolean eraseChildrenRefs);
286
287 /**
288 * Get the key at the given index.
289 *
290 * @param index the index
291 * @return the key
292 */
293 public K getKey(int index) {
294 return keys[index];
295 }
296
297 /**
298 * Get the child page at the given index.
299 *
300 * @param index the index
301 * @return the child page
302 */
303 public abstract Page<K,V> getChildPage(int index);
304
305 /**
306 * Get the position of the child.
307 *
308 * @param index the index
309 * @return the position
310 */
311 public abstract long getChildPagePos(int index);
312
313 /**
314 * Get the value at the given index.
315 *
316 * @param index the index
317 * @return the value
318 */
319 public abstract V getValue(int index);
320
321 /**
322 * Get the number of keys in this page.
323 *
324 * @return the number of keys
325 */
326 public final int getKeyCount() {
327 return keys.length;
328 }
329
330 /**
331 * Check whether this is a leaf page.
332 *
333 * @return true if it is a leaf
334 */
335 public final boolean isLeaf() {
336 return getNodeType() == PAGE_TYPE_LEAF;
337 }
338
339 public abstract int getNodeType();
340
341 /**
342 * Get the position of the page
343 *
344 * @return the position
345 */
346 public final long getPos() {
347 return pos;
348 }
349
350 @Override
351 public String toString() {
352 StringBuilder buff = new StringBuilder();
353 dump(buff);
354 return buff.toString();
355 }
356
357 /**
358 * Dump debug data for this page.
359 *
360 * @param buff append buffer
361 */
362 protected void dump(StringBuilder buff) {
363 buff.append("id: ").append(System.identityHashCode(this)).append('\n');
364 buff.append("pos: ").append(Long.toHexString(pos)).append('\n');
365 if (isSaved()) {
366 int chunkId = DataUtils.getPageChunkId(pos);
367 buff.append("chunk:").append(Long.toHexString(chunkId));
368 if (pageNo >= 0) {
369 buff.append(",no:").append(Long.toHexString(pageNo));
370 }
371 buff.append('\n');
372 }
373 }
374
375 /**
376 * Create a copy of this page.
377 *
378 * @return a mutable copy of this page
379 */
380 public final Page<K,V> copy() {
381 Page<K,V> newPage = clone();
382 newPage.pos = 0;
383 newPage.pageNo = -1;
384 return newPage;
385 }
386
387 @SuppressWarnings("unchecked")
388 @Override
389 protected final Page<K,V> clone() {
390 Page<K,V> clone;
391 try {
392 clone = (Page<K,V>) super.clone();
393 } catch (CloneNotSupportedException impossible) {
394 throw new RuntimeException(impossible);
395 }
396 return clone;
397 }
398
399 /**
400 * Search the key in this page using a binary search. Instead of always
401 * starting the search in the middle, the last found index is cached.
402 * <p>
403 * If the key was found, the returned value is the index in the key array.
404 * If not found, the returned value is negative, where -1 means the provided
405 * key is smaller than any keys in this page. See also Arrays.binarySearch.
406 *
407 * @param key the key
408 * @return the value or null
409 */
410 int binarySearch(K key) {
411 int res = map.getKeyType().binarySearch(key, keys, getKeyCount(), cachedCompare);
412 cachedCompare = res < 0 ? ~res : res + 1;
413 return res;
414 }
415
416 /**
417 * Split the page. This modifies the current page.
418 *
419 * @param at the split index
420 * @return the page with the entries after the split index
421 */
422 abstract Page<K,V> split(int at);
423
424 /**
425 * Split the current keys array into two arrays.
426 *
427 * @param aCount size of the first array.
428 * @param bCount size of the second array/
429 * @return the second array.
430 */
431 final K[] splitKeys(int aCount, int bCount) {
432 assert aCount + bCount <= getKeyCount();
433 K[] aKeys = createKeyStorage(aCount);
434 K[] bKeys = createKeyStorage(bCount);
435 System.arraycopy(keys, 0, aKeys, 0, aCount);
436 System.arraycopy(keys, getKeyCount() - bCount, bKeys, 0, bCount);
437 keys = aKeys;
438 return bKeys;
439 }
440
441 /**
442 * Append additional key/value mappings to this Page.
443 * New mappings suppose to be in correct key order.
444 *
445 * @param extraKeyCount number of mappings to be added
446 * @param extraKeys to be added
447 * @param extraValues to be added
448 */
449 abstract void expand(int extraKeyCount, K[] extraKeys, V[] extraValues);
450
451 /**
452 * Expand the keys array.
453 *
454 * @param extraKeyCount number of extra key entries to create
455 * @param extraKeys extra key values
456 */
457 final void expandKeys(int extraKeyCount, K[] extraKeys) {
458 int keyCount = getKeyCount();
459 K[] newKeys = createKeyStorage(keyCount + extraKeyCount);
460 System.arraycopy(keys, 0, newKeys, 0, keyCount);
461 System.arraycopy(extraKeys, 0, newKeys, keyCount, extraKeyCount);
462 keys = newKeys;
463 }
464
465 /**
466 * Get the total number of key-value pairs, including child pages.
467 *
468 * @return the number of key-value pairs
469 */
470 public abstract long getTotalCount();
471
472 /**
473 * Get the number of key-value pairs for a given child.
474 *
475 * @param index the child index
476 * @return the descendant count
477 */
478 abstract long getCounts(int index);
479
480 /**
481 * Replace the child page.
482 *
483 * @param index the index
484 * @param c the new child page
485 */
486 public abstract void setChild(int index, Page<K,V> c);
487
488 /**
489 * Replace the key at an index in this page.
490 *
491 * @param index the index
492 * @param key the new key
493 */
494 public final void setKey(int index, K key) {
495 keys = keys.clone();
496 if(isPersistent()) {
497 K old = keys[index];
498 if (!map.isMemoryEstimationAllowed() || old == null) {
499 int mem = map.evaluateMemoryForKey(key);
500 if (old != null) {
501 mem -= map.evaluateMemoryForKey(old);
502 }
503 addMemory(mem);
504 }
505 }
506 keys[index] = key;
507 }
508
509 /**
510 * Replace the value at an index in this page.
511 *
512 * @param index the index
513 * @param value the new value
514 * @return the old value
515 */
516 public abstract V setValue(int index, V value);
517
518 /**
519 * Insert a key-value pair into this leaf.
520 *
521 * @param index the index
522 * @param key the key
523 * @param value the value
524 */
525 public abstract void insertLeaf(int index, K key, V value);
526
527 /**
528 * Insert a child page into this node.
529 *
530 * @param index the index
531 * @param key the key
532 * @param childPage the child page
533 */
534 public abstract void insertNode(int index, K key, Page<K,V> childPage);
535
536 /**
537 * Insert a key into the key array
538 *
539 * @param index index to insert at
540 * @param key the key value
541 */
542 final void insertKey(int index, K key) {
543 int keyCount = getKeyCount();
544 assert index <= keyCount : index + " > " + keyCount;
545 K[] newKeys = createKeyStorage(keyCount + 1);
546 DataUtils.copyWithGap(keys, newKeys, keyCount, index);
547 keys = newKeys;
548
549 keys[index] = key;
550
551 if (isPersistent()) {
552 addMemory(MEMORY_POINTER + map.evaluateMemoryForKey(key));
553 }
554 }
555
556 /**
557 * Remove the key and value (or child) at the given index.
558 *
559 * @param index the index
560 */
561 public void remove(int index) {
562 int keyCount = getKeyCount();
563 if (index == keyCount) {
564 --index;
565 }
566 if(isPersistent()) {
567 if (!map.isMemoryEstimationAllowed()) {
568 K old = getKey(index);
569 addMemory(-MEMORY_POINTER - map.evaluateMemoryForKey(old));
570 }
571 }
572 K[] newKeys = createKeyStorage(keyCount - 1);
573 DataUtils.copyExcept(keys, newKeys, keyCount, index);
574 keys = newKeys;
575 }
576
577 /**
578 * Read the page from the buffer.
579 *
580 * @param buff the buffer to read from
581 */
582 private void read(ByteBuffer buff) {
583 int chunkId = DataUtils.getPageChunkId(pos);
584 int offset = DataUtils.getPageOffset(pos);
585
586 int start = buff.position();
587 int pageLength = buff.getInt(); // does not include optional part (pageNo)
588 int remaining = buff.remaining() + 4;
589 if (pageLength > remaining || pageLength < 4) {
590 throw DataUtils.newMVStoreException(DataUtils.ERROR_FILE_CORRUPT,
591 "File corrupted in chunk {0}, expected page length 4..{1}, got {2}", chunkId, remaining,
592 pageLength);
593 }
594
595 short check = buff.getShort();
596 int checkTest = DataUtils.getCheckValue(chunkId)
597 ^ DataUtils.getCheckValue(offset)
598 ^ DataUtils.getCheckValue(pageLength);
599 if (check != (short) checkTest) {
600 throw DataUtils.newMVStoreException(DataUtils.ERROR_FILE_CORRUPT,
601 "File corrupted in chunk {0}, expected check value {1}, got {2}", chunkId, checkTest, check);
602 }
603
604 pageNo = DataUtils.readVarInt(buff);
605 if (pageNo < 0) {
606 throw DataUtils.newMVStoreException(DataUtils.ERROR_FILE_CORRUPT,
607 "File corrupted in chunk {0}, got negative page No {1}", chunkId, pageNo);
608 }
609
610 int mapId = DataUtils.readVarInt(buff);
611 if (mapId != map.getId()) {
612 throw DataUtils.newMVStoreException(DataUtils.ERROR_FILE_CORRUPT,
613 "File corrupted in chunk {0}, expected map id {1}, got {2}", chunkId, map.getId(), mapId);
614 }
615
616 int keyCount = DataUtils.readVarInt(buff);
617 keys = createKeyStorage(keyCount);
618 int type = buff.get();
619 if(isLeaf() != ((type & 1) == PAGE_TYPE_LEAF)) {
620 throw DataUtils.newMVStoreException(
621 DataUtils.ERROR_FILE_CORRUPT,
622 "File corrupted in chunk {0}, expected node type {1}, got {2}",
623 chunkId, isLeaf() ? "0" : "1" , type);
624 }
625
626 // to restrain hacky GenericDataType, which grabs the whole remainder of the buffer
627 buff.limit(start + pageLength);
628
629 if (!isLeaf()) {
630 readPayLoad(buff);
631 }
632 boolean compressed = (type & DataUtils.PAGE_COMPRESSED) != 0;
633 if (compressed) {
634 Compressor compressor;
635 if ((type & DataUtils.PAGE_COMPRESSED_HIGH) ==
636 DataUtils.PAGE_COMPRESSED_HIGH) {
637 compressor = map.getStore().getCompressorHigh();
638 } else {
639 compressor = map.getStore().getCompressorFast();
640 }
641 int lenAdd = DataUtils.readVarInt(buff);
642 int compLen = buff.remaining();
643 byte[] comp;
644 int pos = 0;
645 if (buff.hasArray()) {
646 comp = buff.array();
647 pos = buff.arrayOffset() + buff.position();
648 } else {
649 comp = Utils.newBytes(compLen);
650 buff.get(comp);
651 }
652 int l = compLen + lenAdd;
653 buff = ByteBuffer.allocate(l);
654 compressor.expand(comp, pos, compLen, buff.array(),
655 buff.arrayOffset(), l);
656 }
657 map.getKeyType().read(buff, keys, keyCount);
658 if (isLeaf()) {
659 readPayLoad(buff);
660 }
661 diskSpaceUsed = pageLength;
662 recalculateMemory();
663 }
664
665 /**
666 * Read the page payload from the buffer.
667 *
668 * @param buff the buffer
669 */
670 protected abstract void readPayLoad(ByteBuffer buff);
671
672 public final boolean isSaved() {
673 return DataUtils.isPageSaved(pos);
674 }
675
676 public final boolean isRemoved() {
677 return DataUtils.isPageRemoved(pos);
678 }
679
680 /**
681 * Mark this page as removed "in memory". That means that only adjustment of
682 * "unsaved memory" amount is required. On the other hand, if page was
683 * persisted, it's removal should be reflected in occupancy of the
684 * containing chunk.
685 *
686 * @return true if it was marked by this call or has been marked already,
687 * false if page has been saved already.
688 */
689 private boolean markAsRemoved() {
690 assert getTotalCount() > 0 : this;
691 long pagePos;
692 do {
693 pagePos = pos;
694 if (DataUtils.isPageSaved(pagePos)) {
695 return false;
696 }
697 assert !DataUtils.isPageRemoved(pagePos);
698 } while (!posUpdater.compareAndSet(this, 0L, 1L));
699 return true;
700 }
701
702 /**
703 * Serializes this page into provided buffer, which represents content of the specified
704 * chunk to be persisted and updates the "position" of the page.
705 *
706 * @param pageSerializationManager which provides a target buffer
707 * and can be queried for various attributes
708 * related to serialization
709 * @return the position of the buffer, where serialized child page references (if any) begin
710 */
711 protected final int write(FileStore<?>.PageSerializationManager pageSerializationManager) {
712 pageNo = pageSerializationManager.getPageNo();
713 int keyCount = getKeyCount();
714 WriteBuffer buff = pageSerializationManager.getBuffer();
715 int start = buff.position();
716 buff.putInt(0) // placeholder for pageLength
717 .putShort((byte)0) // placeholder for check
718 .putVarInt(pageNo)
719 .putVarInt(map.getId())
720 .putVarInt(keyCount);
721 int typePos = buff.position();
722 int type = isLeaf() ? PAGE_TYPE_LEAF : DataUtils.PAGE_TYPE_NODE;
723 buff.put((byte)type);
724 int childrenPos = buff.position();
725 writeChildren(buff, true);
726 int compressStart = buff.position();
727 map.getKeyType().write(buff, keys, keyCount);
728 writeValues(buff);
729 MVStore store = map.getStore();
730 int expLen = buff.position() - compressStart;
731 if (expLen > 16) {
732 int compressionLevel = store.getCompressionLevel();
733 if (compressionLevel > 0) {
734 Compressor compressor;
735 int compressType;
736 if (compressionLevel == 1) {
737 compressor = store.getCompressorFast();
738 compressType = DataUtils.PAGE_COMPRESSED;
739 } else {
740 compressor = store.getCompressorHigh();
741 compressType = DataUtils.PAGE_COMPRESSED_HIGH;
742 }
743 byte[] comp = new byte[expLen * 2];
744 ByteBuffer byteBuffer = buff.getBuffer();
745 int pos = 0;
746 byte[] exp;
747 if (byteBuffer.hasArray()) {
748 exp = byteBuffer.array();
749 pos = byteBuffer.arrayOffset() + compressStart;
750 } else {
751 exp = Utils.newBytes(expLen);
752 buff.position(compressStart).get(exp);
753 }
754 int compLen = compressor.compress(exp, pos, expLen, comp, 0);
755 int plus = DataUtils.getVarIntLen(expLen - compLen);
756 if (compLen + plus < expLen) {
757 buff.position(typePos)
758 .put((byte) (type | compressType));
759 buff.position(compressStart)
760 .putVarInt(expLen - compLen)
761 .put(comp, 0, compLen);
762 }
763 }
764 }
765 int pageLength = buff.position() - start;
766 long pagePos = pageSerializationManager.getPagePosition(getMapId(), start, pageLength, type);
767 if (isSaved()) {
768 throw DataUtils.newMVStoreException(
769 DataUtils.ERROR_INTERNAL, "Page already stored");
770 }
771 boolean isDeleted = isRemoved();
772 while (!posUpdater.compareAndSet(this, isDeleted ? 1L : 0L, pagePos)) {
773 isDeleted = isRemoved();
774 }
775 int pageLengthDecoded = DataUtils.getPageMaxLength(pagePos);
776 diskSpaceUsed = pageLengthDecoded != DataUtils.PAGE_LARGE ? pageLengthDecoded : pageLength;
777 boolean singleWriter = map.isSingleWriter();
778
779 pageSerializationManager.onPageSerialized(this, isDeleted, pageLengthDecoded, singleWriter);
780 return childrenPos;
781 }
782
783 /**
784 * Write values that the buffer contains to the buff.
785 *
786 * @param buff the target buffer
787 */
788 protected abstract void writeValues(WriteBuffer buff);
789
790 /**
791 * Write page children to the buff.
792 *
793 * @param buff the target buffer
794 * @param withCounts true if the descendant counts should be written
795 */
796 protected abstract void writeChildren(WriteBuffer buff, boolean withCounts);
797
798 /**
799 * Store this page and all children that are changed, in reverse order, and
800 * update the position and the children.
801 *
802 * @param pageSerializationManager which provides a target buffer
803 * and can be queried for various attributes
804 * related to serialization
805 */
806 abstract void writeUnsavedRecursive(PageSerializationManager pageSerializationManager);
807
808 /**
809 * Unlink the children recursively after all data is written.
810 */
811 abstract void releaseSavedPages();
812
813 public abstract int getRawChildPageCount();
814
815 protected final boolean isPersistent() {
816 return memory != IN_MEMORY;
817 }
818
819 public final int getMemory() {
820 if (isPersistent()) {
821 // assert memory == calculateMemory() :
822 // "Memory calculation error " + memory + " != " + calculateMemory();
823 return memory;
824 }
825 return 0;
826 }
827
828 /**
829 * Amount of used disk space in persistent case including child pages.
830 *
831 * @return amount of used disk space in persistent case
832 */
833 public long getDiskSpaceUsed() {
834 long r = 0;
835 if (isPersistent()) {
836 r += diskSpaceUsed;
837 if (!isLeaf()) {
838 for (int i = 0; i < getRawChildPageCount(); i++) {
839 long pos = getChildPagePos(i);
840 if (pos != 0) {
841 r += getChildPage(i).getDiskSpaceUsed();
842 }
843 }
844 }
845 }
846 return r;
847 }
848
849 /**
850 * Increase estimated memory used in persistent case.
851 *
852 * @param mem additional memory size.
853 */
854 final void addMemory(int mem) {
855 memory += mem;
856 assert memory >= 0;
857 }
858
859 /**
860 * Recalculate estimated memory used in persistent case.
861 */
862 final void recalculateMemory() {
863 assert isPersistent();
864 memory = calculateMemory();
865 }
866
867 /**
868 * Calculate estimated memory used in persistent case.
869 *
870 * @return memory in bytes
871 */
872 protected int calculateMemory() {
873 //*
874 return map.evaluateMemoryForKeys(keys, getKeyCount());
875 /*/
876 int keyCount = getKeyCount();
877 int mem = keyCount * MEMORY_POINTER;
878 DataType<K> keyType = map.getKeyType();
879 for (int i = 0; i < keyCount; i++) {
880 mem += getMemory(keyType, keys[i]);
881 }
882 return mem;
883 //*/
884 }
885
886 public boolean isComplete() {
887 return true;
888 }
889
890 /**
891 * Called when done with copying page.
892 */
893 public void setComplete() {}
894
895 /**
896 * Make accounting changes (chunk occupancy or "unsaved" RAM), related to
897 * this page removal.
898 *
899 * @param version at which page was removed
900 * @return amount (negative), by which "unsaved memory" should be adjusted,
901 * if page is unsaved one, and 0 for page that was already saved, or
902 * in case of non-persistent map
903 */
904 public final int removePage(long version) {
905 if(isPersistent() && getTotalCount() > 0) {
906 MVStore store = map.store;
907 if (!markAsRemoved()) { // only if it has been saved already
908 long pagePos = pos;
909 store.accountForRemovedPage(pagePos, version, map.isSingleWriter(), pageNo);
910 } else {
911 return -memory;
912 }
913 }
914 return 0;
915 }
916
917 /**
918 * Extend path from a given CursorPos chain to "prepend point" in a B-tree, rooted at this Page.
919 *
920 * @param cursorPos presumably pointing to this Page (null if real root), to build upon
921 * @return new head of the CursorPos chain
922 */
923 public abstract CursorPos<K,V> getPrependCursorPos(CursorPos<K,V> cursorPos);
924
925 /**
926 * Extend path from a given CursorPos chain to "append point" in a B-tree, rooted at this Page.
927 *
928 * @param cursorPos presumably pointing to this Page (null if real root), to build upon
929 * @return new head of the CursorPos chain
930 */
931 public abstract CursorPos<K,V> getAppendCursorPos(CursorPos<K,V> cursorPos);
932
933 /**
934 * Remove all page data recursively.
935 * @param version at which page got removed
936 * @return adjustment for "unsaved memory" amount
937 */
938 public abstract int removeAllRecursive(long version);
939
940 /**
941 * Create array for keys storage.
942 *
943 * @param size number of entries
944 * @return values array
945 */
946 public final K[] createKeyStorage(int size) {
947 return map.getKeyType().createStorage(size);
948 }
949
950 /**
951 * Create array for values storage.
952 *
953 * @param size number of entries
954 * @return values array
955 */
956 final V[] createValueStorage(int size) {
957 return map.getValueType().createStorage(size);
958 }
959
960 /**
961 * Create an array of page references.
962 *
963 * @param <K> the key class
964 * @param <V> the value class
965 * @param size the number of entries
966 * @return the array
967 */
968 @SuppressWarnings("unchecked")
969 public static <K,V> PageReference<K,V>[] createRefStorage(int size) {
970 return new PageReference[size];
971 }
972
973 /**
974 * A pointer to a page, either in-memory or using a page position.
975 */
976 public static final class PageReference<K,V> {
977
978 /**
979 * Singleton object used when arrays of PageReference have not yet been filled.
980 */
981 @SuppressWarnings("rawtypes")
982 static final PageReference EMPTY = new PageReference<>(null, 0, 0);
983
984 /**
985 * The position, if known, or 0.
986 */
987 private long pos;
988
989 /**
990 * The page, if in memory, or null.
991 */
992 private Page<K,V> page;
993
994 /**
995 * The descendant count for this child page.
996 */
997 final long count;
998
999 /**
1000 * Get an empty page reference.
1001 *
1002 * @param <X> the key class
1003 * @param <Y> the value class
1004 * @return the page reference
1005 */
1006 @SuppressWarnings("unchecked")
1007 public static <X,Y> PageReference<X,Y> empty() {
1008 return EMPTY;
1009 }
1010
1011 public PageReference(Page<K,V> page) {
1012 this(page, page.getPos(), page.getTotalCount());
1013 }
1014
1015 PageReference(long pos, long count) {
1016 this(null, pos, count);
1017 assert DataUtils.isPageSaved(pos);
1018 }
1019
1020 private PageReference(Page<K,V> page, long pos, long count) {
1021 this.page = page;
1022 this.pos = pos;
1023 this.count = count;
1024 }
1025
1026 public Page<K,V> getPage() {
1027 return page;
1028 }
1029
1030 /**
1031 * Clear if necessary, reference to the actual child Page object,
1032 * so it can be garbage collected if not actively used elsewhere.
1033 * Reference is cleared only if corresponding page was already saved on a disk.
1034 */
1035 void clearPageReference() {
1036 if (page != null) {
1037 page.releaseSavedPages();
1038 assert page.isSaved() || !page.isComplete();
1039 if (page.isSaved()) {
1040 assert pos == page.getPos();
1041 assert count == page.getTotalCount() : count + " != " + page.getTotalCount();
1042 page = null;
1043 }
1044 }
1045 }
1046
1047 long getPos() {
1048 return pos;
1049 }
1050
1051 /**
1052 * Re-acquire position from in-memory page.
1053 */
1054 void resetPos() {
1055 Page<K,V> p = page;
1056 if (p != null && p.isSaved()) {
1057 pos = p.getPos();
1058 assert count == p.getTotalCount();
1059 }
1060 }
1061
1062 @Override
1063 public String toString() {
1064 return "Cnt:" + count + ", pos:" + (pos == 0 ? "0" : DataUtils.getPageChunkId(pos) +
1065 (page == null ? "" : "/" + page.pageNo) +
1066 "-" + DataUtils.getPageOffset(pos) + ":" + DataUtils.getPageMaxLength(pos)) +
1067 ((page == null ? DataUtils.getPageType(pos) == 0 : page.isLeaf()) ? " leaf" : " node") +
1068 ", page:{" + page + "}";
1069 }
1070 }
1071
1072
1073 private static class NonLeaf<K,V> extends Page<K,V> {
1074 /**
1075 * The child page references.
1076 */
1077 private PageReference<K,V>[] children;
1078
1079 /**
1080 * The total entry count of this page and all children.
1081 */
1082 private long totalCount;
1083
1084 NonLeaf(MVMap<K,V> map) {
1085 super(map);
1086 }
1087
1088 NonLeaf(MVMap<K,V> map, NonLeaf<K,V> source, PageReference<K,V>[] children, long totalCount) {
1089 super(map, source);
1090 this.children = children;
1091 this.totalCount = totalCount;
1092 }
1093
1094 NonLeaf(MVMap<K,V> map, K[] keys, PageReference<K,V>[] children, long totalCount) {
1095 super(map, keys);
1096 this.children = children;
1097 this.totalCount = totalCount;
1098 }
1099
1100 @Override
1101 public int getNodeType() {
1102 return DataUtils.PAGE_TYPE_NODE;
1103 }
1104
1105 @Override
1106 public Page<K,V> copy(MVMap<K, V> map, boolean eraseChildrenRefs) {
1107 return eraseChildrenRefs ?
1108 new IncompleteNonLeaf<>(map, this) :
1109 new NonLeaf<>(map, this, children, totalCount);
1110 }
1111
1112 @Override
1113 public Page<K,V> getChildPage(int index) {
1114 PageReference<K,V> ref = children[index];
1115 Page<K,V> page = ref.getPage();
1116 if(page == null) {
1117 page = map.readPage(ref.getPos());
1118 assert ref.getPos() == page.getPos();
1119 assert ref.count == page.getTotalCount();
1120 }
1121 return page;
1122 }
1123
1124 @Override
1125 public long getChildPagePos(int index) {
1126 return children[index].getPos();
1127 }
1128
1129 @Override
1130 public V getValue(int index) {
1131 throw new UnsupportedOperationException();
1132 }
1133
1134 @Override
1135 public Page<K,V> split(int at) {
1136 assert !isSaved();
1137 int b = getKeyCount() - at;
1138 K[] bKeys = splitKeys(at, b - 1);
1139 PageReference<K,V>[] aChildren = createRefStorage(at + 1);
1140 PageReference<K,V>[] bChildren = createRefStorage(b);
1141 System.arraycopy(children, 0, aChildren, 0, at + 1);
1142 System.arraycopy(children, at + 1, bChildren, 0, b);
1143 children = aChildren;
1144
1145 long t = 0;
1146 for (PageReference<K,V> x : aChildren) {
1147 t += x.count;
1148 }
1149 totalCount = t;
1150 t = 0;
1151 for (PageReference<K,V> x : bChildren) {
1152 t += x.count;
1153 }
1154 Page<K,V> newPage = createNode(map, bKeys, bChildren, t, 0);
1155 if(isPersistent()) {
1156 recalculateMemory();
1157 }
1158 return newPage;
1159 }
1160
1161 @Override
1162 public void expand(int keyCount, Object[] extraKeys, Object[] extraValues) {
1163 throw new UnsupportedOperationException();
1164 }
1165
1166 @Override
1167 public long getTotalCount() {
1168 assert !isComplete() || totalCount == calculateTotalCount() :
1169 "Total count: " + totalCount + " != " + calculateTotalCount();
1170 return totalCount;
1171 }
1172
1173 private long calculateTotalCount() {
1174 long check = 0;
1175 int keyCount = getKeyCount();
1176 for (int i = 0; i <= keyCount; i++) {
1177 check += children[i].count;
1178 }
1179 return check;
1180 }
1181
1182 void recalculateTotalCount() {
1183 totalCount = calculateTotalCount();
1184 }
1185
1186 @Override
1187 long getCounts(int index) {
1188 return children[index].count;
1189 }
1190
1191 @Override
1192 public void setChild(int index, Page<K,V> c) {
1193 assert c != null;
1194 PageReference<K,V> child = children[index];
1195 if (c != child.getPage() || c.getPos() != child.getPos()) {
1196 totalCount += c.getTotalCount() - child.count;
1197 children = children.clone();
1198 children[index] = new PageReference<>(c);
1199 }
1200 }
1201
1202 @Override
1203 public V setValue(int index, V value) {
1204 throw new UnsupportedOperationException();
1205 }
1206
1207 @Override
1208 public void insertLeaf(int index, K key, V value) {
1209 throw new UnsupportedOperationException();
1210 }
1211
1212 @Override
1213 public void insertNode(int index, K key, Page<K,V> childPage) {
1214 int childCount = getRawChildPageCount();
1215 insertKey(index, key);
1216
1217 PageReference<K,V>[] newChildren = createRefStorage(childCount + 1);
1218 DataUtils.copyWithGap(children, newChildren, childCount, index);
1219 children = newChildren;
1220 children[index] = new PageReference<>(childPage);
1221
1222 totalCount += childPage.getTotalCount();
1223 if (isPersistent()) {
1224 addMemory(MEMORY_POINTER + PAGE_MEMORY_CHILD);
1225 }
1226 }
1227
1228 @Override
1229 public void remove(int index) {
1230 int childCount = getRawChildPageCount();
1231 super.remove(index);
1232 if(isPersistent()) {
1233 if (map.isMemoryEstimationAllowed()) {
1234 addMemory(-getMemory() / childCount);
1235 } else {
1236 addMemory(-MEMORY_POINTER - PAGE_MEMORY_CHILD);
1237 }
1238 }
1239 totalCount -= children[index].count;
1240 PageReference<K,V>[] newChildren = createRefStorage(childCount - 1);
1241 DataUtils.copyExcept(children, newChildren, childCount, index);
1242 children = newChildren;
1243 }
1244
1245 @Override
1246 public int removeAllRecursive(long version) {
1247 int unsavedMemory = removePage(version);
1248 if (isPersistent()) {
1249 for (int i = 0, size = map.getChildPageCount(this); i < size; i++) {
1250 PageReference<K,V> ref = children[i];
1251 Page<K,V> page = ref.getPage();
1252 if (page != null) {
1253 unsavedMemory += page.removeAllRecursive(version);
1254 } else {
1255 long pagePos = ref.getPos();
1256 assert DataUtils.isPageSaved(pagePos);
1257 if (DataUtils.isLeafPosition(pagePos)) {
1258 map.store.accountForRemovedPage(pagePos, version, map.isSingleWriter(), -1);
1259 } else {
1260 unsavedMemory += map.readPage(pagePos).removeAllRecursive(version);
1261 }
1262 }
1263 }
1264 }
1265 return unsavedMemory;
1266 }
1267
1268 @Override
1269 public CursorPos<K,V> getPrependCursorPos(CursorPos<K,V> cursorPos) {
1270 Page<K,V> childPage = getChildPage(0);
1271 return childPage.getPrependCursorPos(new CursorPos<>(this, 0, cursorPos));
1272 }
1273
1274 @Override
1275 public CursorPos<K,V> getAppendCursorPos(CursorPos<K,V> cursorPos) {
1276 int keyCount = getKeyCount();
1277 Page<K,V> childPage = getChildPage(keyCount);
1278 return childPage.getAppendCursorPos(new CursorPos<>(this, keyCount, cursorPos));
1279 }
1280
1281 @Override
1282 protected void readPayLoad(ByteBuffer buff) {
1283 int keyCount = getKeyCount();
1284 children = createRefStorage(keyCount + 1);
1285 long[] p = new long[keyCount + 1];
1286 for (int i = 0; i <= keyCount; i++) {
1287 p[i] = buff.getLong();
1288 }
1289 long total = 0;
1290 for (int i = 0; i <= keyCount; i++) {
1291 long s = DataUtils.readVarLong(buff);
1292 long position = p[i];
1293 assert position == 0 ? s == 0 : s >= 0;
1294 total += s;
1295 children[i] = position == 0 ?
1296 PageReference.empty() :
1297 new PageReference<>(position, s);
1298 }
1299 totalCount = total;
1300 }
1301
1302 @Override
1303 protected void writeValues(WriteBuffer buff) {}
1304
1305 @Override
1306 protected void writeChildren(WriteBuffer buff, boolean withCounts) {
1307 int keyCount = getKeyCount();
1308 for (int i = 0; i <= keyCount; i++) {
1309 buff.putLong(children[i].getPos());
1310 }
1311 if(withCounts) {
1312 for (int i = 0; i <= keyCount; i++) {
1313 buff.putVarLong(children[i].count);
1314 }
1315 }
1316 }
1317
1318 @Override
1319 void writeUnsavedRecursive(PageSerializationManager pageSerializationManager) {
1320 if (!isSaved()) {
1321 int patch = write(pageSerializationManager);
1322 writeChildrenRecursive(pageSerializationManager);
1323 WriteBuffer buff = pageSerializationManager.getBuffer();
1324 int old = buff.position();
1325 buff.position(patch);
1326 writeChildren(buff, false);
1327 buff.position(old);
1328 }
1329 }
1330
1331 void writeChildrenRecursive(PageSerializationManager pageSerializationManager) {
1332 int len = getRawChildPageCount();
1333 for (int i = 0; i < len; i++) {
1334 PageReference<K,V> ref = children[i];
1335 Page<K,V> p = ref.getPage();
1336 if (p != null) {
1337 p.writeUnsavedRecursive(pageSerializationManager);
1338 ref.resetPos();
1339 }
1340 }
1341 }
1342
1343 @Override
1344 void releaseSavedPages() {
1345 int len = getRawChildPageCount();
1346 for (int i = 0; i < len; i++) {
1347 children[i].clearPageReference();
1348 }
1349 }
1350
1351 @Override
1352 public int getRawChildPageCount() {
1353 return getKeyCount() + 1;
1354 }
1355
1356 @Override
1357 protected int calculateMemory() {
1358 return super.calculateMemory() + PAGE_NODE_MEMORY +
1359 getRawChildPageCount() * (MEMORY_POINTER + PAGE_MEMORY_CHILD);
1360 }
1361
1362 @Override
1363 public void dump(StringBuilder buff) {
1364 super.dump(buff);
1365 int keyCount = getKeyCount();
1366 for (int i = 0; i <= keyCount; i++) {
1367 if (i > 0) {
1368 buff.append(" ");
1369 }
1370 buff.append("[").append(Long.toHexString(children[i].getPos())).append("]");
1371 if(i < keyCount) {
1372 buff.append(" ").append(getKey(i));
1373 }
1374 }
1375 }
1376 }
1377
1378
1379 private static class IncompleteNonLeaf<K,V> extends NonLeaf<K,V> {
1380
1381 private boolean complete;
1382
1383 IncompleteNonLeaf(MVMap<K,V> map, NonLeaf<K,V> source) {
1384 super(map, source, constructEmptyPageRefs(source.getRawChildPageCount()), source.getTotalCount());
1385 }
1386
1387 private static <K,V> PageReference<K,V>[] constructEmptyPageRefs(int size) {
1388 // replace child pages with empty pages
1389 PageReference<K,V>[] children = createRefStorage(size);
1390 Arrays.fill(children, PageReference.empty());
1391 return children;
1392 }
1393
1394 @Override
1395 void writeUnsavedRecursive(PageSerializationManager pageSerializationManager) {
1396 if (complete) {
1397 super.writeUnsavedRecursive(pageSerializationManager);
1398 } else if (!isSaved()) {
1399 writeChildrenRecursive(pageSerializationManager);
1400 }
1401 }
1402
1403 @Override
1404 public boolean isComplete() {
1405 return complete;
1406 }
1407
1408 @Override
1409 public void setComplete() {
1410 recalculateTotalCount();
1411 complete = true;
1412 }
1413
1414 @Override
1415 public void dump(StringBuilder buff) {
1416 super.dump(buff);
1417 buff.append(", complete:").append(complete);
1418 }
1419
1420 }
1421
1422
1423
1424 private static class Leaf<K,V> extends Page<K,V> {
1425 /**
1426 * The storage for values.
1427 */
1428 private V[] values;
1429
1430 Leaf(MVMap<K,V> map) {
1431 super(map);
1432 }
1433
1434 private Leaf(MVMap<K,V> map, Leaf<K,V> source) {
1435 super(map, source);
1436 this.values = source.values;
1437 }
1438
1439 Leaf(MVMap<K,V> map, K[] keys, V[] values) {
1440 super(map, keys);
1441 this.values = values;
1442 }
1443
1444 @Override
1445 public int getNodeType() {
1446 return PAGE_TYPE_LEAF;
1447 }
1448
1449 @Override
1450 public Page<K,V> copy(MVMap<K, V> map, boolean eraseChildrenRefs) {
1451 return new Leaf<>(map, this);
1452 }
1453
1454 @Override
1455 public Page<K,V> getChildPage(int index) {
1456 throw new UnsupportedOperationException();
1457 }
1458
1459 @Override
1460 public long getChildPagePos(int index) {
1461 throw new UnsupportedOperationException();
1462 }
1463
1464 @Override
1465 public V getValue(int index) {
1466 return values == null ? null : values[index];
1467 }
1468
1469 @Override
1470 public Page<K,V> split(int at) {
1471 assert !isSaved();
1472 int b = getKeyCount() - at;
1473 K[] bKeys = splitKeys(at, b);
1474 V[] bValues = createValueStorage(b);
1475 if(values != null) {
1476 V[] aValues = createValueStorage(at);
1477 System.arraycopy(values, 0, aValues, 0, at);
1478 System.arraycopy(values, at, bValues, 0, b);
1479 values = aValues;
1480 }
1481 Page<K,V> newPage = createLeaf(map, bKeys, bValues, 0);
1482 if(isPersistent()) {
1483 recalculateMemory();
1484 }
1485 return newPage;
1486 }
1487
1488 @Override
1489 public void expand(int extraKeyCount, K[] extraKeys, V[] extraValues) {
1490 int keyCount = getKeyCount();
1491 expandKeys(extraKeyCount, extraKeys);
1492 if(values != null) {
1493 V[] newValues = createValueStorage(keyCount + extraKeyCount);
1494 System.arraycopy(values, 0, newValues, 0, keyCount);
1495 System.arraycopy(extraValues, 0, newValues, keyCount, extraKeyCount);
1496 values = newValues;
1497 }
1498 if(isPersistent()) {
1499 recalculateMemory();
1500 }
1501 }
1502
1503 @Override
1504 public long getTotalCount() {
1505 return getKeyCount();
1506 }
1507
1508 @Override
1509 long getCounts(int index) {
1510 throw new UnsupportedOperationException();
1511 }
1512
1513 @Override
1514 public void setChild(int index, Page<K,V> c) {
1515 throw new UnsupportedOperationException();
1516 }
1517
1518 @Override
1519 public V setValue(int index, V value) {
1520 values = values.clone();
1521 V old = setValueInternal(index, value);
1522 if(isPersistent()) {
1523 if (!map.isMemoryEstimationAllowed()) {
1524 addMemory(map.evaluateMemoryForValue(value) -
1525 map.evaluateMemoryForValue(old));
1526 }
1527 }
1528 return old;
1529 }
1530
1531 private V setValueInternal(int index, V value) {
1532 V old = values[index];
1533 values[index] = value;
1534 return old;
1535 }
1536
1537 @Override
1538 public void insertLeaf(int index, K key, V value) {
1539 int keyCount = getKeyCount();
1540 insertKey(index, key);
1541
1542 if(values != null) {
1543 V[] newValues = createValueStorage(keyCount + 1);
1544 DataUtils.copyWithGap(values, newValues, keyCount, index);
1545 values = newValues;
1546 setValueInternal(index, value);
1547 if (isPersistent()) {
1548 addMemory(MEMORY_POINTER + map.evaluateMemoryForValue(value));
1549 }
1550 }
1551 }
1552
1553 @Override
1554 public void insertNode(int index, K key, Page<K,V> childPage) {
1555 throw new UnsupportedOperationException();
1556 }
1557
1558 @Override
1559 public void remove(int index) {
1560 int keyCount = getKeyCount();
1561 super.remove(index);
1562 if (values != null) {
1563 if(isPersistent()) {
1564 if (map.isMemoryEstimationAllowed()) {
1565 addMemory(-getMemory() / keyCount);
1566 } else {
1567 V old = getValue(index);
1568 addMemory(-MEMORY_POINTER - map.evaluateMemoryForValue(old));
1569 }
1570 }
1571 V[] newValues = createValueStorage(keyCount - 1);
1572 DataUtils.copyExcept(values, newValues, keyCount, index);
1573 values = newValues;
1574 }
1575 }
1576
1577 @Override
1578 public int removeAllRecursive(long version) {
1579 return removePage(version);
1580 }
1581
1582 @Override
1583 public CursorPos<K,V> getPrependCursorPos(CursorPos<K,V> cursorPos) {
1584 return new CursorPos<>(this, -1, cursorPos);
1585 }
1586
1587 @Override
1588 public CursorPos<K,V> getAppendCursorPos(CursorPos<K,V> cursorPos) {
1589 int keyCount = getKeyCount();
1590 return new CursorPos<>(this, ~keyCount, cursorPos);
1591 }
1592
1593 @Override
1594 protected void readPayLoad(ByteBuffer buff) {
1595 int keyCount = getKeyCount();
1596 values = createValueStorage(keyCount);
1597 map.getValueType().read(buff, values, getKeyCount());
1598 }
1599
1600 @Override
1601 protected void writeValues(WriteBuffer buff) {
1602 map.getValueType().write(buff, values, getKeyCount());
1603 }
1604
1605 @Override
1606 protected void writeChildren(WriteBuffer buff, boolean withCounts) {}
1607
1608 @Override
1609 void writeUnsavedRecursive(PageSerializationManager pageSerializationManager) {
1610 if (!isSaved()) {
1611 write(pageSerializationManager);
1612 }
1613 }
1614
1615 @Override
1616 void releaseSavedPages() {}
1617
1618 @Override
1619 public int getRawChildPageCount() {
1620 return 0;
1621 }
1622
1623 @Override
1624 protected int calculateMemory() {
1625 //*
1626 return super.calculateMemory() + PAGE_LEAF_MEMORY +
1627 (values == null ? 0 : map.evaluateMemoryForValues(values, getKeyCount()));
1628 /*/
1629 int keyCount = getKeyCount();
1630 int mem = super.calculateMemory() + PAGE_LEAF_MEMORY + keyCount * MEMORY_POINTER;
1631 DataType<V> valueType = map.getValueType();
1632 for (int i = 0; i < keyCount; i++) {
1633 mem += getMemory(valueType, values[i]);
1634 }
1635 return mem;
1636 //*/
1637 }
1638
1639 @Override
1640 public void dump(StringBuilder buff) {
1641 super.dump(buff);
1642 int keyCount = getKeyCount();
1643 for (int i = 0; i < keyCount; i++) {
1644 if (i > 0) {
1645 buff.append(" ");
1646 }
1647 buff.append(getKey(i));
1648 if (values != null) {
1649 buff.append(':');
1650 buff.append(getValue(i));
1651 }
1652 }
1653 }
1654 }
1655 }