432f9b9dec0395385c8e930c7eae3bbd51307ab2
[controller.git] / atomix-storage / src / main / java / io / atomix / storage / journal / SegmentEntry.java
1 /*
2  * Copyright (c) 2024 PANTHEON.tech, s.r.o. and others.  All rights reserved.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 package io.atomix.storage.journal;
17
18 import java.nio.ByteBuffer;
19 import java.util.zip.CRC32;
20 import org.eclipse.jdt.annotation.NonNull;
21
22 /**
23  * An {@link Indexed} entry read from {@link JournalSegment}.
24  *
25  * @param checksum The {@link CRC32} checksum of data
26  * @param bytes Entry bytes
27  */
28 record SegmentEntry(int checksum, @NonNull ByteBuffer bytes) {
29     /**
30      * The size of the header, comprising of:
31      * <ul>
32      *   <li>32-bit signed entry length</li>
33      *   <li>32-bit unsigned CRC32 checksum</li>
34      * </li>
35      */
36     static final int HEADER_BYTES = Integer.BYTES + Integer.BYTES;
37
38     SegmentEntry {
39         if (bytes.remaining() < 1) {
40             throw new IllegalArgumentException("Invalid entry bytes " + bytes);
41         }
42     }
43
44     /**
45      * Compute the {@link CRC32} checksum of a buffer. Note that the buffer will be consumed during this process.
46      *
47      * @param bytes buffer to checksum
48      * @return the checksum
49      */
50     static int computeChecksum(final ByteBuffer bytes) {
51         final var crc32 = new CRC32();
52         crc32.update(bytes);
53         return (int) crc32.getValue();
54     }
55 }