1 package org.apache.lucene.util;
4 * Licensed to the Apache Software Foundation (ASF) under one or more
5 * contributor license agreements. See the NOTICE file distributed with
6 * this work for additional information regarding copyright ownership.
7 * The ASF licenses this file to You under the Apache License, Version 2.0
8 * (the "License"); you may not use this file except in compliance with
9 * the License. You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
21 import java.io.IOException;
23 import org.apache.lucene.index.CorruptIndexException;
24 import org.apache.lucene.index.IndexFormatTooNewException;
25 import org.apache.lucene.index.IndexFormatTooOldException;
26 import org.apache.lucene.store.DataInput;
27 import org.apache.lucene.store.DataOutput;
30 * @lucene.experimental
33 public final class CodecUtil {
34 private CodecUtil() {} // no instance
36 private final static int CODEC_MAGIC = 0x3fd76c17;
38 public static DataOutput writeHeader(DataOutput out, String codec, int version)
40 BytesRef bytes = new BytesRef(codec);
41 if (bytes.length != codec.length() || bytes.length >= 128) {
42 throw new IllegalArgumentException("codec must be simple ASCII, less than 128 characters in length [got " + codec + "]");
44 out.writeInt(CODEC_MAGIC);
45 out.writeString(codec);
46 out.writeInt(version);
51 public static int headerLength(String codec) {
52 return 9+codec.length();
55 public static int checkHeader(DataInput in, String codec, int minVersion, int maxVersion)
58 // Safety to guard against reading a bogus string:
59 final int actualHeader = in.readInt();
60 if (actualHeader != CODEC_MAGIC) {
61 throw new CorruptIndexException("codec header mismatch: actual header=" + actualHeader + " vs expected header=" + CODEC_MAGIC + " (resource: " + in + ")");
64 final String actualCodec = in.readString();
65 if (!actualCodec.equals(codec)) {
66 throw new CorruptIndexException("codec mismatch: actual codec=" + actualCodec + " vs expected codec=" + codec + " (resource: " + in + ")");
69 final int actualVersion = in.readInt();
70 if (actualVersion < minVersion) {
71 throw new IndexFormatTooOldException(in, actualVersion, minVersion, maxVersion);
73 if (actualVersion > maxVersion) {
74 throw new IndexFormatTooNewException(in, actualVersion, minVersion, maxVersion);