2 * Copyright 2017-2022 Open Networking Foundation and others. All rights reserved.
3 * Copyright (c) 2024 PANTHEON.tech, s.r.o.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 package io.atomix.storage.journal;
19 import java.nio.BufferUnderflowException;
20 import java.nio.ByteBuffer;
21 import java.util.zip.CRC32;
26 * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
28 final class MappedJournalSegmentReader<E> extends JournalSegmentReader<E> {
29 private final ByteBuffer buffer;
31 MappedJournalSegmentReader(
33 JournalSegment<E> segment,
35 JournalSerdes namespace) {
36 super(segment, maxEntrySize, namespace);
37 this.buffer = buffer.slice();
41 void setPosition(int position) {
42 buffer.position(position);
46 Indexed<E> readEntry(final long index) {
47 // Mark the buffer so it can be reset if necessary.
51 // Read the length of the entry.
52 final int length = buffer.getInt();
54 // If the buffer length is zero then return.
55 if (length <= 0 || length > maxEntrySize) {
60 // Read the checksum of the entry.
61 long checksum = buffer.getInt() & 0xFFFFFFFFL;
63 // Compute the checksum for the entry bytes.
64 final CRC32 crc32 = new CRC32();
65 ByteBuffer slice = buffer.slice();
69 // If the stored checksum equals the computed checksum, return the entry.
70 if (checksum == crc32.getValue()) {
72 E entry = namespace.deserialize(slice);
73 buffer.position(buffer.position() + length);
74 return new Indexed<>(index, entry, length);
79 } catch (BufferUnderflowException e) {