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,
042                       long min) {
043    NAME = name;
044    OFFSET = previous == null? 0: previous.OFFSET + previous.LENGTH;
045    LENGTH = length;
046    MIN = min;
047    MAX = ((-1L) >>> (64 - LENGTH));
048    MASK = MAX << OFFSET;
049  }
050
051  /** Retrieve the value from the record. */
052  public long retrieve(long record) {
053    return (record & MASK) >>> OFFSET;
054  }
055
056  /** Combine the value to the record. */
057  public long combine(long value, long record) {
058    if (value < MIN) {
059      throw new IllegalArgumentException(
060          "Illagal value: " + NAME + " = " + value + " < MIN = " + MIN);
061    }
062    if (value > MAX) {
063      throw new IllegalArgumentException(
064          "Illagal value: " + NAME + " = " + value + " > MAX = " + MAX);
065    }
066    return (record & ~MASK) | (value << OFFSET);
067  }
068
069  public long getMin() {
070    return MIN;
071  }
072}