/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.activeblaze.wire;

/**
 * Store booleans in a byte
 */
public final class ByteBool {
    private byte data;
    private int pos = 0;

    /**
     * write a boolean value - and move the position in the byte 1 bit forward
     */
    public void writeBoolean(boolean value) {
        if (this.pos >= 8) {
            throw new RuntimeException("ByteBoolean overwrite: " + this.pos);
        }
        if (value) {
            this.data |= 0x01 << this.pos;
        }
        this.pos++;
    }

    /**
     * read a boolean value - and move the position in the byte 1 bit forward
     *
     * @return true if the bit is set
     */
    public boolean readBoolean() {
        boolean result = ((this.data >> this.pos) & 0x01) != 0;
        this.pos++;
        return result;
    }

    /**
     * @return the underlying byte
     */
    public byte getData() {
        return this.data;
    }

    /**
     * Set the byte to read
     */
    public void setData(byte v) {
        this.data = v;
    }

    /**
     * reset the position and clear the byte
     */
    public void clear() {
        this.data = 0;
        this.pos = 0;
    }

    /**
     * reset the position to the first bit
     */
    public void reset() {
        this.pos = 0;
    }
}
