2 * Copyright 2017-2022 Open Networking Foundation and others. All rights reserved.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package io.atomix.storage.journal;
18 import io.atomix.storage.journal.index.JournalIndex;
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,
36 JournalSerdes namespace) {
37 super(segment, maxEntrySize, index, namespace);
38 this.buffer = buffer.slice();
43 void setPosition(int position) {
44 buffer.position(position);
48 Indexed<E> readEntry(final long index) {
49 // Mark the buffer so it can be reset if necessary.
53 // Read the length of the entry.
54 final int length = buffer.getInt();
56 // If the buffer length is zero then return.
57 if (length <= 0 || length > maxEntrySize) {
62 // Read the checksum of the entry.
63 long checksum = buffer.getInt() & 0xFFFFFFFFL;
65 // Compute the checksum for the entry bytes.
66 final CRC32 crc32 = new CRC32();
67 ByteBuffer slice = buffer.slice();
71 // If the stored checksum equals the computed checksum, return the entry.
72 if (checksum == crc32.getValue()) {
74 E entry = namespace.deserialize(slice);
75 buffer.position(buffer.position() + length);
76 return new Indexed<>(index, entry, length);
81 } catch (BufferUnderflowException e) {