001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 * 
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 * 
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.lang3;
018
019/**
020 * <p>Supports operations on bit-mapped fields. Instances of this class can be 
021 * used to store a flag or data within an {@code int}, {@code short} or 
022 * {@code byte}.</p>
023 * 
024 * <p>Each {@code BitField} is constructed with a mask value, which indicates
025 * the bits that will be used to store and retrieve the data for that field. 
026 * For instance, the mask {@code 0xFF} indicates the least-significant byte 
027 * should be used to store the data.</p>
028 * 
029 * <p>As an example, consider a car painting machine that accepts
030 * paint instructions as integers. Bit fields can be used to encode this:</p>
031 *
032 *<pre>
033 *    // blue, green and red are 1 byte values (0-255) stored in the three least 
034 *    // significant bytes
035 *    BitField blue = new BitField(0xFF);
036 *    BitField green = new BitField(0xFF00);
037 *    BitField red = new BitField(0xFF0000);
038 * 
039 *    // anyColor is a flag triggered if any color is used
040 *    BitField anyColor = new BitField(0xFFFFFF);
041 * 
042 *    // isMetallic is a single bit flag
043 *    BitField isMetallic = new BitField(0x1000000);
044 *</pre>
045 *
046 * <p>Using these {@code BitField} instances, a paint instruction can be
047 * encoded into an integer:</p>
048 *
049 *<pre>
050 *    int paintInstruction = 0;
051 *    paintInstruction = red.setValue(paintInstruction, 35);
052 *    paintInstruction = green.setValue(paintInstruction, 100);
053 *    paintInstruction = blue.setValue(paintInstruction, 255);
054 *</pre>
055 *
056 * <p>Flags and data can be retrieved from the integer:</p>
057 * 
058 *<pre>
059 *    // Prints true if red, green or blue is non-zero
060 *    System.out.println(anyColor.isSet(paintInstruction));   // prints true
061 *   
062 *    // Prints value of red, green and blue
063 *    System.out.println(red.getValue(paintInstruction));     // prints 35
064 *    System.out.println(green.getValue(paintInstruction));   // prints 100
065 *    System.out.println(blue.getValue(paintInstruction));    // prints 255
066 *   
067 *    // Prints true if isMetallic was set 
068 *    System.out.println(isMetallic.isSet(paintInstruction)); // prints false
069 *</pre>
070 *
071 * @since 2.0
072 * @version $Id: BitField.java 1592457 2014-05-05 07:05:33Z djones $
073 */
074public class BitField {
075    
076    private final int _mask;
077    private final int _shift_count;
078
079    /**
080     * <p>Creates a BitField instance.</p>
081     *
082     * @param mask the mask specifying which bits apply to this
083     *  BitField. Bits that are set in this mask are the bits
084     *  that this BitField operates on
085     */
086    public BitField(final int mask) {
087        _mask = mask;
088        int count = 0;
089        int bit_pattern = mask;
090
091        if (bit_pattern != 0) {
092            while ((bit_pattern & 1) == 0) {
093                count++;
094                bit_pattern >>= 1;
095            }
096        }
097        _shift_count = count;
098    }
099
100    /**
101     * <p>Obtains the value for the specified BitField, appropriately
102     * shifted right.</p>
103     *
104     * <p>Many users of a BitField will want to treat the specified
105     * bits as an int value, and will not want to be aware that the
106     * value is stored as a BitField (and so shifted left so many
107     * bits).</p>
108     *
109     * @see #setValue(int,int)
110     * @param holder the int data containing the bits we're interested
111     *  in
112     * @return the selected bits, shifted right appropriately
113     */
114    public int getValue(final int holder) {
115        return getRawValue(holder) >> _shift_count;
116    }
117
118    /**
119     * <p>Obtains the value for the specified BitField, appropriately
120     * shifted right, as a short.</p>
121     *
122     * <p>Many users of a BitField will want to treat the specified
123     * bits as an int value, and will not want to be aware that the
124     * value is stored as a BitField (and so shifted left so many
125     * bits).</p>
126     *
127     * @see #setShortValue(short,short)
128     * @param holder the short data containing the bits we're
129     *  interested in
130     * @return the selected bits, shifted right appropriately
131     */
132    public short getShortValue(final short holder) {
133        return (short) getValue(holder);
134    }
135
136    /**
137     * <p>Obtains the value for the specified BitField, unshifted.</p>
138     *
139     * @param holder the int data containing the bits we're
140     *  interested in
141     * @return the selected bits
142     */
143    public int getRawValue(final int holder) {
144        return holder & _mask;
145    }
146
147    /**
148     * <p>Obtains the value for the specified BitField, unshifted.</p>
149     *
150     * @param holder the short data containing the bits we're
151     *  interested in
152     * @return the selected bits
153     */
154    public short getShortRawValue(final short holder) {
155        return (short) getRawValue(holder);
156    }
157
158    /**
159     * <p>Returns whether the field is set or not.</p>
160     *
161     * <p>This is most commonly used for a single-bit field, which is
162     * often used to represent a boolean value; the results of using
163     * it for a multi-bit field is to determine whether *any* of its
164     * bits are set.</p>
165     *
166     * @param holder the int data containing the bits we're interested
167     *  in
168     * @return {@code true} if any of the bits are set,
169     *  else {@code false}
170     */
171    public boolean isSet(final int holder) {
172        return (holder & _mask) != 0;
173    }
174
175    /**
176     * <p>Returns whether all of the bits are set or not.</p>
177     *
178     * <p>This is a stricter test than {@link #isSet(int)},
179     * in that all of the bits in a multi-bit set must be set
180     * for this method to return {@code true}.</p>
181     *
182     * @param holder the int data containing the bits we're
183     *  interested in
184     * @return {@code true} if all of the bits are set,
185     *  else {@code false}
186     */
187    public boolean isAllSet(final int holder) {
188        return (holder & _mask) == _mask;
189    }
190
191    /**
192     * <p>Replaces the bits with new values.</p>
193     *
194     * @see #getValue(int)
195     * @param holder the int data containing the bits we're
196     *  interested in
197     * @param value the new value for the specified bits
198     * @return the value of holder with the bits from the value
199     *  parameter replacing the old bits
200     */
201    public int setValue(final int holder, final int value) {
202        return (holder & ~_mask) | ((value << _shift_count) & _mask);
203    }
204
205    /**
206     * <p>Replaces the bits with new values.</p>
207     *
208     * @see #getShortValue(short)
209     * @param holder the short data containing the bits we're
210     *  interested in
211     * @param value the new value for the specified bits
212     * @return the value of holder with the bits from the value
213     *  parameter replacing the old bits
214     */
215    public short setShortValue(final short holder, final short value) {
216        return (short) setValue(holder, value);
217    }
218
219    /**
220     * <p>Clears the bits.</p>
221     *
222     * @param holder the int data containing the bits we're
223     *  interested in
224     * @return the value of holder with the specified bits cleared
225     *  (set to {@code 0})
226     */
227    public int clear(final int holder) {
228        return holder & ~_mask;
229    }
230
231    /**
232     * <p>Clears the bits.</p>
233     *
234     * @param holder the short data containing the bits we're
235     *  interested in
236     * @return the value of holder with the specified bits cleared
237     *  (set to {@code 0})
238     */
239    public short clearShort(final short holder) {
240        return (short) clear(holder);
241    }
242
243    /**
244     * <p>Clears the bits.</p>
245     *
246     * @param holder the byte data containing the bits we're
247     *  interested in
248     *
249     * @return the value of holder with the specified bits cleared
250     *  (set to {@code 0})
251     */
252    public byte clearByte(final byte holder) {
253        return (byte) clear(holder);
254    }
255
256    /**
257     * <p>Sets the bits.</p>
258     *
259     * @param holder the int data containing the bits we're
260     *  interested in
261     * @return the value of holder with the specified bits set
262     *  to {@code 1}
263     */
264    public int set(final int holder) {
265        return holder | _mask;
266    }
267
268    /**
269     * <p>Sets the bits.</p>
270     *
271     * @param holder the short data containing the bits we're
272     *  interested in
273     * @return the value of holder with the specified bits set
274     *  to {@code 1}
275     */
276    public short setShort(final short holder) {
277        return (short) set(holder);
278    }
279
280    /**
281     * <p>Sets the bits.</p>
282     *
283     * @param holder the byte data containing the bits we're
284     *  interested in
285     *
286     * @return the value of holder with the specified bits set
287     *  to {@code 1}
288     */
289    public byte setByte(final byte holder) {
290        return (byte) set(holder);
291    }
292
293    /**
294     * <p>Sets a boolean BitField.</p>
295     *
296     * @param holder the int data containing the bits we're
297     *  interested in
298     * @param flag indicating whether to set or clear the bits
299     * @return the value of holder with the specified bits set or
300     *         cleared
301     */
302    public int setBoolean(final int holder, final boolean flag) {
303        return flag ? set(holder) : clear(holder);
304    }
305
306    /**
307     * <p>Sets a boolean BitField.</p>
308     *
309     * @param holder the short data containing the bits we're
310     *  interested in
311     * @param flag indicating whether to set or clear the bits
312     * @return the value of holder with the specified bits set or
313     *  cleared
314     */
315    public short setShortBoolean(final short holder, final boolean flag) {
316        return flag ? setShort(holder) : clearShort(holder);
317    }
318
319    /**
320     * <p>Sets a boolean BitField.</p>
321     *
322     * @param holder the byte data containing the bits we're
323     *  interested in
324     * @param flag indicating whether to set or clear the bits
325     * @return the value of holder with the specified bits set or
326     *  cleared
327     */
328    public byte setByteBoolean(final byte holder, final boolean flag) {
329        return flag ? setByte(holder) : clearByte(holder);
330    }
331
332}