Bit field macro

Currently, making a bit field in Swift is difficult and requires the use of bitwise operations and special knowledge by the programmer. A macro could make this safer and easier.

@BitField
public struct ExampleBitField {
  @BitFieldStored(bits: 2) var i: Int
  @BitFieldStored(bits: 3) var j: Int
  @BitFieldStored(bits: 3) var n: Int
  
  // total bit size of 8
}

The macro could scan the type for each occurrence of a BitFieldStored macro, which would just expand to nothing. From there, it could use the total number of bits to determine an appropriate rawValue for the type.

// expands to:
public struct ExampleBitField {
  var _bits: UInt8

  var i: Int {
    // getter/setter code here
  }

  var j: Int {
    // code here
  }

  var n: Int {
    // code here
  }
}
2 Likes

Would an OptionSet do the job instead?

OptionSet

A type that presents a mathematical set interface to a bit set.

protocol OptionSet : RawRepresentable, SetAlgebra

Overview

You use the OptionSet protocol to represent bitset types, where individual bits represent members of a set. Adopting this protocol in your custom types lets you perform set-related operations such as membership tests, unions, and intersections on those types. What’s more, when implemented using specific criteria, adoption of this protocol requires no extra work on your part.

This would be very useful when packing/unpacking data types encoded within something like UInts. For example, the IEEE Decimal/Binary number types have multiple fields within a UInt32/64/128 word that normally require masking and shifting to pack/unpack the multi-bit fields. While this messiness is normally hidden within a Double data structure having a bit field facility would make the underlying code easier to understand and perhaps give the compiler more optimization opportunities.

2 Likes

Not entirely since this is only a bit-level encoding. It doesn't address multi-bit fields that would be mapped to integers.

2 Likes