-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbitjuggle.zig
431 lines (355 loc) · 13.4 KB
/
bitjuggle.zig
1
2
3
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
const std = @import("std");
const assert = std.debug.assert;
const testing = std.testing;
/// Returns `true` is the the bit at index `bit` is set (equals 1).
/// Note: that index 0 is the least significant bit, while index `length() - 1` is the most significant bit.
///
/// ```zig
/// const a: u8 = 0b00000010;
///
/// try testing.expect(!isBitSet(a, 0));
/// try testing.expect(isBitSet(a, 1));
/// ```
pub fn isBitSet(target: anytype, comptime bit: comptime_int) bool {
const TargetType = @TypeOf(target);
comptime {
if (@typeInfo(TargetType) == .Int) {
if (@typeInfo(TargetType).Int.signedness != .unsigned) {
@compileError("requires an unsigned integer, found " ++ @typeName(TargetType));
}
if (bit >= @bitSizeOf(TargetType)) {
@compileError("bit index is out of bounds of the bit field");
}
} else if (@typeInfo(TargetType) == .ComptimeInt) {
if (target < 0) {
@compileError("requires an unsigned integer, found " ++ @typeName(TargetType));
}
} else {
@compileError("requires an unsigned integer, found " ++ @typeName(TargetType));
}
}
const mask: TargetType = comptime blk: {
const MaskType = std.meta.Int(.unsigned, bit + 1);
var temp: MaskType = std.math.maxInt(MaskType);
temp <<= bit;
break :blk @as(TargetType, temp);
};
return (target & mask) != 0;
}
test "isBitSet" {
const a: u8 = 0b00000000;
try testing.expect(!isBitSet(a, 0));
try testing.expect(!isBitSet(a, 1));
const b: u8 = 0b11111111;
try testing.expect(isBitSet(b, 0));
try testing.expect(isBitSet(b, 1));
const c: u8 = 0b00000010;
try testing.expect(!isBitSet(c, 0));
try testing.expect(isBitSet(c, 1));
}
test "isBitSet - comptime_int" {
const a = 0b00000000;
try testing.expect(!isBitSet(a, 0));
try testing.expect(!isBitSet(a, 1));
const b = 0b11111111;
try testing.expect(isBitSet(b, 0));
try testing.expect(isBitSet(b, 1));
const c = 0b00000010;
try testing.expect(!isBitSet(c, 0));
try testing.expect(isBitSet(c, 1));
}
/// Get the value of the bit at index `bit`.
/// Note: that index 0 is the least significant bit, while index `length() - 1` is the most significant bit.
///
/// ```zig
/// const a: u8 = 0b00000010;
///
/// try testing.expect(getBit(a, 0) == 0);
/// try testing.expect(getBit(a, 1) == 1);
/// ```
pub fn getBit(target: anytype, comptime bit: comptime_int) u1 {
return @intFromBool(isBitSet(target, bit));
}
test "getBit" {
const a: u8 = 0b00000000;
try testing.expectEqual(@as(u1, 0), getBit(a, 0));
try testing.expectEqual(@as(u1, 0), getBit(a, 1));
const b: u8 = 0b11111111;
try testing.expectEqual(@as(u1, 1), getBit(b, 0));
try testing.expectEqual(@as(u1, 1), getBit(b, 1));
const c: u8 = 0b00000010;
try testing.expectEqual(@as(u1, 0), getBit(c, 0));
try testing.expectEqual(@as(u1, 1), getBit(c, 1));
}
test "getBit - comptime_int" {
const a = 0b00000000;
try testing.expectEqual(@as(u1, 0), getBit(a, 0));
try testing.expectEqual(@as(u1, 0), getBit(a, 1));
const b = 0b11111111;
try testing.expectEqual(@as(u1, 1), getBit(b, 0));
try testing.expectEqual(@as(u1, 1), getBit(b, 1));
const c = 0b00000010;
try testing.expectEqual(@as(u1, 0), getBit(c, 0));
try testing.expectEqual(@as(u1, 1), getBit(c, 1));
}
/// Obtains the `number_of_bits` bits starting at `start_bit`
/// Where `start_bit` is the lowest significant bit to fetch
///
/// ```zig
/// const a: u8 = 0b01101100;
/// const b = getBits(a, 2, 4);
/// try testing.expectEqual(@as(u4,0b1011), b);
/// ```
pub fn getBits(target: anytype, comptime start_bit: comptime_int, comptime number_of_bits: comptime_int) std.meta.Int(.unsigned, number_of_bits) {
const TargetType = @TypeOf(target);
comptime {
if (number_of_bits == 0) @compileError("non-zero number_of_bits must be provided");
if (@typeInfo(TargetType) == .Int) {
if (@typeInfo(TargetType).Int.signedness != .unsigned) {
@compileError("requires an unsigned integer, found " ++ @typeName(TargetType));
}
if (start_bit >= @bitSizeOf(TargetType)) {
@compileError("start_bit index is out of bounds of the bit field");
}
if (start_bit + number_of_bits > @bitSizeOf(TargetType)) {
@compileError("start_bit + number_of_bits is out of bounds of the bit field");
}
} else if (@typeInfo(TargetType) == .ComptimeInt) {
if (target < 0) {
@compileError("requires an positive integer, found a negative");
}
} else {
@compileError("requires an unsigned integer, found " ++ @typeName(TargetType));
}
}
return @truncate(target >> start_bit);
}
test "getBits" {
const a: u8 = 0b01101100;
const b = getBits(a, 2, 4);
try testing.expectEqual(@as(u4, 0b1011), b);
}
test "getBits - comptime_int" {
const a = 0b01101100;
const b = getBits(a, 2, 4);
try testing.expectEqual(@as(u4, 0b1011), b);
}
/// Sets the bit at the index `bit` to the value `value` (where true means a value of '1' and false means a value of '0')
/// Note: that index 0 is the least significant bit, while index `length() - 1` is the most significant bit.
///
/// ```zig
/// var val: u8 = 0b00000000;
/// try testing.expect(!getBit(val, 0));
/// setBit( &val, 0, true);
/// try testing.expect(getBit(val, 0));
/// ```
pub fn setBit(target: anytype, comptime bit: comptime_int, value: bool) void {
const ptr_type_info: std.builtin.Type = @typeInfo(@TypeOf(target));
comptime {
if (ptr_type_info != .Pointer) @compileError("not a pointer");
}
const TargetType = ptr_type_info.Pointer.child;
comptime {
if (@typeInfo(TargetType) == .Int) {
if (@typeInfo(TargetType).Int.signedness != .unsigned) {
@compileError("requires an unsigned integer, found " ++ @typeName(TargetType));
}
if (bit >= @bitSizeOf(TargetType)) {
@compileError("bit index is out of bounds of the bit field");
}
} else if (@typeInfo(TargetType) == .ComptimeInt) {
@compileError("comptime_int is unsupported");
} else {
@compileError("requires an unsigned integer, found " ++ @typeName(TargetType));
}
}
const mask: TargetType = comptime blk: {
const MaskType = std.meta.Int(.unsigned, bit + 1);
var temp: MaskType = std.math.maxInt(MaskType);
temp <<= bit;
break :blk @as(TargetType, temp);
};
if (value) {
target.* |= mask;
} else {
target.* &= ~(mask);
}
}
test "setBit" {
var val: u8 = 0b00000000;
try testing.expect(!isBitSet(val, 0));
setBit(&val, 0, true);
try testing.expect(isBitSet(val, 0));
setBit(&val, 0, false);
try testing.expect(!isBitSet(val, 0));
}
/// Sets the range of bits starting at `start_bit` upto and excluding `start_bit` + `number_of_bits`.
/// To be specific, if the range is N bits long, the N lower bits of `value` will be used; if any of
/// the other bits in `value` are set to 1, this function will panic.
///
/// ```zig
/// var val: u8 = 0b10000000;
/// setBits(&val, 2, 4, 0b00001101);
/// try testing.expectEqual(@as(u8, 0b10110100), val);
/// ```
///
/// ## Panics
/// This method will panic if the `value` exceeds the bit range of the type of `target`
pub fn setBits(target: anytype, comptime start_bit: comptime_int, comptime number_of_bits: comptime_int, value: anytype) void {
const ptr_type_info: std.builtin.Type = @typeInfo(@TypeOf(target));
comptime {
if (ptr_type_info != .Pointer) @compileError("not a pointer");
}
const TargetType = ptr_type_info.Pointer.child;
const end_bit = start_bit + number_of_bits;
comptime {
if (number_of_bits == 0) @compileError("non-zero number_of_bits must be provided");
if (@typeInfo(TargetType) == .Int) {
if (@typeInfo(TargetType).Int.signedness != .unsigned) {
@compileError("requires an unsigned integer, found " ++ @typeName(TargetType));
}
if (start_bit >= @bitSizeOf(TargetType)) {
@compileError("start_bit index is out of bounds of the bit field");
}
if (end_bit > @bitSizeOf(TargetType)) {
@compileError("start_bit + number_of_bits is out of bounds of the bit field");
}
} else if (@typeInfo(TargetType) == .ComptimeInt) {
@compileError("comptime_int is unsupported");
} else {
@compileError("requires an unsigned integer, found " ++ @typeName(TargetType));
}
}
const peer_value = @as(TargetType, value);
if (std.debug.runtime_safety) {
if (getBits(peer_value, 0, (end_bit - start_bit)) != peer_value) @panic("value exceeds bit range");
}
const bitmask: TargetType = comptime blk: {
var bitmask = ~@as(TargetType, 0);
bitmask <<= (@bitSizeOf(TargetType) - end_bit);
bitmask >>= (@bitSizeOf(TargetType) - end_bit);
bitmask >>= start_bit;
bitmask <<= start_bit;
break :blk ~bitmask;
};
target.* = (target.* & bitmask) | (peer_value << start_bit);
}
test "setBits" {
var val: u8 = 0b10000000;
setBits(&val, 2, 4, 0b00001101);
try testing.expectEqual(@as(u8, 0b10110100), val);
}
inline fn PtrCastPreserveCV(comptime T: type, comptime PtrToT: type, comptime NewT: type) type {
return switch (PtrToT) {
*T => *NewT,
*const T => *const NewT,
*volatile T => *volatile NewT,
*const volatile T => *const volatile NewT,
else => @compileError("invalid type " ++ @typeName(PtrToT) ++ " given to PtrCastPreserveCV"),
};
}
pub fn Bitfield(comptime FieldType: type, comptime shift_amount: usize, comptime num_bits: usize) type {
if (shift_amount + num_bits > @bitSizeOf(FieldType)) {
@compileError("bitfield doesn't fit");
}
const self_mask: FieldType = ((1 << num_bits) - 1) << shift_amount;
const ValueType = std.meta.Int(.unsigned, num_bits);
return extern struct {
dummy: FieldType,
const Self = @This();
// This function uses `anytype` inorder to support both const and non-const pointers
inline fn field(self: anytype) PtrCastPreserveCV(Self, @TypeOf(self), FieldType) {
return @ptrCast(self);
}
pub fn write(self: *Self, val: ValueType) void {
self.field().* &= ~self_mask;
self.field().* |= @as(FieldType, @intCast(val)) << shift_amount;
}
pub fn read(self: Self) ValueType {
const val: FieldType = self.field().*;
return @intCast((val & self_mask) >> shift_amount);
}
};
}
test "bitfield" {
const S = extern union {
low: Bitfield(u32, 0, 16),
high: Bitfield(u32, 16, 16),
val: u32,
};
try std.testing.expect(@sizeOf(S) == 4);
try std.testing.expect(@bitSizeOf(S) == 32);
var s: S = .{ .val = 0x13376969 };
try std.testing.expect(s.low.read() == 0x6969);
try std.testing.expect(s.high.read() == 0x1337);
s.low.write(0x1337);
s.high.write(0x6969);
try std.testing.expect(s.val == 0x69691337);
}
fn BitType(comptime FieldType: type, comptime shift_amount: usize, comptime ValueType: type) type {
const self_bit: FieldType = (1 << shift_amount);
return extern struct {
bits: Bitfield(FieldType, shift_amount, 1),
const Self = @This();
fn set(self: *Self) void {
self.bits.field().* |= self_bit;
}
fn unset(self: *Self) void {
self.bits.field().* &= ~self_bit;
}
pub fn read(self: Self) ValueType {
return @bitCast(@as(u1, @truncate(self.bits.field().* >> shift_amount)));
}
// Since these are mostly used with MMIO, I want to avoid
// reading the memory just to write it again, also races
pub fn write(self: *Self, val: ValueType) void {
if (@as(bool, @bitCast(val))) {
self.set();
} else {
self.unset();
}
}
comptime {
std.testing.refAllDecls(@This());
}
};
}
pub fn Bit(comptime FieldType: type, comptime shift_amount: usize) type {
return BitType(FieldType, shift_amount, u1);
}
pub fn Boolean(comptime FieldType: type, comptime shift_amount: usize) type {
return BitType(FieldType, shift_amount, bool);
}
test "bit" {
const S = extern union {
low: Bit(u32, 0),
high: Bit(u32, 1),
val: u32,
};
try std.testing.expect(@sizeOf(S) == 4);
try std.testing.expect(@bitSizeOf(S) == 32);
var s: S = .{ .val = 1 };
try std.testing.expect(s.low.read() == 1);
try std.testing.expect(s.high.read() == 0);
s.low.write(0);
s.high.write(1);
try std.testing.expect(s.val == 2);
}
test "boolean" {
const S = extern union {
low: Boolean(u32, 0),
high: Boolean(u32, 1),
val: u32,
};
try std.testing.expect(@sizeOf(S) == 4);
try std.testing.expect(@bitSizeOf(S) == 32);
var s: S = .{ .val = 2 };
try std.testing.expect(s.low.read() == false);
try std.testing.expect(s.high.read() == true);
s.low.write(true);
s.high.write(false);
try std.testing.expect(s.val == 1);
}
comptime {
std.testing.refAllDecls(@This());
}