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.io.IOException;
20 import java.nio.ByteBuffer;
21 import java.nio.channels.FileChannel;
24 * Mappable log segment reader.
26 class MappableJournalSegmentReader<E> implements JournalReader<E> {
27 private final JournalSegment<E> segment;
28 private final FileChannel channel;
29 private final int maxEntrySize;
30 private final JournalIndex index;
31 private final JournalSerdes namespace;
32 private JournalReader<E> reader;
34 MappableJournalSegmentReader(
36 JournalSegment<E> segment,
39 JournalSerdes namespace) {
40 this.channel = channel;
41 this.segment = segment;
42 this.maxEntrySize = maxEntrySize;
44 this.namespace = namespace;
45 this.reader = new FileChannelJournalSegmentReader<>(channel, segment, maxEntrySize, index, namespace);
49 * Converts the reader to a mapped reader using the given buffer.
51 * @param buffer the mapped buffer
53 void map(ByteBuffer buffer) {
54 if (!(reader instanceof MappedJournalSegmentReader)) {
55 JournalReader<E> reader = this.reader;
56 this.reader = new MappedJournalSegmentReader<>(buffer, segment, maxEntrySize, index, namespace);
57 this.reader.reset(reader.getNextIndex());
63 * Converts the reader to an unmapped reader.
66 if (reader instanceof MappedJournalSegmentReader) {
67 JournalReader<E> reader = this.reader;
68 this.reader = new FileChannelJournalSegmentReader<>(channel, segment, maxEntrySize, index, namespace);
69 this.reader.reset(reader.getNextIndex());
75 public long getFirstIndex() {
76 return reader.getFirstIndex();
80 public long getCurrentIndex() {
81 return reader.getCurrentIndex();
85 public Indexed<E> getCurrentEntry() {
86 return reader.getCurrentEntry();
90 public long getNextIndex() {
91 return reader.getNextIndex();
95 public boolean hasNext() {
96 return reader.hasNext();
100 public Indexed<E> next() {
101 return reader.next();
105 public void reset() {
110 public void reset(long index) {
115 public void close() {
119 } catch (IOException e) {
120 throw new StorageException(e);
122 segment.closeReader(this);