| 620 | } |
| 621 | |
| 622 | auto BTreeDatabase::BTreeImpl::loadLeaf(Pointer pointer) -> Leaf { |
| 623 | auto leaf = make_shared<LeafNode>(); |
| 624 | leaf->self = pointer; |
| 625 | |
| 626 | BlockIndex currentLeafBlock = leaf->self; |
| 627 | DataStreamBuffer leafBuffer; |
| 628 | leafBuffer.reset(parent->m_blockSize); |
| 629 | parent->readBlock(currentLeafBlock, 0, leafBuffer.ptr(), parent->m_blockSize); |
| 630 | |
| 631 | if (leafBuffer.readBytes(2) != ByteArray(LeafMagic, 2)) |
| 632 | throw DBException("Error, incorrect leaf block signature."); |
| 633 | |
| 634 | DataStreamFunctions leafInput([&](char* data, size_t len) -> size_t { |
| 635 | size_t pos = 0; |
| 636 | size_t left = len; |
| 637 | |
| 638 | while (left > 0) { |
| 639 | if (leafBuffer.pos() + left < parent->m_blockSize - sizeof(BlockIndex)) { |
| 640 | leafBuffer.readData(data + pos, left); |
| 641 | pos += left; |
| 642 | left = 0; |
| 643 | } else { |
| 644 | size_t toRead = parent->m_blockSize - sizeof(BlockIndex) - leafBuffer.pos(); |
| 645 | leafBuffer.readData(data + pos, toRead); |
| 646 | pos += toRead; |
| 647 | left -= toRead; |
| 648 | } |
| 649 | |
| 650 | if (leafBuffer.pos() == (parent->m_blockSize - sizeof(BlockIndex)) && left > 0) { |
| 651 | currentLeafBlock = leafBuffer.read<BlockIndex>(); |
| 652 | if (currentLeafBlock != InvalidBlockIndex) { |
| 653 | leafBuffer.reset(parent->m_blockSize); |
| 654 | parent->readBlock(currentLeafBlock, 0, leafBuffer.ptr(), parent->m_blockSize); |
| 655 | |
| 656 | if (leafBuffer.readBytes(2) != ByteArray(LeafMagic, 2)) |
| 657 | throw DBException("Error, incorrect leaf block signature."); |
| 658 | |
| 659 | } else { |
| 660 | throw DBException("Leaf read off end of Leaf list."); |
| 661 | } |
| 662 | } |
| 663 | } |
| 664 | |
| 665 | return len; |
| 666 | }, {}); |
| 667 | |
| 668 | uint32_t count = leafInput.read<uint32_t>(); |
| 669 | leaf->elements.resize(count); |
| 670 | for (uint32_t i = 0; i < count; ++i) { |
| 671 | auto& element = leaf->elements[i]; |
| 672 | element.key = leafInput.readBytes(parent->m_keySize); |
| 673 | element.data = leafInput.read<ByteArray>(); |
| 674 | } |
| 675 | |
| 676 | return leaf; |
| 677 | } |
| 678 | |
| 679 | bool BTreeDatabase::BTreeImpl::leafNeedsShift(Leaf const& l) { |