2 * Copyright 2018-present Open Networking Foundation
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.ByteBuffer;
20 import java.nio.channels.FileChannel;
23 * Mappable log segment reader.
25 final class MappableJournalSegmentReader<E> implements JournalReader<E> {
26 private final JournalSegment<E> segment;
27 private final FileChannel channel;
28 private final int maxEntrySize;
29 private final JournalIndex index;
30 private final JournalSerdes namespace;
31 private JournalSegmentReader<E> reader;
33 MappableJournalSegmentReader(
35 JournalSegment<E> segment,
38 JournalSerdes namespace) {
39 this.channel = channel;
40 this.segment = segment;
41 this.maxEntrySize = maxEntrySize;
43 this.namespace = namespace;
44 this.reader = new FileChannelJournalSegmentReader<>(channel, segment, maxEntrySize, index, namespace);
48 * Converts the reader to a mapped reader using the given buffer.
50 * @param buffer the mapped buffer
52 void map(ByteBuffer buffer) {
53 if (!(reader instanceof MappedJournalSegmentReader)) {
54 JournalReader<E> reader = this.reader;
55 this.reader = new MappedJournalSegmentReader<>(buffer, segment, maxEntrySize, index, namespace);
56 this.reader.reset(reader.getNextIndex());
62 * Converts the reader to an unmapped reader.
65 if (reader instanceof MappedJournalSegmentReader) {
66 JournalReader<E> reader = this.reader;
67 this.reader = new FileChannelJournalSegmentReader<>(channel, segment, maxEntrySize, index, namespace);
68 this.reader.reset(reader.getNextIndex());
74 public long getFirstIndex() {
75 return reader.getFirstIndex();
79 public long getCurrentIndex() {
80 return reader.getCurrentIndex();
84 public Indexed<E> getCurrentEntry() {
85 return reader.getCurrentEntry();
89 public long getNextIndex() {
90 return reader.getNextIndex();
94 public boolean hasNext() {
95 return reader.hasNext();
99 public Indexed<E> next() {
100 return reader.next();
104 public void reset() {
109 public void reset(long index) {
114 public void close() {
116 segment.closeReader(this);