FBoolArray.hpp 2.55 KB
Newer Older
1 2
#ifndef FBOOLARRAY_HPP
#define FBOOLARRAY_HPP
3
// [--License--]
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104

// To get memcpy
#include <cstring>

/**
* @author Berenger Bramas (berenger.bramas@inria.fr)
* @class FBoolArray
* Please read the license
*/
class FBoolArray{
    /** Size of a unsigned long */
    const static int SizeOfLong = sizeof(unsigned long);

    /** Size of the array => number of real elements */
    const int size;
    /** The array to store bits */
    unsigned long* const array;
    /** Size of the memory allocated */
    const int memSize;

    /** get size to number of long */
    int LongFromSize(const int inSize){
        const int nbLong = (inSize / (SizeOfLong * 8) );
        return nbLong + 1;
    }

    /** Alloc an array */
    unsigned long * AllocArray(const int inSize){
        return new unsigned long[LongFromSize(inSize)];
    }

public :
    /** Constructor with size */
    FBoolArray(const int inSize) : size(inSize), array(AllocArray(inSize)), memSize(LongFromSize(inSize)*SizeOfLong) {
        setToZeros();
    }

    /** Constructor form another array */
    FBoolArray(const FBoolArray& other): size(other.size), array(AllocArray(other.size)), memSize(other.memSize){
        *this = other;
    }

    /** Destructor */
    ~FBoolArray(){
        delete [] array;
    }

    /**
    * Operator =
    * Array must have the same size
    */
    FBoolArray& operator=(const FBoolArray& other){
        memcpy(array, other.array, memSize);
        return *this;
    }

    /**
    * Operator ==
    * Array must have the same size
    */
    bool operator==(const FBoolArray& other){
        return memcmp(array, other.array, memSize) == 0;
    }

    /**
    * Operator !=
    * Array must have the same size
    */
    bool operator!=(const FBoolArray& other){
        return !(*this == other);
    }

    /** To get a value */
    bool get(const int inPos) const {
        const int posInArray = inPos / (SizeOfLong*8);
        const int bytePosition = inPos - (posInArray * 8);
        return (array[posInArray] >> bytePosition) & 1;
    }

    /** To set a value */
    void set(const int inPos, const bool inVal){
        const int posInArray = inPos / (SizeOfLong*8);
        const int bytePosition = inPos - (posInArray * 8);
        if(inVal) array[posInArray] |= (1UL << bytePosition);
        else array[posInArray] &= ~(1UL << bytePosition);
    }

    /** To get the size of the array */
    int getSize() const {
        return size;
    }

    /** Set all the memory to 0 */
    void setToZeros() const {
        memset( array, 0, memSize);
    }
};


#endif //FBOOLARRAY_HPP

105
// [--END--]