#arithmetic on type to generate new type?

1 messages · Page 1 of 1 (latest)

young rain
#

Hi! I'm wondering if it's possible to do something like below?


// d1 would be a numeric type, d2 would be a numeric type, I want to compute the type of d3 such that
// i then want this field to be zero by default

fn Data(D1: type, D2: type) type {
  // compute D3 such that the the number of bits would be 12 - ("bits for d1" + "bits for d2")
  // D1 = u4, D2 = u4 -> D3 = u4
  // D1 = u4, D2 = u8 -> D3 = u0

  return packed struct(u12) {
    d1: D1,
    d2: D2,
    d3: D3 = 0
  }
}
drowsy mulch
#

do you want D3 length to be D3_bits = 12 - D1_bits - D2_bits?

#

it should be easily possible with @typeInfo(D1).Int.bits (or similar, can't remember the exact names) to get the number of bits, and @Type(.{ .Int = .{ .signedness = .unsigned, .bits = … }}), is the computation from the other values (again, it might not be completely correct, check the docs)

drowsy mulch
#

here's how it looks like (now that I'm in front of a computer and can check myself):

fn Data(comptime D1: type, comptime D2: type) type {
    const bits: u16 = 12 - @typeInfo(D1).Int.bits - @typeInfo(D2).Int.bits;
    const D3 = @Type(.{ .Int = .{ .signedness = .unsigned, .bits = bits } });
    return packed struct(u12) { d1: D1, d2: D2, d3: D3 = 0 };
}
gritty fiber
#

const D3 = std.meta.Int(.unsigned, bits); is a neat short-hand