BitArray Slicing

Ilya Yaroshenko via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Dec 21 03:49:06 PST 2016


On Wednesday, 21 December 2016 at 09:08:51 UTC, Ezneh wrote:
> Hi, in one of my projects I have to get a slice from a BitArray.
>
> I am trying to achieve that like this :
>
> void foo(BitArray ba)
> {
>    auto slice = ba[0..3]; // Assuming it has more than 4 
> elements
> }
>
> The problem is that I get an error :
>
> "no operator [] overload for type BitArray".
>
> Is there any other way to get a slice from a BitArray ?
>
> Thanks,
> Ezneh.

Mir allows you to define simple alternative to BitArray:

https://github.com/libmir/mir

------
struct BitMap
{
     size_t* ptr;

     import core.bitop;

     bool opIndex(size_t index) const
     {
         return bt(ptr, index) != 0;
     }

     void opIndexAssign(bool val, size_t index)
     {
         if(val)
             bts(ptr, index);
         else
             btr(ptr, index);
     }
}

import mir.ndslice;

void main()
{
     auto arr = new size_t[3];
     auto sl = BitMap(arr.ptr).sliced(size_t.sizeof * 8 * 
arr.length);

     sl[4] = true;
     sl[100] = true;
     sl.popFrontN(3);
     assert(sl[1]);
     assert(sl[97]);

     auto sl2 = sl[1...3]; // slicing
}
------


More information about the Digitalmars-d-learn mailing list