001/** 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package org.apache.hadoop.hdfs.util; 019 020import java.io.Serializable; 021 022 023/** 024 * Bit format in a long. 025 */ 026public class LongBitFormat implements Serializable { 027 private static final long serialVersionUID = 1L; 028 029 private final String NAME; 030 /** Bit offset */ 031 private final int OFFSET; 032 /** Bit length */ 033 private final int LENGTH; 034 /** Minimum value */ 035 private final long MIN; 036 /** Maximum value */ 037 private final long MAX; 038 /** Bit mask */ 039 private final long MASK; 040 041 public LongBitFormat(String name, LongBitFormat previous, int length, long min) { 042 NAME = name; 043 OFFSET = previous == null? 0: previous.OFFSET + previous.LENGTH; 044 LENGTH = length; 045 MIN = min; 046 MAX = ((-1L) >>> (64 - LENGTH)); 047 MASK = MAX << OFFSET; 048 } 049 050 /** Retrieve the value from the record. */ 051 public long retrieve(long record) { 052 return (record & MASK) >>> OFFSET; 053 } 054 055 /** Combine the value to the record. */ 056 public long combine(long value, long record) { 057 if (value < MIN) { 058 throw new IllegalArgumentException( 059 "Illagal value: " + NAME + " = " + value + " < MIN = " + MIN); 060 } 061 if (value > MAX) { 062 throw new IllegalArgumentException( 063 "Illagal value: " + NAME + " = " + value + " > MAX = " + MAX); 064 } 065 return (record & ~MASK) | (value << OFFSET); 066 } 067 068 public long getMin() { 069 return MIN; 070 } 071}