2 * Copyright (c) 2024 PANTHEON.tech, s.r.o. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package io.atomix.storage.journal;
10 import static java.util.Objects.requireNonNull;
12 import io.atomix.storage.journal.index.JournalIndex;
13 import io.atomix.storage.journal.index.Position;
14 import java.util.NoSuchElementException;
15 import org.eclipse.jdt.annotation.Nullable;
17 abstract sealed class JournalSegmentReader<E> implements JournalReader<E>
18 permits FileChannelJournalSegmentReader, MappedJournalSegmentReader {
19 final int maxEntrySize;
20 private final JournalIndex index;
21 final JournalSerdes namespace;
22 private final long firstIndex;
24 private Indexed<E> currentEntry;
25 private Indexed<E> nextEntry;
27 JournalSegmentReader(final JournalSegment<E> segment, final int maxEntrySize, final JournalIndex index,
28 final JournalSerdes namespace) {
29 this.maxEntrySize = maxEntrySize;
30 this.index = requireNonNull(index);
31 this.namespace = requireNonNull(namespace);
32 firstIndex = segment.index();
36 public final long getFirstIndex() {
41 public final long getCurrentIndex() {
42 return currentEntry != null ? currentEntry.index() : 0;
46 public final Indexed<E> getCurrentEntry() {
51 public final long getNextIndex() {
52 return currentEntry != null ? currentEntry.index() + 1 : firstIndex;
56 public final boolean hasNext() {
57 return nextEntry != null || (nextEntry = readNext()) != null;
61 public final Indexed<E> next() {
63 throw new NoSuchElementException();
66 // Set the current entry to the next entry.
67 currentEntry = nextEntry;
69 // Reset the next entry to null.
72 // Read the next entry in the segment.
73 nextEntry = readNext();
75 // Return the current entry.
80 public final void reset() {
83 setPosition(JournalSegmentDescriptor.BYTES);
84 nextEntry = readNext();
88 public final void reset(final long index) {
90 Position position = this.index.lookup(index - 1);
91 if (position != null) {
92 currentEntry = new Indexed<>(position.index() - 1, null, 0);
93 setPosition(position.position());
94 nextEntry = readNext();
96 while (getNextIndex() < index && hasNext()) {
102 public final void close() {
103 // FIXME: CONTROLLER-2098: remove this method
107 * Set the file position.
109 * @param position new position
111 abstract void setPosition(int position);
114 * Reads the next entry in the segment.
116 * @return Next entry, or {@code null}
118 abstract @Nullable Indexed<E> readNext();