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.io.IOException;
20 import java.nio.BufferUnderflowException;
21 import java.nio.ByteBuffer;
22 import java.nio.channels.FileChannel;
23 import java.util.zip.CRC32;
28 * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
30 final class DiskJournalSegmentReader<E> extends JournalSegmentReader<E> {
31 private final FileChannel channel;
32 private final ByteBuffer memory;
33 private long currentPosition;
35 DiskJournalSegmentReader(
37 JournalSegment<E> segment,
39 JournalSerdes namespace) {
40 super(segment, maxEntrySize, namespace);
41 this.channel = channel;
42 this.memory = ByteBuffer.allocate((maxEntrySize + SegmentEntry.HEADER_BYTES) * 2);
46 void setPosition(int position) {
47 currentPosition = position;
48 memory.clear().flip();
52 Indexed<E> readEntry(final long index) {
54 // Read more bytes from the segment if necessary.
55 if (memory.remaining() < maxEntrySize) {
56 long position = currentPosition + memory.position();
57 channel.read(memory.clear(), position);
58 currentPosition = position;
62 // Mark the buffer so it can be reset if necessary.
66 // Read the length of the entry.
67 final int length = memory.getInt();
69 // If the buffer length is zero then return.
70 if (length <= 0 || length > maxEntrySize) {
71 memory.reset().limit(memory.position());
75 // Read the checksum of the entry.
76 long checksum = memory.getInt() & 0xFFFFFFFFL;
78 // Compute the checksum for the entry bytes.
79 final CRC32 crc32 = new CRC32();
80 crc32.update(memory.array(), memory.position(), length);
82 // If the stored checksum equals the computed checksum, return the entry.
83 if (checksum == crc32.getValue()) {
84 int limit = memory.limit();
85 memory.limit(memory.position() + length);
86 E entry = namespace.deserialize(memory);
88 return new Indexed<>(index, entry, length);
90 memory.reset().limit(memory.position());
93 } catch (BufferUnderflowException e) {
94 memory.reset().limit(memory.position());
97 } catch (IOException e) {
98 throw new StorageException(e);