[rust-dev] Defining a bitfield type

Edward Wang edward.yu.wang at gmail.com
Sat Jan 25 22:10:57 PST 2014


Hi Elliott,

Did you take a look at extra::bitv,
https://github.com/mozilla/rust/blob/master/src/libextra/bitv.rs? It does
exactly what you want.

Ed


On Sun, Jan 26, 2014 at 1:31 PM, Elliott Conant <elliottcon at gmail.com>wrote:

> Hello, this is my first post here so I wanted to say congrats on making
> such an awesome language so far!
>
> On to my question, I've been struggling to elegantly define a fixed size
> 64-bit bitfield type.  There are two parts I'm stuck on: implementing
> (just) the std::num::Bitwise operations, and extending it to iterate over
> bit indices. Here's some stuff I tried:
>
> // This gets me 90% of the way there, but it pulls in operations like add
> and multiply
> // which don't make sense in this context. This makes the interface a
> little unsafe.
> type Bits64 = u64;
>
> // This won't compile because u64 is defined externally. It looks like
> 'type X = Y'
> // just gives an alias to the original type.
> impl Bits64 {
>   fn bit_index_iter() ...
> }
> // An alternative that iterates over Bits64 directly. Would be neat but
> same problem.
> impl Iterator<u64> for Bits64 {
>   fn next(&mut self) -> Option<u64> ...
> }
>
> // Works, but doesn't looks as cool as putting it in the Bits64 impl, a
> little disappointing.
> fn bit_index_iter(b : &Bits64) ...
>
> // Some other ways the Bits64 type could be represented.  I could make
> this work if
> // I had to but the boilerplate I'd have to write scared me away.
> struct Bits64(u64);
> struct Bits64 {
>   b: u64
> }
> impl std::num::Bitwise for Bits64 { ... }
> let x = Bits64(123)
> let x = Bits64 { b: 123 }
>
>
> In my perfect world I'd be able to do something like this:
>
> // Defines the Bits64 type and exposes only the Bitwise operations from
> u64.
> type Bits64 implements std::num::Bitwise = u64;
>
> // I'd be able to extend it :)
> impl Bits64 { ... }
>
> // Easy to instantiate.
> let x : Bits64 = 123;
>
>
> I wonder if there's something simple I missed or other alternatives?
> Thanks!
>
> _______________________________________________
> Rust-dev mailing list
> Rust-dev at mozilla.org
> https://mail.mozilla.org/listinfo/rust-dev
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/rust-dev/attachments/20140126/ba48a6e3/attachment.html>


More information about the Rust-dev mailing list