code
stringlengths 38
801k
| repo_path
stringlengths 6
263
|
---|---|
const std = @import("std");
const ascii = std.ascii;
const math = std.math;
const mem = std.mem;
const os = std.os;
const sort = std.sort;
const wordlist = @import("words.zig").wordlist;
const max_word_length = @import("words.zig").max_word_length;
pub const Error = error{
// Expected even sized slice, got an odd one
OddSize,
// Word not in words list
WordNotFound,
// Size is greater than maxmimum allowed
SizeTooLarge,
// Size is smaller than minimum allowed
SizeTooSmall,
} || mem.Allocator.Error;
// most recent not found word for error reporting
var word_not_found: ?[]const u8 = null;
pub const min_password_size = 2;
pub const max_password_size = 1024;
/// Returns the most recent not found word.
pub fn getWordNotFound() ?[]const u8 {
return word_not_found;
}
/// Compute the space needed to convert bytes into a passphrase.
pub fn passphraseSize(bytes: []const u8) !usize {
if (bytes.len < min_password_size) {
return error.SizeTooSmall;
} else if (bytes.len > max_password_size) {
return error.SizeTooBig;
} else if (bytes.len % 2 != 0) {
return error.OddSize;
}
// this cannot error, because we already check if the size is even
var size: usize = 0;
var i: usize = 0;
while (i < bytes.len) : (i += 2) {
const word_idx = mem.readInt(
u16,
&[_]u8{ bytes[i + 0], bytes[i + 1] },
.Big,
);
size += wordlist[word_idx].len;
}
return size;
}
/// Converts a byte array into a passphrase. Use [passphraseSize] to compute an appropriate buffer size.
pub fn bytesToPassphrase(out: []u8, bytes: []const u8) !void {
var writer = std.io.fixedBufferStream(out).writer();
var i: usize = 0;
while (i < bytes.len) : (i += 2) {
const word_idx = mem.readInt(
u16,
&[_]u8{ bytes[i + 0], bytes[i + 1] },
.Big,
);
try writer.writeAll(wordlist[word_idx]);
// only append a space if we are not at the last iteration
if (i != bytes.len - 2) {
try writer.writeByte(' ');
}
}
}
/// Converts a byte array into a passphrase.
pub fn bytesToPassphraseAlloc(ally: *mem.Allocator, bytes: []const u8) ![][]const u8 {
if (bytes.len < min_password_size) {
return error.SizeTooSmall;
} else if (bytes.len > max_password_size) {
return error.SizeTooLarge;
} else if (bytes.len % 2 != 0) {
return error.OddSize;
}
// division is safe, because it's always even
var res = try std.ArrayList([]const u8).initCapacity(ally, bytes.len / 2);
errdefer res.deinit();
var i: usize = 0;
while (i < bytes.len) : (i += 2) {
const word_idx = mem.readInt(
u16,
&[_]u8{ bytes[i + 0], bytes[i + 1] },
.Big,
);
res.appendAssumeCapacity(wordlist[word_idx]);
}
return res.toOwnedSlice();
}
/// Compute the space needed to convert a passphrase into bytes.
pub fn bytesSize(passphrase: []const []const u8) usize {
return passphrase.len * 2;
}
/// Converts a passphrase back into the original byte array. Use [bytesSize] to compute an appropriate buffer size.
pub fn passphraseToBytes(out: []u8, passphrase: []const []const u8) !void {
if (out.len != passphrase.len * 2) {
return error.WrongSize;
}
var writer = std.io.fixedBufferStream(out).writer();
for (passphrase) |word| {
// checks if the word is longer than any known word
if (word.len > max_word_length) {
word_not_found = word;
return error.WordNotFound;
}
const word_idx = sort.binarySearch(
[]const u8,
word,
&wordlist,
{},
struct {
fn compare(context: void, a: []const u8, b: []const u8) math.Order {
_ = context;
return ascii.orderIgnoreCase(a, b);
}
}.compare,
) orelse {
word_not_found = word;
return error.WordNotFound;
};
try writer.writeIntBig(u16, @intCast(u16, word_idx));
}
}
/// Converts a passphrase back into the original byte array.
pub fn passphraseToBytesAlloc(ally: *mem.Allocator, passphrase: []const []const u8) ![]u8 {
var bytes = try ally.alloc(u8, passphrase.len * 2);
errdefer ally.free(bytes);
try passphraseToBytes(bytes, passphrase);
return bytes;
}
/// Generates a passphrase with the specified number of bytes.
pub fn generatePassphraseAlloc(ally: *mem.Allocator, size: u11) ![][]const u8 {
// fills an array of bytes using system random (normally, this is cryptographically secure)
var random_bytes = try ally.alloc(u8, size);
errdefer ally.free(random_bytes);
try os.getrandom(random_bytes);
return bytesToPassphraseAlloc(ally, random_bytes);
} | src/niceware.zig |
const std = @import("std");
const assert = std.debug.assert;
const allocator = std.testing.allocator;
pub const Board = struct {
const SIZE: usize = 5;
const Pos = struct {
l: isize,
x: usize,
y: usize,
pub fn init(l: isize, x: usize, y: usize) Pos {
var self = Pos{
.l = l,
.x = x,
.y = y,
};
return self;
}
};
recursive: bool,
cells: [2]std.AutoHashMap(Pos, Tile),
cc: usize,
cy: usize,
lmin: isize,
lmax: isize,
pub const Tile = enum(u8) {
Empty = 0,
Bug = 1,
};
pub fn init(recursive: bool) Board {
var self = Board{
.recursive = recursive,
.cells = undefined,
.cc = 0,
.cy = 0,
.lmin = 0,
.lmax = 0,
};
self.cells[0] = std.AutoHashMap(Pos, Tile).init(allocator);
self.cells[1] = std.AutoHashMap(Pos, Tile).init(allocator);
return self;
}
pub fn deinit(self: *Board) void {
self.cells[1].deinit();
self.cells[0].deinit();
}
pub fn put_cell(self: *Board, c: usize, l: isize, x: usize, y: usize, t: Tile) void {
if (t != Tile.Bug) return;
const p = Pos.init(l, x, y);
_ = self.cells[c].put(p, t) catch unreachable;
if (self.lmin > l) self.lmin = l;
if (self.lmax < l) self.lmax = l;
}
pub fn get_cell(self: Board, c: usize, l: isize, x: usize, y: usize) Tile {
const p = Pos.init(l, x, y);
if (!self.cells[c].contains(p)) return Tile.Empty;
return self.cells[c].get(p).?;
}
pub fn add_lines(self: *Board, lines: []const u8) void {
var it = std.mem.split(u8, lines, "\n");
while (it.next()) |line| {
self.add_line(line);
}
}
pub fn add_line(self: *Board, line: []const u8) void {
var x: usize = 0;
while (x < line.len) : (x += 1) {
var t: Tile = Tile.Empty;
if (line[x] == '#') t = Tile.Bug;
self.put_cell(0, 0, x, self.cy, t);
}
self.cy += 1;
}
pub fn check_bug(self: Board, c: usize, l: isize, x: usize, y: usize) usize {
if (self.get_cell(c, l, x, y) == Tile.Bug) return 1;
return 0;
}
pub fn bugs_in_neighbours(self: *Board, l: isize, x: usize, y: usize) usize {
const u = l - 1;
const d = l + 1;
var bugs: usize = 0;
// NORTH
if (y == 0) {
if (self.recursive) {
bugs += self.check_bug(self.cc, u, 2, 1);
}
} else if (self.recursive and y == 3 and x == 2) {
var k: usize = 0;
while (k < SIZE) : (k += 1) {
bugs += self.check_bug(self.cc, d, k, SIZE - 1);
}
} else {
bugs += self.check_bug(self.cc, l, x, y - 1);
}
// SOUTH
if (y == SIZE - 1) {
if (self.recursive) {
bugs += self.check_bug(self.cc, u, 2, 3);
}
} else if (self.recursive and y == 1 and x == 2) {
var k: usize = 0;
while (k < SIZE) : (k += 1) {
bugs += self.check_bug(self.cc, d, k, 0);
}
} else {
bugs += self.check_bug(self.cc, l, x, y + 1);
}
// WEST
if (x == 0) {
if (self.recursive) {
bugs += self.check_bug(self.cc, u, 1, 2);
}
} else if (self.recursive and x == 3 and y == 2) {
var k: usize = 0;
while (k < SIZE) : (k += 1) {
bugs += self.check_bug(self.cc, d, SIZE - 1, k);
}
} else {
bugs += self.check_bug(self.cc, l, x - 1, y);
}
// EAST
if (x == SIZE - 1) {
if (self.recursive) {
bugs += self.check_bug(self.cc, u, 3, 2);
}
} else if (self.recursive and x == 1 and y == 2) {
var k: usize = 0;
while (k < SIZE) : (k += 1) {
bugs += self.check_bug(self.cc, d, 0, k);
}
} else {
bugs += self.check_bug(self.cc, l, x + 1, y);
}
return bugs;
}
pub fn step(self: *Board) void {
const nc = 1 - self.cc;
self.cells[nc].clearRetainingCapacity();
const lmin = self.lmin - 1;
const lmax = self.lmax + 1;
var l: isize = lmin;
while (l <= lmax) : (l += 1) {
var y: usize = 0;
while (y < SIZE) : (y += 1) {
var x: usize = 0;
while (x < SIZE) : (x += 1) {
if (self.recursive and x == 2 and y == 2) continue;
const t = self.get_cell(self.cc, l, x, y);
var n: Tile = t;
const bugs = self.bugs_in_neighbours(l, x, y);
// std.debug.warn("Bugs for {} {} {} ({}) = {}\n", l, x, y, t, bugs);
switch (t) {
.Bug => {
if (bugs != 1) n = Tile.Empty;
},
.Empty => {
if (bugs == 1 or bugs == 2) n = Tile.Bug;
},
}
self.put_cell(nc, l, x, y, n);
}
}
}
self.cc = nc;
}
pub fn run_until_repeated(self: *Board) usize {
var seen = std.AutoHashMap(usize, void).init(allocator);
defer seen.deinit();
var count: usize = 0;
while (true) : (count += 1) {
self.step();
// self.show();
const c = self.encode();
if (seen.contains(c)) break;
_ = seen.put(c, {}) catch unreachable;
}
return count;
}
pub fn run_for_N_steps(self: *Board, n: usize) void {
var count: usize = 0;
while (count < n) : (count += 1) {
self.step();
// self.show();
}
}
pub fn encode(self: Board) usize {
var code: usize = 0;
var mask: usize = 1;
var y: usize = 0;
while (y < SIZE) : (y += 1) {
var x: usize = 0;
while (x < SIZE) : (x += 1) {
const t = self.get_cell(self.cc, 0, x, y);
if (t == Tile.Bug) {
code |= mask;
}
mask <<= 1;
}
}
return code;
}
pub fn count_bugs(self: Board) usize {
var count: usize = 0;
var l: isize = self.lmin;
while (l <= self.lmax) : (l += 1) {
var y: usize = 0;
while (y < SIZE) : (y += 1) {
var x: usize = 0;
while (x < SIZE) : (x += 1) {
const t = self.get_cell(self.cc, l, x, y);
if (t == Tile.Bug) count += 1;
}
}
}
return count;
}
pub fn show(self: Board) void {
std.debug.warn("BOARD {} x {}, levels {} - {}\n", SIZE, SIZE, self.lmin, self.lmax);
var l: isize = self.lmin;
while (l <= self.lmax) : (l += 1) {
std.debug.warn("LEVEL {}\n", l);
var y: usize = 0;
while (y < SIZE) : (y += 1) {
var x: usize = 0;
std.debug.warn("{:4} | ", y);
while (x < SIZE) : (x += 1) {
const t = self.get_cell(self.cc, l, x, y);
var c: u8 = ' ';
switch (t) {
.Empty => c = '.',
.Bug => c = '#',
}
if (x == 2 and y == 2) c = '?';
std.debug.warn("{c}", c);
}
std.debug.warn("|\n");
}
}
}
};
test "non-recursive simple" {
const data: []const u8 =
\\....#
\\#..#.
\\#..##
\\..#..
\\#....
;
const expected: []const u8 =
\\####.
\\....#
\\##..#
\\.....
\\##...
;
var board = Board.init(false);
defer board.deinit();
board.add_lines(data);
const steps: usize = 4;
board.run_for_N_steps(steps);
var y: usize = 0;
var it = std.mem.split(u8, expected, "\n");
while (it.next()) |line| : (y += 1) {
var x: usize = 0;
while (x < Board.SIZE) : (x += 1) {
const t = board.get_cell(board.cc, 0, x, y);
var c: u8 = '.';
if (t == Board.Tile.Bug) c = '#';
assert(line[x] == c);
}
}
}
test "non-recursive run until repeated" {
const data: []const u8 =
\\....#
\\#..#.
\\#..##
\\..#..
\\#....
;
const expected: []const u8 =
\\.....
\\.....
\\.....
\\#....
\\.#...
;
var board = Board.init(false);
defer board.deinit();
board.add_lines(data);
const count = board.run_until_repeated();
assert(count == 85);
var y: usize = 0;
var it = std.mem.split(u8, expected, "\n");
while (it.next()) |line| : (y += 1) {
var x: usize = 0;
while (x < Board.SIZE) : (x += 1) {
const t = board.get_cell(board.cc, 0, x, y);
var c: u8 = '.';
if (t == Board.Tile.Bug) c = '#';
assert(line[x] == c);
}
}
}
test "recursive run for N steps" {
const data: []const u8 =
\\....#
\\#..#.
\\#..##
\\..#..
\\#....
;
var board = Board.init(true);
defer board.deinit();
board.add_lines(data);
const steps: usize = 10;
board.run_for_N_steps(steps);
const count = board.count_bugs();
assert(count == 99);
} | 2019/p24/board.zig |
const std = @import("std");
const assert = std.debug.assert;
const tools = @import("tools");
const Vec2 = tools.Vec2;
pub fn run(input_text: []const u8, allocator: std.mem.Allocator) ![2][]const u8 {
const param: struct {
stride: usize,
width: usize,
height: usize,
map: []const u8,
} = blk: {
const width = std.mem.indexOfScalar(u8, input_text, '\n').?;
const stride = width + 2 + 1;
const height = (input_text.len + 1) / (width + 1);
const input = try allocator.alloc(u8, (height + 2) * stride);
errdefer allocator.free(input);
std.mem.set(u8, input[0 .. width + 2], '.');
std.mem.set(u8, input[(height + 1) * stride .. ((height + 1) * stride) + width + 2], '.');
input[width + 2] = '\n';
input[((height + 1) * stride) + width + 2] = '\n';
var y: usize = 1;
var it = std.mem.tokenize(u8, input_text, "\n\r");
while (it.next()) |line| {
std.mem.copy(u8, input[y * stride + 1 .. y * stride + 1 + width], line[0..width]);
input[y * stride + 0] = '.';
input[y * stride + width + 1] = '.';
input[y * stride + width + 2] = '\n';
y += 1;
}
// std.debug.print("{}\n", .{input});
break :blk .{
.stride = stride,
.width = width,
.height = height,
.map = input,
};
};
defer allocator.free(param.map);
const ans1 = ans: {
const buf1 = try allocator.dupe(u8, param.map);
defer allocator.free(buf1);
const buf2 = try allocator.dupe(u8, param.map);
defer allocator.free(buf2);
const bufs = [2][]u8{ buf1, buf2 };
var curbuf: u32 = 0;
var prev_count: u32 = 0;
while (true) {
const prev = bufs[curbuf];
const next = bufs[1 - curbuf];
var next_count: u32 = 0;
var p = Vec2{ .x = 1, .y = 1 };
while (p.y <= param.height) : (p.y += 1) {
p.x = 1;
while (p.x <= param.width) : (p.x += 1) {
const nb_neihb = blk: {
var count: u32 = 0;
const neighbours = [_]Vec2{
.{ .x = -1, .y = -1 }, .{ .x = -1, .y = 0 }, .{ .x = -1, .y = 1 },
.{ .x = 0, .y = -1 }, .{ .x = 0, .y = 1 }, .{ .x = 1, .y = -1 },
.{ .x = 1, .y = 0 }, .{ .x = 1, .y = 1 },
};
inline for (neighbours) |o| {
const n = p.add(o);
if (prev[@intCast(usize, n.y) * param.stride + @intCast(usize, n.x)] == '#')
count += 1;
}
break :blk count;
};
const curseat = prev[@intCast(usize, p.y) * param.stride + @intCast(usize, p.x)];
const nextseat = &next[@intCast(usize, p.y) * param.stride + @intCast(usize, p.x)];
if (curseat == 'L' and nb_neihb == 0) {
nextseat.* = '#';
} else if (curseat == '#' and nb_neihb >= 4) {
nextseat.* = 'L';
} else {
nextseat.* = curseat;
}
if (nextseat.* == '#') next_count += 1;
}
}
// std.debug.print("seats={}:\n{}\n", .{ next_count, next });
if (prev_count == next_count) break :ans next_count;
prev_count = next_count;
curbuf = 1 - curbuf;
}
unreachable;
};
const ans2 = ans: {
const buf1 = try allocator.dupe(u8, param.map);
defer allocator.free(buf1);
const buf2 = try allocator.dupe(u8, param.map);
defer allocator.free(buf2);
const bufs = [2][]u8{ buf1, buf2 };
var curbuf: u32 = 0;
var prev_count: u32 = 0;
while (true) {
const prev = bufs[curbuf];
const next = bufs[1 - curbuf];
var next_count: u32 = 0;
var p = Vec2{ .x = 1, .y = 1 };
while (p.y <= param.height) : (p.y += 1) {
p.x = 1;
while (p.x <= param.width) : (p.x += 1) {
const nb_neihb = blk: {
const neighbours = [_]Vec2{
.{ .x = -1, .y = -1 }, .{ .x = -1, .y = 0 }, .{ .x = -1, .y = 1 },
.{ .x = 0, .y = -1 }, .{ .x = 0, .y = 1 }, .{ .x = 1, .y = -1 },
.{ .x = 1, .y = 0 }, .{ .x = 1, .y = 1 },
};
var d: i32 = 0;
var count: u32 = 0;
var done: std.meta.Vector(8, u1) = [1]u1{0} ** 8;
while (@reduce(.And, done) == 0) {
d += 1;
inline for (neighbours) |o, i| {
const n = p.add(Vec2{ .x = o.x * d, .y = o.y * d });
if (n.x < 1 or n.y < 1 or n.x > param.width or n.y > param.height) {
done[i] = 1;
} else if (done[i] != 0) {
const seat = prev[@intCast(usize, n.y) * param.stride + @intCast(usize, n.x)];
if (seat == '#') {
count += 1;
done[i] = 1;
} else if (seat == 'L') {
done[i] = 1;
}
}
}
}
break :blk count;
};
const idx = @intCast(usize, p.y) * param.stride + @intCast(usize, p.x);
const curseat = prev[idx];
const nextseat = &next[idx];
if (curseat == 'L' and nb_neihb == 0) {
nextseat.* = '#';
} else if (curseat == '#' and nb_neihb >= 5) {
nextseat.* = 'L';
} else {
nextseat.* = curseat;
}
if (nextseat.* == '#') next_count += 1;
//if (curbuf == 1 and nextseat.* != '.') nextseat.* = '0' + @intCast(u8, count);
}
}
//std.debug.print("seats={}:\n{}\n", .{ next_count, next });
if (prev_count == next_count) break :ans next_count;
prev_count = next_count;
curbuf = 1 - curbuf;
}
unreachable;
};
return [_][]const u8{
try std.fmt.allocPrint(allocator, "{}", .{ans1}),
try std.fmt.allocPrint(allocator, "{}", .{ans2}),
};
}
pub const main = tools.defaultMain("2020/input_day11.txt", run); | 2020/day11.zig |
const std = @import("std");
const tools_v1 = @import("tools.zig");
const assert = std.debug.assert;
const print = std.debug.print;
pub const tracy = @import("tracy.zig");
pub const RunError = tools_v1.RunError;
pub const defaultMain = tools_v1.defaultMain;
pub const BestFirstSearch = tools_v1.BestFirstSearch;
pub const ModArith = tools_v1.ModArith;
pub const generate_permutations = tools_v1.generate_permutations;
pub const generate_unique_permutations = tools_v1.generate_unique_permutations;
pub const match_pattern_hexa = tools_v1.match_pattern_hexa;
pub const match_pattern = tools_v1.match_pattern;
pub const nameToEnum = tools_v1.nameToEnum;
pub const IntCode_Computer = tools_v1.IntCode_Computer;
// -----------------------------------------------------------
// ----- 2d Map
// -----------------------------------------------------------
pub const Vec2 = @Vector(2, i32);
pub const Vec = struct {
pub fn clamp(v: Vec2, mini: Vec2, maxi: Vec2) Vec2 {
return @minimum(@maximum(v, mini), maxi);
}
pub fn min(a: Vec2, b: Vec2) Vec2 {
return @minimum(a, b);
}
pub fn max(a: Vec2, b: Vec2) Vec2 {
return @maximum(a, b);
}
pub fn dist(a: Vec2, b: Vec2) u32 {
return @reduce(.Add, std.math.absInt(a - b) catch unreachable);
}
pub fn scale(a: i32, v: Vec2) Vec2 {
return v * @splat(2, a);
}
pub const Rot = enum { none, cw, ccw };
pub fn rotate(vec: Vec2, rot: Rot) Vec2 {
const v = vec; // copy to avoid return value alias
return switch (rot) {
.none => return v,
.cw => Vec2{ -v[1], v[0] },
.ccw => Vec2{ v[1], -v[0] },
};
}
pub fn lessThan(_: void, lhs: Vec2, rhs: Vec2) bool {
if (lhs[1] < rhs[1]) return true;
if (lhs[1] == rhs[1] and lhs[0] < rhs[0]) return true;
return false;
}
pub fn eq(lhs: Vec2, rhs: Vec2) bool {
return @reduce(.And, lhs == rhs);
}
pub const cardinal4_dirs = [_]Vec2{
Vec2{ 0, -1 }, // N
Vec2{ -1, 0 }, // W
Vec2{ 1, 0 }, // E
Vec2{ 0, 1 }, // S
};
pub const cardinal8_dirs = [_]Vec2{
Vec2{ 0, -1 }, // N
Vec2{ -1, -1 },
Vec2{ -1, 0 }, // W
Vec2{ -1, 1 },
Vec2{ 0, 1 }, // S
Vec2{ 1, 1 },
Vec2{ 1, 0 }, // E
Vec2{ 1, -1 },
};
pub const Transfo = enum { r0, r90, r180, r270, r0_flip, r90_flip, r180_flip, r270_flip };
pub const all_tranfos = [_]Transfo{ .r0, .r90, .r180, .r270, .r0_flip, .r90_flip, .r180_flip, .r270_flip };
pub fn referential(t: Transfo) struct { x: Vec2, y: Vec2 } {
return switch (t) {
.r0 => .{ .x = Vec2{ 1, 0 }, .y = Vec2{ 0, 1 } },
.r90 => .{ .x = Vec2{ 0, 1 }, .y = Vec2{ -1, 0 } },
.r180 => .{ .x = Vec2{ -1, 0 }, .y = Vec2{ 0, -1 } },
.r270 => .{ .x = Vec2{ 0, -1 }, .y = Vec2{ 1, 0 } },
.r0_flip => .{ .x = Vec2{ -1, 0 }, .y = Vec2{ 0, 1 } },
.r90_flip => .{ .x = Vec2{ 0, 1 }, .y = Vec2{ 1, 0 } },
.r180_flip => .{ .x = Vec2{ 1, 0 }, .y = Vec2{ 0, -1 } },
.r270_flip => .{ .x = Vec2{ 0, -1 }, .y = Vec2{ -1, 0 } },
};
}
};
pub fn spiralIndexFromPos(p: Vec2) u32 {
// https://stackoverflow.com/questions/9970134/get-spiral-index-from-location
const x = p[0];
const y = p[1];
if (y * y >= x * x) {
var i = 4 * y * y - y - x;
if (y < x)
i -= 2 * (y - x);
return @intCast(u32, i);
} else {
var i = 4 * x * x - y - x;
if (y < x)
i += 2 * (y - x);
return @intCast(u32, i);
}
}
fn sqrtRound(v: usize) usize {
// todo: cf std.math.sqrt(idx)
return @floatToInt(usize, @round(std.math.sqrt(@intToFloat(f64, v))));
}
pub fn posFromSpiralIndex(idx: usize) Vec2 {
const i = @intCast(i32, idx);
const j = @intCast(i32, sqrtRound(idx));
const k = (std.math.absInt(j * j - i) catch unreachable) - j;
const parity: i32 = @mod(j, 2); // 0 ou 1
const sign: i32 = if (parity == 0) 1 else -1;
return Vec2{
sign * @divFloor(k + j * j - i - parity, 2),
sign * @divFloor(-k + j * j - i - parity, 2),
};
}
pub const BBox = struct {
min: Vec2,
max: Vec2,
pub fn includes(bbox: BBox, p: Vec2) bool {
return @reduce(.And, Vec.clamp(p, bbox.min, bbox.max) == p);
}
pub fn isEmpty(bbox: BBox) bool {
return @reduce(.Or, bbox.min > bbox.max);
}
pub fn size(bbox: BBox) u32 {
assert(!bbox.isEmpty());
const sz = (bbox.max - bbox.min) + Vec2{ 1, 1 };
return @intCast(u32, @reduce(.Mul, sz));
}
pub const empty = BBox{ .min = Vec2{ 999999, 999999 }, .max = Vec2{ -999999, -999999 } };
};
pub fn Map(comptime TileType: type, width: usize, height: usize, allow_negative_pos: bool) type {
return struct {
pub const stride = width;
pub const Tile = TileType;
const Self = @This();
map: [height * width]Tile = undefined, // TODO: u1 -> std.StaticBitSet
bbox: BBox = BBox.empty,
default_tile: Tile,
const center_offset: isize = if (allow_negative_pos) ((width / 2) + stride * (height / 2)) else 0;
pub fn intToChar(t: Tile) u8 {
return switch (t) {
0 => '.',
1...9 => (@intCast(u8, t) + '0'),
else => '?',
};
}
fn defaultTileToChar(t: Tile) u8 {
if (Tile == u8)
return t;
unreachable;
}
pub fn printToBuf(map: *const Self, buf: []u8, opt: struct { pos: ?Vec2 = null, clip: ?BBox = null, tileToCharFn: fn (m: Tile) u8 = defaultTileToChar }) []const u8 {
var i: usize = 0;
const b = if (opt.clip) |box|
BBox{
.min = Vec.max(map.bbox.min, box.min),
.max = Vec.min(map.bbox.max, box.max),
}
else
map.bbox;
var p = b.min;
while (p[1] <= b.max[1]) : (p += Vec2{ 0, 1 }) {
p[0] = b.min[0];
while (p[0] <= b.max[0]) : (p += Vec2{ 1, 0 }) {
const offset = map.offsetof(p);
if (opt.pos != null and @reduce(.And, p == opt.pos.?)) {
buf[i] = '@';
} else {
buf[i] = opt.tileToCharFn(map.map[offset]);
}
i += 1;
}
buf[i] = '\n';
i += 1;
}
return buf[0..i];
}
pub fn fill(map: *Self, v: Tile, clip: ?BBox) void {
if (clip) |b| {
var p = b.min;
while (p[1] <= b.max[1]) : (p += Vec2{ 0, 1 }) {
p[0] = b.min[0];
while (p[0] <= b.max[0]) : (p += Vec2{ 1, 0 }) {
map.set(p, v);
}
}
} else {
std.mem.set(Tile, &map.map, v);
}
}
pub fn fillIncrement(map: *Self, v: Tile, clip: BBox) void {
const b = clip;
var p = b.min;
while (p[1] <= b.max[1]) : (p += Vec2{ 0, 1 }) {
p[0] = b.min[0];
while (p[0] <= b.max[0]) : (p += Vec2{ 1, 0 }) {
if (map.get(p)) |prev| {
map.set(p, prev + v);
} else {
map.set(p, v);
}
}
}
}
pub fn growBBox(map: *Self, p: Vec2) void {
if (map.bbox.includes(p)) return;
if (allow_negative_pos) {
assert(p[0] <= Self.stride / 2 and -p[0] <= Self.stride / 2);
} else {
assert(p[0] >= 0 and p[1] >= 0);
}
const prev = map.bbox;
map.bbox.min = Vec.min(p, map.bbox.min);
map.bbox.max = Vec.max(p, map.bbox.max);
if (prev.isEmpty()) {
map.fill(map.default_tile, map.bbox);
} else {
var y = map.bbox.min[1];
while (y < prev.min[1]) : (y += 1) {
const o = map.offsetof(Vec2{ map.bbox.min[0], y });
std.mem.set(Tile, map.map[o .. o + @intCast(usize, map.bbox.max[0] + 1 - map.bbox.min[0])], map.default_tile);
}
if (map.bbox.min[0] < prev.min[0]) {
assert(map.bbox.max[0] == prev.max[0]); // une seule colonne, on n'a grandi que d'un point.
while (y <= prev.max[1]) : (y += 1) {
const o = map.offsetof(Vec2{ map.bbox.min[0], y });
std.mem.set(Tile, map.map[o .. o + @intCast(usize, prev.min[0] - map.bbox.min[0])], map.default_tile);
}
} else if (map.bbox.max[0] > prev.max[0]) {
assert(map.bbox.min[0] == prev.min[0]);
while (y <= prev.max[1]) : (y += 1) {
const o = map.offsetof(Vec2{ prev.max[0] + 1, y });
std.mem.set(Tile, map.map[o .. o + @intCast(usize, map.bbox.max[0] + 1 - (prev.max[0] + 1))], map.default_tile);
}
} else {
y += (prev.max[1] - prev.min[1]) + 1;
}
while (y <= map.bbox.max[1]) : (y += 1) {
const o = map.offsetof(Vec2{ map.bbox.min[0], y });
std.mem.set(Tile, map.map[o .. o + @intCast(usize, map.bbox.max[0] + 1 - map.bbox.min[0])], map.default_tile);
}
}
}
pub fn offsetof(_: *const Self, p: Vec2) usize {
return @intCast(usize, center_offset + @reduce(.Add, @as(@Vector(2, isize), p) * @Vector(2, isize){ 1, @intCast(isize, stride) }));
}
pub fn at(map: *const Self, p: Vec2) Tile {
assert(map.bbox.includes(p));
const offset = map.offsetof(p);
return map.map[offset];
}
pub fn get(map: *const Self, p: Vec2) ?Tile {
if (!map.bbox.includes(p)) return null;
const offset = map.offsetof(p);
if (offset >= map.map.len)
return null;
return map.map[offset];
}
pub fn set(map: *Self, p: Vec2, t: Tile) void {
map.growBBox(p);
const offset = map.offsetof(p);
map.map[offset] = t;
}
pub fn setLine(map: *Self, p: Vec2, t: []const Tile) void {
if (allow_negative_pos) {
assert(p[0] <= Self.stride / 2 and -p[0] <= Self.stride / 2);
assert(p[0] + @intCast(i32, t.len - 1) <= Self.stride / 2);
} else {
assert(p[0] >= 0 and p[1] >= 0);
}
map.growBBox(p);
map.growBBox(p + Vec2{ @intCast(i32, t.len - 1), 0 });
const offset = map.offsetof(p);
std.mem.copy(Tile, map.map[offset .. offset + t.len], t);
}
const Iterator = struct {
map: *Self,
b: BBox,
p: Vec2,
pub fn next(self: *@This()) ?Tile {
if (self.p[1] > self.b.max[1]) return null;
const t = self.map.at(self.p);
self.p[0] += 1;
if (self.p[0] > self.b.max[0]) {
self.p[0] = self.b.min[0];
self.p[1] += 1;
}
return t;
}
pub fn nextPos(self: *@This()) ?Vec2 {
if (self.p[1] > self.b.max[1]) return null;
const t = self.p;
self.p[0] += 1;
if (self.p[0] > self.b.max[0]) {
self.p[0] = self.b.min[0];
self.p[1] += 1;
}
return t;
}
const TileAndNeighbours = struct {
t: *Tile,
p: Vec2,
neib4: [4]?Tile,
neib8: [8]?Tile,
up_left: ?Tile,
up: ?Tile,
up_right: ?Tile,
left: ?Tile,
right: ?Tile,
down_left: ?Tile,
down: ?Tile,
down_right: ?Tile,
};
pub fn nextEx(self: *@This()) ?TileAndNeighbours {
if (self.p[1] > self.b.max[1]) return null;
const t: *Tile = &self.map.map[self.map.offsetof(self.p)];
const n4 = [4]?Tile{
self.map.get(self.p + Vec2{ 1, 0 }),
self.map.get(self.p + Vec2{ -1, 0 }),
self.map.get(self.p + Vec2{ 0, 1 }),
self.map.get(self.p + Vec2{ 0, -1 }),
};
const n8 = [8]?Tile{
n4[0], n4[1], n4[2], n4[3],
self.map.get(self.p + Vec2{ -1, -1 }), self.map.get(self.p + Vec2{ 1, -1 }), self.map.get(self.p + Vec2{ -1, 1 }), self.map.get(self.p + Vec2{ 1, 1 }),
};
var r = TileAndNeighbours{
.t = t,
.p = self.p,
.neib4 = n4,
.neib8 = n8,
.up_left = n8[4],
.up = n4[3],
.up_right = n8[5],
.left = n4[1],
.right = n4[0],
.down_left = n8[6],
.down = n4[2],
.down_right = n8[7],
};
self.p[0] += 1;
if (self.p[0] > self.b.max[0]) {
self.p[0] = self.b.min[0];
self.p[1] += 1;
}
return r;
}
};
pub fn iter(map: *Self, clip: ?BBox) Iterator {
const b = if (clip) |box|
BBox{
.min = Vec.max(map.bbox.min, box.min),
.max = Vec.min(map.bbox.max, box.max),
}
else
map.bbox;
return Iterator{ .map = map, .b = b, .p = b.min };
}
};
} | common/tools_v2.zig |
pub const _FACDXCORE = @as(u32, 2176);
pub const DXCORE_ADAPTER_ATTRIBUTE_D3D11_GRAPHICS = Guid.initString("8c47866b-7583-450d-f0f0-6bada895af4b");
pub const DXCORE_ADAPTER_ATTRIBUTE_D3D12_GRAPHICS = Guid.initString("0c9ece4d-2f6e-4f01-8c96-e89e331b47b1");
pub const DXCORE_ADAPTER_ATTRIBUTE_D3D12_CORE_COMPUTE = Guid.initString("248e2800-a793-4724-abaa-23a6de1be090");
//--------------------------------------------------------------------------------
// Section: Types (13)
//--------------------------------------------------------------------------------
pub const DXCoreAdapterProperty = enum(u32) {
InstanceLuid = 0,
DriverVersion = 1,
DriverDescription = 2,
HardwareID = 3,
KmdModelVersion = 4,
ComputePreemptionGranularity = 5,
GraphicsPreemptionGranularity = 6,
DedicatedAdapterMemory = 7,
DedicatedSystemMemory = 8,
SharedSystemMemory = 9,
AcgCompatible = 10,
IsHardware = 11,
IsIntegrated = 12,
IsDetachable = 13,
HardwareIDParts = 14,
};
pub const InstanceLuid = DXCoreAdapterProperty.InstanceLuid;
pub const DriverVersion = DXCoreAdapterProperty.DriverVersion;
pub const DriverDescription = DXCoreAdapterProperty.DriverDescription;
pub const HardwareID = DXCoreAdapterProperty.HardwareID;
pub const KmdModelVersion = DXCoreAdapterProperty.KmdModelVersion;
pub const ComputePreemptionGranularity = DXCoreAdapterProperty.ComputePreemptionGranularity;
pub const GraphicsPreemptionGranularity = DXCoreAdapterProperty.GraphicsPreemptionGranularity;
pub const DedicatedAdapterMemory = DXCoreAdapterProperty.DedicatedAdapterMemory;
pub const DedicatedSystemMemory = DXCoreAdapterProperty.DedicatedSystemMemory;
pub const SharedSystemMemory = DXCoreAdapterProperty.SharedSystemMemory;
pub const AcgCompatible = DXCoreAdapterProperty.AcgCompatible;
pub const IsHardware = DXCoreAdapterProperty.IsHardware;
pub const IsIntegrated = DXCoreAdapterProperty.IsIntegrated;
pub const IsDetachable = DXCoreAdapterProperty.IsDetachable;
pub const HardwareIDParts = DXCoreAdapterProperty.HardwareIDParts;
pub const DXCoreAdapterState = enum(u32) {
IsDriverUpdateInProgress = 0,
AdapterMemoryBudget = 1,
};
pub const IsDriverUpdateInProgress = DXCoreAdapterState.IsDriverUpdateInProgress;
pub const AdapterMemoryBudget = DXCoreAdapterState.AdapterMemoryBudget;
pub const DXCoreSegmentGroup = enum(u32) {
Local = 0,
NonLocal = 1,
};
pub const Local = DXCoreSegmentGroup.Local;
pub const NonLocal = DXCoreSegmentGroup.NonLocal;
pub const DXCoreNotificationType = enum(u32) {
ListStale = 0,
NoLongerValid = 1,
BudgetChange = 2,
HardwareContentProtectionTeardown = 3,
};
pub const AdapterListStale = DXCoreNotificationType.ListStale;
pub const AdapterNoLongerValid = DXCoreNotificationType.NoLongerValid;
pub const AdapterBudgetChange = DXCoreNotificationType.BudgetChange;
pub const AdapterHardwareContentProtectionTeardown = DXCoreNotificationType.HardwareContentProtectionTeardown;
pub const DXCoreAdapterPreference = enum(u32) {
Hardware = 0,
MinimumPower = 1,
HighPerformance = 2,
};
pub const Hardware = DXCoreAdapterPreference.Hardware;
pub const MinimumPower = DXCoreAdapterPreference.MinimumPower;
pub const HighPerformance = DXCoreAdapterPreference.HighPerformance;
pub const DXCoreHardwareID = extern struct {
vendorID: u32,
deviceID: u32,
subSysID: u32,
revision: u32,
};
pub const DXCoreHardwareIDParts = extern struct {
vendorID: u32,
deviceID: u32,
subSystemID: u32,
subVendorID: u32,
revisionID: u32,
};
pub const DXCoreAdapterMemoryBudgetNodeSegmentGroup = extern struct {
nodeIndex: u32,
segmentGroup: DXCoreSegmentGroup,
};
pub const DXCoreAdapterMemoryBudget = extern struct {
budget: u64,
currentUsage: u64,
availableForReservation: u64,
currentReservation: u64,
};
pub const PFN_DXCORE_NOTIFICATION_CALLBACK = fn(
notificationType: DXCoreNotificationType,
object: ?*IUnknown,
context: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) void;
const IID_IDXCoreAdapter_Value = @import("../zig.zig").Guid.initString("f0db4c7f-fe5a-42a2-bd62-f2a6cf6fc83e");
pub const IID_IDXCoreAdapter = &IID_IDXCoreAdapter_Value;
pub const IDXCoreAdapter = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
IsValid: fn(
self: *const IDXCoreAdapter,
) callconv(@import("std").os.windows.WINAPI) bool,
IsAttributeSupported: fn(
self: *const IDXCoreAdapter,
attributeGUID: ?*const Guid,
) callconv(@import("std").os.windows.WINAPI) bool,
IsPropertySupported: fn(
self: *const IDXCoreAdapter,
property: DXCoreAdapterProperty,
) callconv(@import("std").os.windows.WINAPI) bool,
GetProperty: fn(
self: *const IDXCoreAdapter,
property: DXCoreAdapterProperty,
bufferSize: usize,
// TODO: what to do with BytesParamIndex 1?
propertyData: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPropertySize: fn(
self: *const IDXCoreAdapter,
property: DXCoreAdapterProperty,
bufferSize: ?*usize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsQueryStateSupported: fn(
self: *const IDXCoreAdapter,
property: DXCoreAdapterState,
) callconv(@import("std").os.windows.WINAPI) bool,
QueryState: fn(
self: *const IDXCoreAdapter,
state: DXCoreAdapterState,
inputStateDetailsSize: usize,
// TODO: what to do with BytesParamIndex 1?
inputStateDetails: ?*const anyopaque,
outputBufferSize: usize,
// TODO: what to do with BytesParamIndex 3?
outputBuffer: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsSetStateSupported: fn(
self: *const IDXCoreAdapter,
property: DXCoreAdapterState,
) callconv(@import("std").os.windows.WINAPI) bool,
SetState: fn(
self: *const IDXCoreAdapter,
state: DXCoreAdapterState,
inputStateDetailsSize: usize,
// TODO: what to do with BytesParamIndex 1?
inputStateDetails: ?*const anyopaque,
inputDataSize: usize,
// TODO: what to do with BytesParamIndex 3?
inputData: ?*const anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFactory: fn(
self: *const IDXCoreAdapter,
riid: ?*const Guid,
ppvFactory: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXCoreAdapter_IsValid(self: *const T) callconv(.Inline) bool {
return @ptrCast(*const IDXCoreAdapter.VTable, self.vtable).IsValid(@ptrCast(*const IDXCoreAdapter, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXCoreAdapter_IsAttributeSupported(self: *const T, attributeGUID: ?*const Guid) callconv(.Inline) bool {
return @ptrCast(*const IDXCoreAdapter.VTable, self.vtable).IsAttributeSupported(@ptrCast(*const IDXCoreAdapter, self), attributeGUID);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXCoreAdapter_IsPropertySupported(self: *const T, property: DXCoreAdapterProperty) callconv(.Inline) bool {
return @ptrCast(*const IDXCoreAdapter.VTable, self.vtable).IsPropertySupported(@ptrCast(*const IDXCoreAdapter, self), property);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXCoreAdapter_GetProperty(self: *const T, property: DXCoreAdapterProperty, bufferSize: usize, propertyData: ?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXCoreAdapter.VTable, self.vtable).GetProperty(@ptrCast(*const IDXCoreAdapter, self), property, bufferSize, propertyData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXCoreAdapter_GetPropertySize(self: *const T, property: DXCoreAdapterProperty, bufferSize: ?*usize) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXCoreAdapter.VTable, self.vtable).GetPropertySize(@ptrCast(*const IDXCoreAdapter, self), property, bufferSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXCoreAdapter_IsQueryStateSupported(self: *const T, property: DXCoreAdapterState) callconv(.Inline) bool {
return @ptrCast(*const IDXCoreAdapter.VTable, self.vtable).IsQueryStateSupported(@ptrCast(*const IDXCoreAdapter, self), property);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXCoreAdapter_QueryState(self: *const T, state: DXCoreAdapterState, inputStateDetailsSize: usize, inputStateDetails: ?*const anyopaque, outputBufferSize: usize, outputBuffer: ?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXCoreAdapter.VTable, self.vtable).QueryState(@ptrCast(*const IDXCoreAdapter, self), state, inputStateDetailsSize, inputStateDetails, outputBufferSize, outputBuffer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXCoreAdapter_IsSetStateSupported(self: *const T, property: DXCoreAdapterState) callconv(.Inline) bool {
return @ptrCast(*const IDXCoreAdapter.VTable, self.vtable).IsSetStateSupported(@ptrCast(*const IDXCoreAdapter, self), property);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXCoreAdapter_SetState(self: *const T, state: DXCoreAdapterState, inputStateDetailsSize: usize, inputStateDetails: ?*const anyopaque, inputDataSize: usize, inputData: ?*const anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXCoreAdapter.VTable, self.vtable).SetState(@ptrCast(*const IDXCoreAdapter, self), state, inputStateDetailsSize, inputStateDetails, inputDataSize, inputData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXCoreAdapter_GetFactory(self: *const T, riid: ?*const Guid, ppvFactory: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXCoreAdapter.VTable, self.vtable).GetFactory(@ptrCast(*const IDXCoreAdapter, self), riid, ppvFactory);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDXCoreAdapterList_Value = @import("../zig.zig").Guid.initString("526c7776-40e9-459b-b711-f32ad76dfc28");
pub const IID_IDXCoreAdapterList = &IID_IDXCoreAdapterList_Value;
pub const IDXCoreAdapterList = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetAdapter: fn(
self: *const IDXCoreAdapterList,
index: u32,
riid: ?*const Guid,
ppvAdapter: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAdapterCount: fn(
self: *const IDXCoreAdapterList,
) callconv(@import("std").os.windows.WINAPI) u32,
IsStale: fn(
self: *const IDXCoreAdapterList,
) callconv(@import("std").os.windows.WINAPI) bool,
GetFactory: fn(
self: *const IDXCoreAdapterList,
riid: ?*const Guid,
ppvFactory: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Sort: fn(
self: *const IDXCoreAdapterList,
numPreferences: u32,
preferences: [*]const DXCoreAdapterPreference,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsAdapterPreferenceSupported: fn(
self: *const IDXCoreAdapterList,
preference: DXCoreAdapterPreference,
) callconv(@import("std").os.windows.WINAPI) bool,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXCoreAdapterList_GetAdapter(self: *const T, index: u32, riid: ?*const Guid, ppvAdapter: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXCoreAdapterList.VTable, self.vtable).GetAdapter(@ptrCast(*const IDXCoreAdapterList, self), index, riid, ppvAdapter);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXCoreAdapterList_GetAdapterCount(self: *const T) callconv(.Inline) u32 {
return @ptrCast(*const IDXCoreAdapterList.VTable, self.vtable).GetAdapterCount(@ptrCast(*const IDXCoreAdapterList, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXCoreAdapterList_IsStale(self: *const T) callconv(.Inline) bool {
return @ptrCast(*const IDXCoreAdapterList.VTable, self.vtable).IsStale(@ptrCast(*const IDXCoreAdapterList, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXCoreAdapterList_GetFactory(self: *const T, riid: ?*const Guid, ppvFactory: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXCoreAdapterList.VTable, self.vtable).GetFactory(@ptrCast(*const IDXCoreAdapterList, self), riid, ppvFactory);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXCoreAdapterList_Sort(self: *const T, numPreferences: u32, preferences: [*]const DXCoreAdapterPreference) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXCoreAdapterList.VTable, self.vtable).Sort(@ptrCast(*const IDXCoreAdapterList, self), numPreferences, preferences);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXCoreAdapterList_IsAdapterPreferenceSupported(self: *const T, preference: DXCoreAdapterPreference) callconv(.Inline) bool {
return @ptrCast(*const IDXCoreAdapterList.VTable, self.vtable).IsAdapterPreferenceSupported(@ptrCast(*const IDXCoreAdapterList, self), preference);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IDXCoreAdapterFactory_Value = @import("../zig.zig").Guid.initString("78ee5945-c36e-4b13-a669-005dd11c0f06");
pub const IID_IDXCoreAdapterFactory = &IID_IDXCoreAdapterFactory_Value;
pub const IDXCoreAdapterFactory = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CreateAdapterList: fn(
self: *const IDXCoreAdapterFactory,
numAttributes: u32,
filterAttributes: [*]const Guid,
riid: ?*const Guid,
ppvAdapterList: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAdapterByLuid: fn(
self: *const IDXCoreAdapterFactory,
adapterLUID: ?*const LUID,
riid: ?*const Guid,
ppvAdapter: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsNotificationTypeSupported: fn(
self: *const IDXCoreAdapterFactory,
notificationType: DXCoreNotificationType,
) callconv(@import("std").os.windows.WINAPI) bool,
RegisterEventNotification: fn(
self: *const IDXCoreAdapterFactory,
dxCoreObject: ?*IUnknown,
notificationType: DXCoreNotificationType,
callbackFunction: ?PFN_DXCORE_NOTIFICATION_CALLBACK,
callbackContext: ?*anyopaque,
eventCookie: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UnregisterEventNotification: fn(
self: *const IDXCoreAdapterFactory,
eventCookie: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXCoreAdapterFactory_CreateAdapterList(self: *const T, numAttributes: u32, filterAttributes: [*]const Guid, riid: ?*const Guid, ppvAdapterList: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXCoreAdapterFactory.VTable, self.vtable).CreateAdapterList(@ptrCast(*const IDXCoreAdapterFactory, self), numAttributes, filterAttributes, riid, ppvAdapterList);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXCoreAdapterFactory_GetAdapterByLuid(self: *const T, adapterLUID: ?*const LUID, riid: ?*const Guid, ppvAdapter: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXCoreAdapterFactory.VTable, self.vtable).GetAdapterByLuid(@ptrCast(*const IDXCoreAdapterFactory, self), adapterLUID, riid, ppvAdapter);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXCoreAdapterFactory_IsNotificationTypeSupported(self: *const T, notificationType: DXCoreNotificationType) callconv(.Inline) bool {
return @ptrCast(*const IDXCoreAdapterFactory.VTable, self.vtable).IsNotificationTypeSupported(@ptrCast(*const IDXCoreAdapterFactory, self), notificationType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXCoreAdapterFactory_RegisterEventNotification(self: *const T, dxCoreObject: ?*IUnknown, notificationType: DXCoreNotificationType, callbackFunction: ?PFN_DXCORE_NOTIFICATION_CALLBACK, callbackContext: ?*anyopaque, eventCookie: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXCoreAdapterFactory.VTable, self.vtable).RegisterEventNotification(@ptrCast(*const IDXCoreAdapterFactory, self), dxCoreObject, notificationType, callbackFunction, callbackContext, eventCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDXCoreAdapterFactory_UnregisterEventNotification(self: *const T, eventCookie: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDXCoreAdapterFactory.VTable, self.vtable).UnregisterEventNotification(@ptrCast(*const IDXCoreAdapterFactory, self), eventCookie);
}
};}
pub usingnamespace MethodMixin(@This());
};
//--------------------------------------------------------------------------------
// Section: Functions (1)
//--------------------------------------------------------------------------------
pub extern "DXCORE" fn DXCoreCreateAdapterFactory(
riid: ?*const Guid,
ppvFactory: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (0)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
},
.wide => struct {
},
.unspecified => if (@import("builtin").is_test) struct {
} else struct {
},
};
//--------------------------------------------------------------------------------
// Section: Imports (4)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const HRESULT = @import("../foundation.zig").HRESULT;
const IUnknown = @import("../system/com.zig").IUnknown;
const LUID = @import("../foundation.zig").LUID;
test {
// The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476
if (@hasDecl(@This(), "PFN_DXCORE_NOTIFICATION_CALLBACK")) { _ = PFN_DXCORE_NOTIFICATION_CALLBACK; }
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
} | win32/graphics/dxcore.zig |
const std = @import("std");
const builtin = @import("builtin");
const uri = @import("uri");
const api = @import("api.zig");
const cache = @import("cache.zig");
const Engine = @import("Engine.zig");
const Dependency = @import("Dependency.zig");
const Project = @import("Project.zig");
const utils = @import("utils.zig");
const local = @import("local.zig");
const main = @import("root");
const ThreadSafeArenaAllocator = @import("ThreadSafeArenaAllocator.zig");
const c = @cImport({
@cInclude("git2.h");
});
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
pub const name = "git";
pub const Resolution = []const u8;
pub const ResolutionEntry = struct {
url: []const u8,
ref: []const u8,
commit: []const u8,
root: []const u8,
dep_idx: ?usize = null,
pub fn format(
entry: ResolutionEntry,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) @TypeOf(writer).Error!void {
_ = fmt;
_ = options;
try writer.print("{s}:{s}/{s} -> {}", .{
entry.url,
entry.commit,
entry.root,
entry.dep_idx,
});
}
};
pub const FetchError =
@typeInfo(@typeInfo(@TypeOf(getHeadCommitOfRef)).Fn.return_type.?).ErrorUnion.error_set ||
@typeInfo(@typeInfo(@TypeOf(fetch)).Fn.return_type.?).ErrorUnion.error_set;
const FetchQueue = Engine.MultiQueueImpl(Resolution, FetchError);
const ResolutionTable = std.ArrayListUnmanaged(ResolutionEntry);
pub fn deserializeLockfileEntry(
allocator: Allocator,
it: *std.mem.TokenIterator(u8),
resolutions: *ResolutionTable,
) !void {
try resolutions.append(allocator, .{
.url = it.next() orelse return error.Url,
.ref = it.next() orelse return error.NoRef,
.root = it.next() orelse return error.NoRoot,
.commit = it.next() orelse return error.NoCommit,
});
}
pub fn serializeResolutions(
resolutions: []const ResolutionEntry,
writer: anytype,
) !void {
for (resolutions) |entry| {
if (entry.dep_idx != null)
try writer.print("git {s} {s} {s} {s}\n", .{
entry.url,
entry.ref,
entry.root,
entry.commit,
});
}
}
pub fn findResolution(
dep: Dependency.Source,
resolutions: []const ResolutionEntry,
) ?usize {
const root = dep.git.root orelse utils.default_root;
return for (resolutions) |entry, j| {
if (std.mem.eql(u8, dep.git.url, entry.url) and
std.mem.eql(u8, dep.git.ref, entry.ref) and
std.mem.eql(u8, root, entry.root))
{
break j;
}
} else null;
}
fn findMatch(
dep_table: []const Dependency.Source,
dep_idx: usize,
edges: []const Engine.Edge,
) ?usize {
const dep = dep_table[dep_idx].git;
const root = dep.root orelse utils.default_root;
return for (edges) |edge| {
const other = dep_table[edge.to].git;
const other_root = other.root orelse utils.default_root;
if (std.mem.eql(u8, dep.url, other.url) and
std.mem.eql(u8, dep.ref, other.ref) and
std.mem.eql(u8, root, other_root))
{
break edge.to;
}
} else null;
}
const RemoteHeadEntry = struct {
oid: [c.GIT_OID_HEXSZ]u8,
name: []const u8,
};
pub fn getHEADCommit(
allocator: Allocator,
url: []const u8,
) ![]const u8 {
const url_z = try allocator.dupeZ(u8, url);
defer allocator.free(url_z);
var remote: ?*c.git_remote = null;
var err = c.git_remote_create_anonymous(&remote, null, url_z);
if (err < 0) {
const last_error = c.git_error_last();
std.log.err("{s}", .{last_error.*.message});
return error.GitRemoteCreate;
}
defer c.git_remote_free(remote);
var callbacks: c.git_remote_callbacks = undefined;
err = c.git_remote_init_callbacks(
&callbacks,
c.GIT_REMOTE_CALLBACKS_VERSION,
);
if (err < 0) {
const last_error = c.git_error_last();
std.log.err("{s}", .{last_error.*.message});
return error.GitRemoteInitCallbacks;
}
err = c.git_remote_connect(
remote,
c.GIT_DIRECTION_FETCH,
&callbacks,
null,
null,
);
if (err < 0) {
const last_error = c.git_error_last();
std.log.err("{s}", .{last_error.*.message});
return error.GitRemoteConnect;
}
var refs_ptr: [*c][*c]c.git_remote_head = undefined;
var refs_len: usize = undefined;
err = c.git_remote_ls(&refs_ptr, &refs_len, remote);
if (err < 0) {
const last_error = c.git_error_last();
std.log.err("{s}", .{last_error.*.message});
return error.GitRemoteLs;
}
var refs = std.ArrayList(RemoteHeadEntry).init(allocator);
defer {
for (refs.items) |entry|
allocator.free(entry.name);
refs.deinit();
}
var i: usize = 0;
while (i < refs_len) : (i += 1) {
const len = std.mem.len(refs_ptr[i].*.name);
try refs.append(.{
.oid = undefined,
.name = try allocator.dupeZ(u8, refs_ptr[i].*.name[0..len]),
});
_ = c.git_oid_fmt(
&refs.items[refs.items.len - 1].oid,
&refs_ptr[i].*.oid,
);
}
return for (refs.items) |entry| {
if (std.mem.eql(u8, entry.name, "HEAD"))
break allocator.dupe(u8, &entry.oid);
} else error.RefNotFound;
}
pub fn getHeadCommitOfRef(
allocator: Allocator,
url: []const u8,
ref: []const u8,
) ![]const u8 {
// if ref is the same size as an OID and hex format then treat it as a
// commit
if (ref.len == c.GIT_OID_HEXSZ) {
for (ref) |char| {
if (!std.ascii.isXDigit(char))
break;
} else return allocator.dupe(u8, ref);
}
const url_z = try allocator.dupeZ(u8, url);
defer allocator.free(url_z);
var remote: ?*c.git_remote = null;
var err = c.git_remote_create_anonymous(&remote, null, url_z);
if (err < 0) {
const last_error = c.git_error_last();
std.log.err("{s}", .{last_error.*.message});
return error.GitRemoteCreate;
}
defer c.git_remote_free(remote);
var callbacks: c.git_remote_callbacks = undefined;
err = c.git_remote_init_callbacks(
&callbacks,
c.GIT_REMOTE_CALLBACKS_VERSION,
);
if (err < 0) {
const last_error = c.git_error_last();
std.log.err("{s}", .{last_error.*.message});
return error.GitRemoteInitCallbacks;
}
err = c.git_remote_connect(
remote,
c.GIT_DIRECTION_FETCH,
&callbacks,
null,
null,
);
if (err < 0) {
const last_error = c.git_error_last();
std.log.err("{s}", .{last_error.*.message});
return error.GitRemoteConnect;
}
var refs_ptr: [*c][*c]c.git_remote_head = undefined;
var refs_len: usize = undefined;
err = c.git_remote_ls(&refs_ptr, &refs_len, remote);
if (err < 0) {
const last_error = c.git_error_last();
std.log.err("{s}", .{last_error.*.message});
return error.GitRemoteLs;
}
var refs = std.ArrayList(RemoteHeadEntry).init(allocator);
defer {
for (refs.items) |entry|
allocator.free(entry.name);
refs.deinit();
}
var i: usize = 0;
while (i < refs_len) : (i += 1) {
const len = std.mem.len(refs_ptr[i].*.name);
try refs.append(.{
.oid = undefined,
.name = try allocator.dupeZ(u8, refs_ptr[i].*.name[0..len]),
});
_ = c.git_oid_fmt(
&refs.items[refs.items.len - 1].oid,
&refs_ptr[i].*.oid,
);
}
inline for (&[_][]const u8{ "refs/tags/", "refs/heads/" }) |prefix| {
for (refs.items) |entry| {
if (std.mem.startsWith(u8, entry.name, prefix) and
std.mem.eql(u8, entry.name[prefix.len..], ref))
{
return allocator.dupe(u8, &entry.oid);
}
}
}
std.log.err("'{s}' ref not found", .{ref});
return error.RefNotFound;
}
const CloneState = struct {
arena: *ThreadSafeArenaAllocator,
base_path: []const u8,
};
fn submoduleCb(sm: ?*c.git_submodule, sm_name: [*c]const u8, payload: ?*anyopaque) callconv(.C) c_int {
return if (submoduleCbImpl(sm, sm_name, payload)) 0 else |err| blk: {
std.log.err("got err: {s}", .{@errorName(err)});
break :blk -1;
};
}
fn indexerCb(stats_c: [*c]const c.git_indexer_progress, payload: ?*anyopaque) callconv(.C) c_int {
const stats = @ptrCast(*const c.git_indexer_progress, stats_c);
const handle = @ptrCast(*usize, @alignCast(@alignOf(*usize), payload)).*;
main.display.updateEntry(handle, .{
.progress = .{
.current = stats.received_objects + stats.indexed_objects,
.total = stats.total_objects * 2,
},
}) catch {};
return 0;
}
fn submoduleCbImpl(sm: ?*c.git_submodule, sm_name: [*c]const u8, payload: ?*anyopaque) !void {
const parent_state = @ptrCast(*CloneState, @alignCast(@alignOf(*CloneState), payload));
const arena = parent_state.arena;
const allocator = arena.child_allocator;
if (sm == null)
return;
const submodule_name = if (sm_name != null)
std.mem.span(sm_name)
else
return;
// git always uses posix path separators
const sub_path = try std.mem.replaceOwned(u8, allocator, submodule_name, "/", std.fs.path.sep_str);
defer allocator.free(sub_path);
const base_path = try std.fs.path.join(allocator, &.{ parent_state.base_path, sub_path });
defer allocator.free(base_path);
const oid = try arena.allocator().alloc(u8, c.GIT_OID_HEXSZ);
_ = c.git_oid_fmt(
oid.ptr,
c.git_submodule_head_id(sm),
);
const sm_url = c.git_submodule_url(sm);
const url = if (sm_url != null)
std.mem.sliceTo(sm_url, 0)
else
return;
var handle = try main.display.createEntry(.{
.sub = .{
.url = try arena.allocator().dupe(u8, url),
.commit = oid,
},
});
errdefer main.display.updateEntry(handle, .{ .err = {} }) catch {};
var options: c.git_submodule_update_options = undefined;
_ = c.git_submodule_update_options_init(&options, c.GIT_SUBMODULE_UPDATE_OPTIONS_VERSION);
options.fetch_opts.callbacks.transfer_progress = indexerCb;
options.fetch_opts.callbacks.payload = &handle;
var err = c.git_submodule_update(sm, 1, &options);
if (err != 0) {
std.log.err("{s}", .{c.git_error_last().*.message});
return error.GitSubmoduleUpdate;
}
var repo: ?*c.git_repository = null;
err = c.git_submodule_open(&repo, sm);
if (err != 0)
return error.GitSubmoduleOpen;
defer c.git_repository_free(repo);
var state = CloneState{
.arena = arena,
.base_path = base_path,
};
err = c.git_submodule_foreach(repo, submoduleCb, &state);
if (err != 0) {
std.log.err("{s}", .{c.git_error_last().*.message});
return error.GitSubmoduleForeach;
}
// TODO: deleteTree doesn't work on windows with hidden or read-only files
if (builtin.target.os.tag != .windows) {
const dot_git = try std.fs.path.join(allocator, &.{ base_path, ".git" });
defer allocator.free(dot_git);
try std.fs.cwd().deleteTree(dot_git);
}
}
pub fn clone(
arena: *ThreadSafeArenaAllocator,
url: []const u8,
commit: []const u8,
path: []const u8,
) !void {
const allocator = arena.child_allocator;
const url_z = try allocator.dupeZ(u8, url);
defer allocator.free(url_z);
const path_z = try allocator.dupeZ(u8, path);
defer allocator.free(path_z);
const commit_z = try allocator.dupeZ(u8, commit);
defer allocator.free(commit_z);
var handle = try main.display.createEntry(.{
.git = .{
.url = url,
.commit = commit,
},
});
errdefer main.display.updateEntry(handle, .{ .err = {} }) catch {};
var repo: ?*c.git_repository = null;
var options: c.git_clone_options = undefined;
_ = c.git_clone_options_init(&options, c.GIT_CLONE_OPTIONS_VERSION);
options.fetch_opts.callbacks.transfer_progress = indexerCb;
options.fetch_opts.callbacks.payload = &handle;
var err = c.git_clone(&repo, url_z, path_z, &options);
if (err != 0) {
std.log.err("{s}", .{c.git_error_last().*.message});
return error.GitClone;
}
defer c.git_repository_free(repo);
var oid: c.git_oid = undefined;
err = c.git_oid_fromstr(&oid, commit_z);
if (err != 0) {
std.log.err("{s}", .{c.git_error_last().*.message});
return error.GitOidFromString;
}
var obj: ?*c.git_object = undefined;
err = c.git_object_lookup(&obj, repo, &oid, c.GIT_OBJECT_COMMIT);
if (err != 0) {
std.log.err("{s}", .{c.git_error_last().*.message});
return error.GitObjectLookup;
}
var checkout_opts: c.git_checkout_options = undefined;
_ = c.git_checkout_options_init(&checkout_opts, c.GIT_CHECKOUT_OPTIONS_VERSION);
err = c.git_checkout_tree(repo, obj, &checkout_opts);
if (err != 0) {
std.log.err("{s}", .{c.git_error_last().*.message});
return error.GitCheckoutTree;
}
var state = CloneState{
.arena = arena,
.base_path = path,
};
err = c.git_submodule_foreach(repo, submoduleCb, &state);
if (err != 0) {
std.log.err("\n{s}", .{c.git_error_last().*.message});
return error.GitSubmoduleForeach;
}
// TODO: deleteTree doesn't work on windows with hidden or read-only files
if (builtin.target.os.tag != .windows) {
const dot_git = try std.fs.path.join(allocator, &.{ path, ".git" });
defer allocator.free(dot_git);
try std.fs.cwd().deleteTree(dot_git);
}
}
fn findPartialMatch(
allocator: Allocator,
dep_table: []const Dependency.Source,
commit: []const u8,
dep_idx: usize,
edges: []const Engine.Edge,
) !?usize {
const dep = dep_table[dep_idx].git;
return for (edges) |edge| {
const other = dep_table[edge.to].git;
if (std.mem.eql(u8, dep.url, other.url)) {
const other_commit = try getHeadCommitOfRef(
allocator,
other.url,
other.ref,
);
defer allocator.free(other_commit);
if (std.mem.eql(u8, commit, other_commit)) {
break edge.to;
}
}
} else null;
}
pub fn fmtCachePath(
allocator: Allocator,
url: []const u8,
commit: []const u8,
) ![]const u8 {
var components = std.ArrayList([]const u8).init(allocator);
defer components.deinit();
const link = try uri.parse(url);
const scheme = link.scheme orelse return error.NoUriScheme;
const end = url.len - if (std.mem.endsWith(u8, url, ".git"))
".git".len
else
0;
var it = std.mem.tokenize(u8, url[scheme.len + 1 .. end], "/");
while (it.next()) |comp|
try components.insert(0, comp);
try components.append(commit[0..8]);
return std.mem.join(allocator, "-", components.items);
}
pub fn resolutionToCachePath(
allocator: Allocator,
res: ResolutionEntry,
) ![]const u8 {
return fmtCachePath(allocator, res.url, res.commit);
}
fn fetch(
arena: *ThreadSafeArenaAllocator,
dep: Dependency.Source,
done: bool,
commit: Resolution,
deps: *std.ArrayListUnmanaged(Dependency),
path: *?[]const u8,
) !void {
const allocator = arena.child_allocator;
const entry_name = try fmtCachePath(allocator, dep.git.url, commit);
defer allocator.free(entry_name);
var entry = try cache.getEntry(entry_name);
defer entry.deinit();
const base_path = try std.fs.path.join(allocator, &.{
".gyro",
entry_name,
"pkg",
});
defer allocator.free(base_path);
if (!done and !try entry.isDone()) {
if (builtin.target.os.tag != .windows) {
if (std.fs.cwd().access(base_path, .{})) {
try std.fs.cwd().deleteTree(base_path);
} else |_| {}
// TODO: if base_path exists then deleteTree it
}
try clone(
arena,
dep.git.url,
commit,
base_path,
);
try entry.done();
}
const root = dep.git.root orelse utils.default_root;
path.* = try utils.joinPathConvertSep(arena, &.{ base_path, root });
if (!done) {
var base_dir = try std.fs.cwd().openDir(base_path, .{});
defer base_dir.close();
const project_file = try base_dir.createFile("gyro.zzz", .{
.read = true,
.truncate = false,
.exclusive = false,
});
defer project_file.close();
const text = try project_file.reader().readAllAlloc(
arena.allocator(),
std.math.maxInt(usize),
);
const project = try Project.fromUnownedText(arena, base_path, text);
defer project.destroy();
try deps.appendSlice(allocator, project.deps.items);
}
}
pub fn dedupeResolveAndFetch(
arena: *ThreadSafeArenaAllocator,
dep_table: []const Dependency.Source,
resolutions: []const ResolutionEntry,
fetch_queue: *FetchQueue,
i: usize,
) void {
dedupeResolveAndFetchImpl(
arena,
dep_table,
resolutions,
fetch_queue,
i,
) catch |err| {
fetch_queue.items(.result)[i] = .{ .err = err };
};
}
fn dedupeResolveAndFetchImpl(
arena: *ThreadSafeArenaAllocator,
dep_table: []const Dependency.Source,
resolutions: []const ResolutionEntry,
fetch_queue: *FetchQueue,
i: usize,
) FetchError!void {
const dep_idx = fetch_queue.items(.edge)[i].to;
var commit: []const u8 = undefined;
if (findResolution(dep_table[dep_idx], resolutions)) |res_idx| {
if (resolutions[res_idx].dep_idx) |idx| {
fetch_queue.items(.result)[i] = .{
.replace_me = idx,
};
return;
} else if (findMatch(
dep_table,
dep_idx,
fetch_queue.items(.edge)[0..i],
)) |idx| {
fetch_queue.items(.result)[i] = .{
.replace_me = idx,
};
return;
} else {
fetch_queue.items(.result)[i] = .{
.fill_resolution = res_idx,
};
}
} else if (findMatch(
dep_table,
dep_idx,
fetch_queue.items(.edge)[0..i],
)) |idx| {
fetch_queue.items(.result)[i] = .{
.replace_me = idx,
};
return;
} else {
commit = try getHeadCommitOfRef(
arena.allocator(),
dep_table[dep_idx].git.url,
dep_table[dep_idx].git.ref,
);
if (try findPartialMatch(
arena.child_allocator,
dep_table,
commit,
dep_idx,
fetch_queue.items(.edge)[0..i],
)) |idx| {
fetch_queue.items(.result)[i] = .{
.copy_deps = idx,
};
} else {
fetch_queue.items(.result)[i] = .{
.new_entry = commit,
};
}
}
var done = false;
const resolution = switch (fetch_queue.items(.result)[i]) {
.fill_resolution => |res_idx| resolutions[res_idx].commit,
.new_entry => |entry_commit| entry_commit,
.copy_deps => blk: {
done = true;
break :blk commit;
},
else => unreachable,
};
try fetch(
arena,
dep_table[dep_idx],
done,
resolution,
&fetch_queue.items(.deps)[i],
&fetch_queue.items(.path)[i],
);
assert(fetch_queue.items(.path)[i] != null);
}
pub fn updateResolution(
allocator: Allocator,
resolutions: *ResolutionTable,
dep_table: []const Dependency.Source,
fetch_queue: *FetchQueue,
i: usize,
) !void {
switch (fetch_queue.items(.result)[i]) {
.fill_resolution => |res_idx| {
const dep_idx = fetch_queue.items(.edge)[i].to;
assert(resolutions.items[res_idx].dep_idx == null);
resolutions.items[res_idx].dep_idx = dep_idx;
},
.new_entry => |commit| {
const dep_idx = fetch_queue.items(.edge)[i].to;
const git = &dep_table[dep_idx].git;
const root = git.root orelse utils.default_root;
try resolutions.append(allocator, .{
.url = git.url,
.ref = git.ref,
.root = root,
.commit = commit,
.dep_idx = dep_idx,
});
},
.replace_me => |dep_idx| fetch_queue.items(.edge)[i].to = dep_idx,
.err => |err| {
std.log.err("recieved error: {s} while getting dep: {}", .{
@errorName(err),
dep_table[fetch_queue.items(.edge)[i].to],
});
return error.Explained;
},
.copy_deps => |queue_idx| {
const commit = resolutions.items[
findResolution(
dep_table[fetch_queue.items(.edge)[queue_idx].to],
resolutions.items,
).?
].commit;
const dep_idx = fetch_queue.items(.edge)[i].to;
const git = &dep_table[dep_idx].git;
const root = git.root orelse utils.default_root;
try resolutions.append(allocator, .{
.url = git.url,
.ref = git.ref,
.root = root,
.commit = commit,
.dep_idx = dep_idx,
});
try fetch_queue.items(.deps)[i].appendSlice(
allocator,
fetch_queue.items(.deps)[queue_idx].items,
);
},
}
} | src/git.zig |
pub fn main() void {
comptime var ret = compileBrainfuck("default.bf", 16);
const print = @import("std").debug.print;
print("Output: {}\nCycles done: {}\nTape: ", .{
ret.value.buffer,
ret.value.runtime,
});
inline for (ret.value.tape) |te| print("{} ", .{te});
print("\n", .{});
}
/// Compile Brainfuck file to a State object, containing all computations done.
/// This is to aid with optimization in a future.
fn compileBrainfuck(comptime fname: []const u8, comptime tape_size: usize) State(Machine(tape_size)) {
return comptime blk: {
const ST = State(Machine(tape_size));
var state = ST.create(Machine(tape_size){
.runtime = 0,
.codeptr = 0,
.tape = [_]u8{0} ** tape_size,
.pointer = 0,
.callstack = Stack(8, usize).init(0),
.buffer = "",
});
const file = @embedFile(fname);
@setEvalBranchQuota(10000);
inline while (state.value.codeptr < file.len) {
state = comptimeParse(Machine(tape_size), state, file[state.value.codeptr]);
}
break :blk state;
};
}
/// Parse Brainfuck instruction at compile-time.
/// Receives a State object, and a character representing the instruction.
/// Returns a new State object referencing the old one.
fn comptimeParse(comptime T: type, comptime state: State(T), comptime char: u8) !State(T) {
var tape = state.value.tape;
var pointer = state.value.pointer;
var callstack = state.value.callstack;
var buffer = state.value.buffer;
var codeptr = state.value.codeptr;
var runtime = state.value.runtime;
switch (char) {
'+' => {
tape[pointer] += 1;
codeptr += 1;
},
'-' => {
tape[pointer] -= 1;
codeptr += 1;
},
'>' => {
pointer += 1;
codeptr += 1;
},
'<' => {
pointer -= 1;
codeptr += 1;
},
'[' => {
callstack.push(codeptr);
codeptr += 1;
},
']' => {
if (tape[pointer] != 0) {
codeptr = callstack.pop();
} else {
codeptr += 1;
}
},
'.' => {
buffer = buffer ++ [_]u8{tape[pointer]};
codeptr += 1;
},
',' => {
return error.Unavail;
},
else => {
codeptr += 1;
},
}
return State(T){
.old_state = &state,
.value = T{
.runtime = runtime + 1,
.codeptr = codeptr,
.tape = tape,
.pointer = pointer,
.callstack = callstack,
.buffer = buffer,
},
};
}
fn Machine(comptime s: usize) type {
return struct {
const Self = @This();
runtime: usize,
codeptr: usize,
tape: [s]u8,
pointer: usize,
callstack: Stack(8, usize),
buffer: []const u8
};
}
fn Stack(comptime s: usize, comptime T: type) type {
return struct {
const Self = @This();
items: [s]T,
pointer: usize,
pub fn init(comptime v: T) Self {
return Self{
.items = [_]T{v} ** s,
.pointer = 0,
};
}
pub fn push(self: *Self, value: T) void {
self.items[self.pointer] = value;
self.pointer += 1;
}
pub fn pop(self: *Self) T {
self.pointer -= 1;
return self.items[self.pointer];
}
};
}
fn State(comptime T: type) type {
return struct {
const Self = @This();
old_state: ?*const Self,
value: T,
pub fn create(comptime value: T) Self {
return Self{
.old_state = null,
.value = value,
};
}
};
} | src/main.zig |
const std = @import("std");
const ssl = @import("ssl");
const SSLConnection = ssl.SSLConnection;
const Address = std.net.Address;
const Allocator = std.mem.Allocator;
const Url = @import("../url.zig").Url;
pub const GeminiResponse = struct {
original: []const u8,
content: []const u8,
statusCode: u8,
meta: []const u8,
alloc: *Allocator,
pub fn deinit(self: *GeminiResponse) void {
self.alloc.free(self.original);
self.alloc.free(self.meta);
}
};
pub const TemporaryFailureEnum = enum {
/// 40 TEMPORARY FAILURE
Default,
/// 41 SERVER UNAVAILABLE
ServerUnavailable,
/// 42 CGI ERROR
CgiError,
/// 43 PROXY ERROR
ProxyError,
/// 44 SLOW DOWN
SlowDown
};
pub const PermanentFailureEnum = enum {
/// 50 PERMANENT FAILURE
Default,
/// 51 NOT FOUND
NotFound,
/// 52 GONE
Gone,
/// 53 PROXY REQUEST REFUSED
ProxyRequestRefused,
/// 59 BAD REQUEST
BadRequest
};
pub const ClientCertificateEnum = enum {
/// 60 CLIENT CERTIFICATE REQUIRED
Default,
/// 61 CERTIFICATE NOT AUTHORISED
NotAuthorised,
/// 62 CERTIFICATE NOT VALID
NotValid
};
pub const GeminiErrorDetails = union(enum) {
/// 1x input
Input: struct {
sensitive: bool,
meta: []const u8,
allocator: *Allocator
},
/// 3x error
Redirect: struct {
temporary: bool,
meta: []const u8,
allocator: *Allocator
},
/// 4x error
TemporaryFailure: struct {
detail: TemporaryFailureEnum,
meta: []const u8,
allocator: *Allocator
},
/// 5x error
PermanentFailure: struct {
detail: PermanentFailureEnum,
meta: []const u8,
allocator: *Allocator
},
/// 6x error
ClientCertificateRequired: struct {
detail: ClientCertificateEnum,
meta: []const u8,
allocator: *Allocator
},
pub fn deinit(self: GeminiErrorDetails) void {
const info = @typeInfo(GeminiErrorDetails).Union;
const tag_type = info.tag_type.?;
const active = std.meta.activeTag(self);
inline for (info.fields) |field_info| {
if (@field(tag_type, field_info.name) == active) {
const child = @field(self, field_info.name);
child.allocator.free(child.meta);
}
}
}
};
pub const GeminiError = error {
// invalid response
MetaTooLong,
/// After receiving this error, the client should prompt the user to input a string
/// and retry the request with the inputted string
InputRequired,
/// The error is a known protocol error and details are in the passed GeminiErrorDetails union.
KnownError,
/// The response from the server was malformed
BadResponse,
MissingStatus,
InvalidStatus,
};
fn parseResponse(allocator: *Allocator, text: []const u8, errorDetails: *GeminiErrorDetails) !GeminiResponse {
const headerEnd = std.mem.indexOf(u8, text, "\r\n") orelse {
std.log.scoped(.gemini).err("Missing \\r\\n in server's response", .{});
return GeminiError.BadResponse;
};
const header = text[0..headerEnd];
var splitIterator = std.mem.split(u8, header, " ");
const status = splitIterator.next() orelse return GeminiError.MissingStatus;
if (status.len != 2) {
std.log.scoped(.gemini).err("Status code ({s}) has an invalid length: {} != 2", .{status, status.len});
return GeminiError.InvalidStatus;
}
const statusCode = std.fmt.parseUnsigned(u8, status, 10) catch {
std.log.scoped(.gemini).err("Invalid status code (not a number): {s}", .{status});
return GeminiError.InvalidStatus;
};
const meta = try allocator.dupe(u8, splitIterator.rest());
if (meta.len > 1024) {
std.log.scoped(.gemini).warn("Meta string is too long: {} bytes > 1024 bytes", .{meta.len});
//return GeminiError.MetaTooLong;
}
if (statusCode >= 10 and statusCode < 20) { // 1x (INPUT)
errorDetails.* = .{
.Input = .{
.sensitive = statusCode == 11,
.meta = meta,
.allocator = allocator
}
};
return GeminiError.InputRequired;
} else if (statusCode >= 30 and statusCode < 40) { // 3x (REDIRECT)
// TODO: redirect
std.log.scoped(.gemini).crit("TODO status code: {}", .{statusCode});
return GeminiError.KnownError;
} else if (statusCode >= 40 and statusCode < 50) { // 4x (TEMPORARY FAILURE)
errorDetails.* = .{
.TemporaryFailure = .{
.detail = switch (statusCode) {
41 => .ServerUnavailable,
42 => .CgiError,
43 => .ProxyError,
44 => .SlowDown,
else => .Default
},
.meta = meta,
.allocator = allocator
}
};
return GeminiError.KnownError;
} else if (statusCode >= 50 and statusCode < 60) { // 5x (PERMANENT FAILURE)
errorDetails.* = .{
.PermanentFailure = .{
.detail = switch (statusCode) {
51 => .NotFound,
52 => .Gone,
53 => .ProxyRequestRefused,
59 => .BadRequest,
else => .Default
},
.meta = meta,
.allocator = allocator
}
};
return GeminiError.KnownError;
} else if (statusCode >= 60 and statusCode < 70) { // 6x (CLIENT CERTIFICATE REQUIRED)
// TODO: client certificate
std.log.scoped(.gemini).crit("TODO status code: {}", .{statusCode});
return GeminiError.KnownError;
} else if (statusCode < 20 or statusCode > 29) { // not 2x (SUCCESS)
std.log.scoped(.gemini).err("{} is not a valid status code", .{statusCode});
return GeminiError.InvalidStatus;
}
return GeminiResponse {
.alloc = allocator,
.content = text[std.math.min(text.len, headerEnd+2)..],
.original = text,
.statusCode = statusCode,
.meta = meta
};
}
fn syncTcpConnect(address: Address) !std.fs.File {
const sock_flags = std.os.SOCK_STREAM | (if (@import("builtin").os.tag == .windows) 0 else std.os.SOCK_CLOEXEC);
const sockfd = try std.os.socket(address.any.family, sock_flags, std.os.IPPROTO_TCP);
errdefer std.os.close(sockfd);
try std.os.connect(sockfd, &address.any, address.getOsSockLen());
return std.fs.File{ .handle = sockfd };
}
pub fn request(allocator: *Allocator, address: Address, url: Url, errorDetails: *GeminiErrorDetails) !GeminiResponse {
var stream = try std.net.tcpConnectToAddress(address);
const conn = try SSLConnection.init(allocator, stream, url.host, true);
defer conn.deinit();
const reader = conn.reader();
const writer = conn.writer();
const buf = try std.fmt.allocPrint(allocator, "{}\r\n", .{url});
try writer.writeAll(buf); // send it all at once to avoid problems with bugged servers
allocator.free(buf);
var result: []u8 = try allocator.alloc(u8, 0);
errdefer allocator.free(result);
var bytes: [1024]u8 = undefined;
var read: usize = 0;
var len: usize = 0;
while (true) {
read = try reader.read(&bytes);
var start = len;
len += read;
result = try allocator.realloc(result, len);
@memcpy(result[start..].ptr, bytes[0..read].ptr, read);
if (read == 0) {
break;
}
}
return parseResponse(allocator, result, errorDetails);
} | zervo/protocols/gemini.zig |
usingnamespace @import("ncurses").ncurses;
const width: c_int = 30;
const height: c_int = 10;
var startx: c_int = 0;
var starty: c_int = 0;
const choices = [_][]const u8{
"Choice 1",
"Choice 2",
"Choice 3",
"Choice 4",
"Exit",
};
pub fn main() anyerror!void {
var highlight: isize = 1;
var choice: isize = 0;
var c: c_int = 0;
var event: MEVENT = undefined;
_ = try initscr();
defer endwin() catch {};
try noecho();
try clear();
try cbreak();
_ = mousemask(ALL_MOUSE_EVENTS | REPORT_MOUSE_POSITION, null);
startx = @divTrunc(80 - width, 2);
starty = @divTrunc(24 - height, 2);
try attron(A_REVERSE);
try mvaddstrzig(23, 1, "Click on Exit to quit (Works best in a virtual console)");
try refresh();
try attroff(A_REVERSE);
const menu_win = try newwin(height, width, starty, startx);
try menu_win.keypad(true);
try printMenu(menu_win, highlight);
while (true) {
c = try menu_win.wgetch();
switch (c) {
KEY_MOUSE => {
try getmouse(&event);
if (event.bstate & BUTTON1_CLICKED != 0) {
try reportChoice(event.x + 1, event.y + 1, &choice);
if (choice == -1) break;
if (choice == 0) continue;
try mvprintwzig(
22,
1,
"Choice made is : {d} String Chosen is \"{s:10}\"",
.{ choice, choices[@intCast(usize, choice - 1)] },
);
try refresh();
}
try printMenu(menu_win, choice);
},
else => {},
}
}
}
fn printMenu(menu_win: Window, highlight: isize) !void {
var x: c_int = 2;
var y: c_int = 2;
try menu_win.box(0, 0);
var i: usize = 0;
while (i < choices.len) : (i += 1) {
if (highlight == i + 1) {
try menu_win.wattron(A_REVERSE);
try menu_win.mvwprintwzig(y, x, "{s}", .{choices[i]});
try menu_win.wattroff(A_REVERSE);
} else {
try menu_win.mvwprintwzig(y, x, "{s}", .{choices[i]});
}
y += 1;
}
try menu_win.wrefresh();
}
fn reportChoice(mousex: c_int, mousey: c_int, choice: *isize) !void {
var i = startx + 2;
var j = starty + 3;
var ch: usize = 0;
while (ch < choices.len) : (ch += 1) {
if (mousey == j + choice.* and mousex >= i and mousex <= i + @intCast(c_int, choices[ch].len)) {
if (ch == choices.len - 1) {
choice.* = -1;
} else {
choice.* += 1;
}
}
}
} | examples/mouse.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const print = std.debug.print;
const data = @embedFile("../inputs/day20.txt");
pub fn main() anyerror!void {
var gpa_impl = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa_impl.deinit();
const gpa = gpa_impl.allocator();
return main_with_allocator(gpa);
}
pub fn main_with_allocator(allocator: Allocator) anyerror!void {
var prob = try parse(allocator, data);
defer prob.img.deinit();
var i: usize = 0;
while (i < 50) : (i += 1) {
try prob.img.enhance(allocator, prob.algo);
if (i == 1) print("Part 1: {d}\n", .{prob.img.count()});
}
print("Part 2: {d}\n", .{prob.img.count()});
}
const ImgEnhanceAlgo = [512]u1;
const Img = struct {
const Self = @This();
outside: u1,
inside: std.ArrayList(std.ArrayList(u1)),
fn deinit(self: Self) void {
for (self.inside.items) |row| row.deinit();
self.inside.deinit();
}
fn dump(self: Self) void {
for (self.inside.items) |row| {
for (row.items) |c| {
if (c == 1) {
print("#", .{});
} else {
print(".", .{});
}
}
print("\n", .{});
}
}
fn count(self: Self) usize {
var out: usize = 0;
for (self.inside.items) |row| {
for (row.items) |c| {
if (c == 1) out += 1;
}
}
return out;
}
fn enhance(self: *Self, allocator: Allocator, algo: ImgEnhanceAlgo) !void {
const row_size = self.inside.items[0].items.len + 2;
const num_rows = self.inside.items.len + 2;
// Add new rows and columns
for (self.inside.items) |*row| {
try row.insert(0, self.outside);
try row.append(self.outside);
}
var first_row = std.ArrayList(u1).init(allocator);
try first_row.appendNTimes(self.outside, row_size);
var last_row = std.ArrayList(u1).init(allocator);
try last_row.appendNTimes(self.outside, row_size);
try self.inside.insert(0, first_row);
try self.inside.append(last_row);
var out_buffer = [2]std.ArrayList(u1){
std.ArrayList(u1).init(allocator),
std.ArrayList(u1).init(allocator),
};
defer {
out_buffer[0].deinit();
out_buffer[1].deinit();
}
try out_buffer[0].appendNTimes(undefined, row_size);
try out_buffer[1].appendNTimes(undefined, row_size);
for (self.inside.items) |row, i| {
for (row.items) |_, j| {
var idx: u9 = 0;
var dy: isize = -1;
while (dy <= 1) : (dy += 1) {
var dx: isize = -1;
while (dx <= 1) : (dx += 1) {
const y = @intCast(isize, i) + dy;
const x = @intCast(isize, j) + dx;
idx <<= 1;
if (y < 0 or y >= num_rows or x < 0 or x >= row_size) {
idx |= self.outside;
} else {
idx |= self.inside.items[@intCast(usize, y)].items[@intCast(usize, x)];
}
}
}
out_buffer[0].items[j] = algo[idx];
}
if (i > 0) std.mem.swap(std.ArrayList(u1), &out_buffer[1], &self.inside.items[i - 1]);
std.mem.swap(std.ArrayList(u1), &out_buffer[0], &out_buffer[1]);
}
std.mem.swap(std.ArrayList(u1), &out_buffer[1], &self.inside.items[num_rows - 1]);
self.outside = algo[if (self.outside == 1) 0b1_1111_1111 else 0];
}
};
fn reset_as(row: *std.ArrayList(u1), from: std.ArrayList(u1)) void {
row.clearRetainingCapacity();
row.appendSliceAssumeCapacity(from.items);
}
const ParseResult = struct {
algo: ImgEnhanceAlgo,
img: Img,
};
fn char_to_pixel(c: u8) !u1 {
return switch (c) {
'#' => 1,
'.' => 0,
else => error.InvalidChar,
};
}
fn parse(allocator: Allocator, input: []const u8) !ParseResult {
var it = std.mem.split(u8, input, "\n\n");
const raw_enhance = it.next().?;
var algo: ImgEnhanceAlgo = undefined;
std.debug.assert(raw_enhance.len == 512);
for (raw_enhance) |c, i| {
algo[i] = try char_to_pixel(c);
}
var img = std.ArrayList(std.ArrayList(u1)).init(allocator);
var lines = std.mem.tokenize(u8, it.next().?, "\n");
while (lines.next()) |line| {
var row = try std.ArrayList(u1).initCapacity(allocator, line.len);
for (line) |c| {
try row.append(try char_to_pixel(c));
}
try img.append(row);
}
return ParseResult{
.algo = algo,
.img = Img{
.outside = 0,
.inside = img,
},
};
}
test "image enhancement" {
const input =
\\..#.#..#####.#.#.#.###.##.....###.##.#..###.####..#####..#....#..#..##..###..######.###...####..#..#####..##..#.#####...##.#.#..#.##..#.#......#.###.######.###.####...#.##.##..#..#..#####.....#.#....###..#.##......#.....#..#..#..##..#...##.######.####.####.#.#...#.......#..#.#.#...####.##.#......#..#...##.#.##..#...##.#.##..###.#......#.#.......#.#.#.####.###.##...#.....####.#..#..#.##.#....##..#.####....##...##..#...#......#.#.......#.......##..####..#...#.#.#...##..#.#..###..#####........#..####......#..#
\\
\\#..#.
\\#....
\\##..#
\\..#..
\\..###
;
const allocator = std.testing.allocator;
var prob = try parse(allocator, input);
defer prob.img.deinit();
try prob.img.enhance(allocator, prob.algo);
try prob.img.enhance(allocator, prob.algo);
try std.testing.expectEqual(@as(usize, 35), prob.img.count());
} | src/day20.zig |
const inputFile = @embedFile("./input/day14.txt");
const std = @import("std");
const Allocator = std.mem.Allocator;
const List = std.ArrayList;
const Str = []const u8;
const BitSet = std.DynamicBitSet;
const StrMap = std.StringHashMap;
const HashMap = std.HashMap;
const Map = std.AutoHashMap;
const assert = std.debug.assert;
const tokenize = std.mem.tokenize;
const print = std.debug.print;
const parseInt = std.fmt.parseInt;
fn sort(comptime T: type, items: []T) void {
std.sort.sort(T, items, {}, comptime std.sort.asc(T));
}
fn println(x: Str) void {
print("{s}\n", .{x});
}
const TwoCharSubstitution = struct {
substitute: u8,
count: u64,
// printf implementation
pub fn format(self: @This(), comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
if (self.count > 0 or self.substitute != 0) {
try writer.print("({d}) -> {c}", .{ self.count, self.substitute });
}
}
};
const numUppercaseLetters = 26;
fn toIndex(charA: u8, charB: u8) usize {
return (@as(usize, (charA - 'A')) * numUppercaseLetters) + (charB - 'A');
}
fn toIndexZeroBased(charA: u8, charB: u8) usize {
return (@as(usize, charA) * numUppercaseLetters) + charB;
}
fn fromIndex(pos: usize) struct { a: u8, b: u8 } {
const a = @intCast(u8, pos / 26) + 'A';
const b = @intCast(u8, pos % 26) + 'A';
return .{ .a = a, .b = b };
}
fn printSubstitutions(substitutions: []TwoCharSubstitution) void {
for (substitutions) |sub, pos| {
if (sub.count > 0) {
const temp = fromIndex(pos);
const a = temp.a;
const b = temp.b;
print("{c}{c}({d}) -> {c}\n", .{ a, b, sub.count, sub.substitute });
}
}
}
/// New algorithm thanks to my friend VVHack
/// See the old algorithm in the Git history prior to this commit
fn runSubstitutions(input: Str, allocator: Allocator, nRounds: u32) !usize {
var substitutions = try allocator.alloc(TwoCharSubstitution, numUppercaseLetters * numUppercaseLetters);
defer allocator.free(substitutions);
std.mem.set(TwoCharSubstitution, substitutions, .{ .substitute = 0, .count = 0 });
// ============= Step 1: parse ================
var it = tokenize(u8, input, "\n");
const initialStr = it.next().?; // the string to be substituted
// substitution rules
while (it.next()) |line| {
assert(line[3] == '-'); // sanity check
const idx = toIndex(line[0], line[1]);
const valPos = comptime "AA -> ".len;
substitutions[idx].substitute = line[valPos];
}
// ============= Step 2: generate counts ================
const lastChar = initialStr[initialStr.len - 1]; // special case the last char as it never gets substituted
for (initialStr) |c, i| {
// chunk every two char
if (i == initialStr.len - 1) break;
const idx = toIndex(c, initialStr[i + 1]);
substitutions[idx].count += 1;
}
// ============= Step 3: substitute ================
var round: usize = 0;
while (round < nRounds) : (round += 1) {
// for each two character list, run the substitution and add it to the substitutionsNew
var substitutionsNew = try allocator.dupe(TwoCharSubstitution, substitutions);
defer allocator.free(substitutionsNew);
for (substitutions) |substitution, pos| {
if (substitution.count > 0 and substitution.substitute != 0) {
// make the substitution
const temp = fromIndex(pos);
const charA = temp.a;
const charB = temp.b;
substitutionsNew[pos].count -= substitution.count;
substitutionsNew[toIndex(charA, substitution.substitute)].count += substitution.count;
substitutionsNew[toIndex(substitution.substitute, charB)].count += substitution.count;
}
}
std.mem.swap([]TwoCharSubstitution, &substitutions, &substitutionsNew);
}
// ============= Step 4: count min max ================
var counts = try allocator.alloc(usize, numUppercaseLetters);
defer allocator.free(counts);
std.mem.set(usize, counts, 0);
for (substitutions) |substitute, pos| {
const temp = fromIndex(pos);
const charA = temp.a - 'A';
counts[charA] += substitute.count;
}
counts[lastChar - 'A'] += 1;
var max: usize = 0;
var min: usize = std.math.maxInt(usize);
for (counts) |val| {
if (val != 0) {
if (max < val) {
max = val;
}
if (val < min) {
min = val;
}
}
}
return max - min;
}
pub fn main() !void {
// Standard boilerplate for Aoc problems
const stdout = std.io.getStdOut().writer();
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var gpaAllocator = gpa.allocator();
defer assert(!gpa.deinit()); // Check for memory leaks
var arena = std.heap.ArenaAllocator.init(gpaAllocator);
defer arena.deinit();
var allocator = arena.allocator();
try stdout.print("Part 2:{d}\n", .{try runSubstitutions(inputFile, allocator, 40)});
}
test "Part 1 and 2" {
const testInput =
\\NNCB
\\
\\CH -> B
\\HH -> N
\\CB -> H
\\NH -> C
\\HB -> C
\\HC -> B
\\HN -> C
\\NN -> C
\\BH -> H
\\NC -> B
\\NB -> B
\\BN -> B
\\BB -> N
\\BC -> B
\\CC -> N
\\CN -> C
\\
;
try std.testing.expectEqual(@as(usize, 5), try runSubstitutions(testInput, std.testing.allocator, 2));
try std.testing.expectEqual(@as(usize, 1588), try runSubstitutions(testInput, std.testing.allocator, 10));
try std.testing.expectEqual(@as(usize, 480563), try runSubstitutions(testInput, std.testing.allocator, 18));
} | src/day14.zig |
const std = @import("std");
const max_usize = @as(usize, 0) -% 1; // MAXusize
test "example" {
const input = @embedFile("15_example.txt");
var grid = Cave(input).init();
try std.testing.expectEqual(@as(usize, 315), grid.run());
}
pub fn main() void {
const input = @embedFile("15.txt");
var grid = Cave(input).init();
std.debug.print("{}\n", .{grid.run()});
}
fn Cave(comptime input: []const u8) type {
const m = comptime std.mem.indexOfScalar(u8, input, '\n') orelse @compileError("invalid input");
const n = m * 5;
return struct {
const Self = @This();
const Set = std.StaticBitSet(n * n);
set: Set,
grid: [n][n]u4,
distance: [n][n]usize,
fn nextRisk(risk: u4) u4 {
if (risk == 9) {
return 1;
} else {
return risk + 1;
}
}
fn init() Self {
var cave = Self{
.set = Set.initEmpty(),
.grid = undefined,
.distance = undefined,
};
var lines = std.mem.split(u8, input, "\n");
var row: usize = 0;
while (lines.next()) |line| {
for (line) |val, col| {
var risk = @intCast(u4, val - '0');
var y: u4 = 0;
var row_risk = risk;
while (y < 5) : (y += 1) {
var x: u4 = 0;
var col_risk = row_risk;
while (x < 5) : (x += 1) {
cave.grid[y * m + row][x * m + col] = col_risk;
cave.distance[y * m + row][x * m + col] = max_usize;
cave.set.set((y * m + row) * n + (x * m + col));
col_risk = nextRisk(col_risk);
}
row_risk = nextRisk(row_risk);
}
}
row += 1;
}
cave.distance[0][0] = 0;
return cave;
}
fn minFromSet(self: Self) ?usize {
var min: ?usize = null;
var min_val = max_usize;
var iter = self.set.iterator(.{});
while (iter.next()) |i| {
const row = i / n;
const col = i % n;
if (self.distance[row][col] < min_val) {
min = i;
min_val = self.distance[row][col];
}
}
return min;
}
fn run(self: *Self) usize {
while (self.minFromSet()) |u| {
self.set.unset(u);
const row = u / n;
const col = u % n;
// Up: row - 1, col
if (row != 0) {
const alt = self.distance[row][col] + self.grid[row - 1][col];
if (alt < self.distance[row - 1][col]) {
self.distance[row - 1][col] = alt;
}
}
// Right: row, col + 1
if (col != n - 1) {
const alt = self.distance[row][col] + self.grid[row][col + 1];
if (alt < self.distance[row][col + 1]) {
self.distance[row][col + 1] = alt;
}
}
// Left: row, col - 1
if (col != 0) {
const alt = self.distance[row][col] + self.grid[row][col - 1];
if (alt < self.distance[row][col - 1]) {
self.distance[row][col - 1] = alt;
}
}
// Down: row + 1, col
if (row != n - 1) {
const alt = self.distance[row][col] + self.grid[row + 1][col];
if (alt < self.distance[row + 1][col]) {
self.distance[row + 1][col] = alt;
}
}
}
return self.distance[n - 1][n - 1];
}
};
} | shritesh+zig/15b.zig |
const std = @import("std");
const iup = @import("iup.zig");
const interop = @import("interop.zig");
const Element = iup.Element;
const Handle = iup.Handle;
///
/// Translates the C-API IUP's signature to zig function
pub fn CallbackHandler(comptime T: type, comptime TCallback: type, comptime action: [:0]const u8) type {
return struct {
/// Attribute key to store a reference to the zig callback on IUP's side
const STORE = "__" ++ action;
const ACTION = action;
const Self = @This();
/// Set or remove the callback function
pub fn setCallback(handle: *T, callback: ?TCallback) void {
if (callback) |ptr| {
var nativeCallback = getNativeCallback(TCallback);
interop.setNativeCallback(handle, ACTION, nativeCallback);
interop.setCallbackStoreAttribute(TCallback, handle, STORE, ptr);
} else {
interop.setNativeCallback(handle, ACTION, null);
interop.setCallbackStoreAttribute(TCallback, handle, STORE, null);
}
}
pub fn setGlobalCallback(callback: ?TCallback) void {
if (callback) |ptr| {
var nativeCallback = getNativeCallback(TCallback);
interop.setNativeCallback({}, ACTION, nativeCallback);
interop.setCallbackStoreAttribute(TCallback, {}, STORE, ptr);
} else {
interop.setNativeCallback({}, ACTION, null);
interop.setCallbackStoreAttribute(TCallback, {}, STORE, null);
}
}
///
/// Invoke the attached function
/// args must be a tuple matching the TCallbackFn signature
fn invoke(handle: ?*Handle, args: anytype) c_int {
if (T == void) {
if (getGlobalCallback()) |callback| {
@call(.{}, callback, args) catch |err| switch (err) {
iup.CallbackResult.Ignore => return interop.consts.IUP_IGNORE,
iup.CallbackResult.Continue => return interop.consts.IUP_CONTINUE,
iup.CallbackResult.Close => return interop.consts.IUP_CLOSE,
else => return iup.MainLoop.onError(null, err),
};
}
} else {
var validHandle = handle orelse @panic("Invalid handle from callback");
if (getCallback(validHandle)) |callback| {
var element = @ptrCast(*T, validHandle);
@call(.{}, callback, .{element} ++ args) catch |err| switch (err) {
iup.CallbackResult.Ignore => return interop.consts.IUP_IGNORE,
iup.CallbackResult.Continue => return interop.consts.IUP_CONTINUE,
iup.CallbackResult.Close => return interop.consts.IUP_CLOSE,
else => return iup.MainLoop.onError(Element.fromRef(element), err),
};
}
}
return interop.consts.IUP_DEFAULT;
}
/// Gets a zig function related on the IUP's handle
fn getCallback(handle: *Handle) ?TCallback {
return interop.getCallbackStoreAttribute(TCallback, handle, STORE);
}
/// Gets a zig function related on the IUP's global handle
fn getGlobalCallback() ?TCallback {
return interop.getCallbackStoreAttribute(TCallback, {}, STORE);
}
/// Gets a native function with the propper signature
fn getNativeCallback(comptime Function: type) interop.NativeCallbackFn {
const native_callback = comptime blk: {
const info = @typeInfo(Function);
if (info != .Fn)
@compileError("getNativeCallback expects a function type");
const function_info = info.Fn;
var args: [function_info.args.len]type = undefined;
inline for (function_info.args) |arg, i| {
args[i] = arg.arg_type.?;
}
// TODO: Add all supported callbacks
// See iupcbs.h for more details
if (args.len == 0) {
break :blk Self.nativeCallbackFn;
} else if (args.len == 1) {
break :blk Self.nativeCallbackIFn;
} else if (args.len == 2 and args[1] == i32) {
break :blk Self.nativeCallbackIFni;
} else if (args.len == 2 and args[1] == [:0]const u8) {
break :blk Self.nativeCallbackIFns;
} else if (args.len == 3 and args[1] == i32 and args[2] == i32) {
break :blk Self.nativeCallbackIFnii;
} else if (args.len == 3 and args[1] == i32 and args[2] == [:0]const u8) {
break :blk Self.nativeCallbackIFnis;
} else if (args.len == 4 and args[1] == i32 and args[2] == i32 and args[3] == i32) {
break :blk Self.nativeCallbackIFniii;
} else if (args.len == 4 and args[1] == [:0]const u8 and args[2] == i32 and args[3] == i32) {
break :blk Self.nativeCallbackIFnsii;
} else if (args.len == 5 and args[1] == i32 and args[2] == i32 and args[3] == i32 and args[4] == i32) {
break :blk Self.nativeCallbackIFniiii;
} else if (args.len == 5 and args[1] == i32 and args[2] == i32 and args[3] == i32 and args[4] == [:0]const u8) {
break :blk Self.nativeCallbackIFniiis;
} else if (args.len == 6 and args[1] == i32 and args[2] == i32 and args[3] == i32 and args[4] == i32 and args[5] == [:0]const u8) {
break :blk Self.nativeCallbackIFniiiis;
} else {
@compileLog("args = ", args);
unreachable;
}
};
return @ptrCast(interop.NativeCallbackFn, native_callback);
}
// TODO: Add all supported callbacks
// See iupcbs.h for more details
fn nativeCallbackFn() callconv(.C) c_int {
return invoke(null, .{});
}
fn nativeCallbackIFn(handle: ?*Handle) callconv(.C) c_int {
return invoke(handle, .{});
}
fn nativeCallbackIFni(handle: ?*Handle, arg0: i32) callconv(.C) c_int {
return invoke(handle, .{arg0});
}
fn nativeCallbackIFns(handle: ?*Handle, arg0: [*]const u8) callconv(.C) c_int {
return invoke(handle, .{interop.fromCStr(arg0)});
}
fn nativeCallbackIFnii(handle: ?*Handle, arg0: i32, arg1: i32) callconv(.C) c_int {
return invoke(handle, .{ arg0, arg1 });
}
fn nativeCallbackIFnis(handle: ?*Handle, arg0: i32, arg1: [*]const u8) callconv(.C) c_int {
return invoke(handle, .{ arg0, interop.fromCStr(arg1) });
}
fn nativeCallbackIFniii(handle: ?*Handle, arg0: i32, arg1: i32, arg2: i32) callconv(.C) c_int {
return invoke(handle, .{ arg0, arg1, arg2 });
}
fn nativeCallbackIFniiii(handle: ?*Handle, arg0: i32, arg1: i32, arg2: i32, arg3: i32) callconv(.C) c_int {
return invoke(handle, .{ arg0, arg1, arg2, arg3 });
}
fn nativeCallbackIFnsii(handle: ?*Handle, arg0: [*]const u8, arg1: i32, arg2: i32) callconv(.C) c_int {
return invoke(handle, .{ interop.fromCStr(arg0), arg1, arg2 });
}
fn nativeCallbackIFniiis(handle: ?*Handle, arg0: i32, arg1: i32, arg2: i32, arg3: [*]const u8) callconv(.C) c_int {
return invoke(handle, .{ arg0, arg1, arg2, interop.fromCStr(arg3) });
}
fn nativeCallbackIFniiiis(handle: ?*Handle, arg0: i32, arg1: i32, arg2: i32, arg3: i32, arg4: [*]const u8) callconv(.C) c_int {
return invoke(handle, .{ arg0, arg1, arg2, arg3, interop.fromCStr(arg4) });
}
};
} | src/callback_handler.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
pub const NDError = error{
BufferTooSmall,
InvalidPick,
MissingAllocator,
OutOfBounds,
Unsupported,
};
pub const Order = enum {
Stride,
Major,
Minor,
};
pub const IterOpts = struct {
order: Order = .Major,
};
pub fn NDArray(comptime N: usize, comptime T: type) type {
return struct {
allocator: ?*const Allocator,
data: []T,
len: usize,
offset: isize,
shape: [N]u32,
stride: [N]isize,
order: [N]u8,
pub const T = T;
pub const dim: u32 = N;
const Self = @This();
const PositionIterator = struct {
parent: *const Self,
order: [N]u8,
pos: [N]u32 = [_]u32{0} ** N,
done: bool = false,
pub fn init(parent: *const Self, order: Order) @This() {
var iter = @This(){
.parent = parent,
.order = undefined,
};
switch (order) {
.Major => {
for (iter.order) |_, i| iter.order[i] = @intCast(u8, N - 1 - i);
},
.Minor => {
for (iter.order) |_, i| iter.order[i] = @intCast(u8, i);
},
.Stride => {
iter.order = parent.order;
},
}
return iter;
}
pub fn next(self: *@This()) ?[N]u32 {
if (self.done) return null;
const res: [N]u32 = self.pos;
const lastUpdate = for (self.order) |o, i| {
self.pos[o] = (self.pos[o] + 1) % self.parent.shape[o];
if (self.pos[o] != 0) break i;
} else N;
if (lastUpdate == N) self.done = true;
return res;
}
};
const IndexIterator = struct {
pos: PositionIterator,
pub fn next(self: *@This()) ?usize {
return if (self.pos.next()) |i| self.pos.parent.index(i) else null;
}
};
const ValueIterator = struct {
pos: PositionIterator,
pub fn next(self: *@This()) ?T {
return if (self.pos.next()) |i| self.pos.parent.at(i) else null;
}
};
pub fn init(opts: struct {
allocator: ?*const Allocator = null,
data: ?[]T = null,
offset: isize = 0,
shape: [N]u32,
stride: ?[N]isize = null,
}) !Self {
var self = Self{
.allocator = opts.allocator,
.data = undefined,
.len = Self.length(opts.shape),
.offset = opts.offset,
.shape = opts.shape,
.stride = if (opts.stride) |stride| stride else Self.shapeToStride(opts.shape),
.order = undefined,
};
self.order = Self.strideOrder(self.stride);
if (opts.data) |data| {
if (data.len >= self.len) {
self.data = data;
} else {
return NDError.BufferTooSmall;
}
} else {
if (opts.allocator) |allocator| {
self.data = try allocator.alloc(T, self.len);
@memset(@ptrCast([*]u8, self.data), 0, self.len * @sizeOf(T));
} else {
return NDError.MissingAllocator;
}
}
return self;
}
pub fn free(self: *Self) void {
if (self.allocator) |allocator| {
allocator.free(self.data);
}
}
pub inline fn index(self: *const Self, pos: [N]u32) usize {
var idx = self.offset;
comptime var i = 0;
inline while (i < N) {
idx += self.stride[i] * pos[i];
i += 1;
}
return @intCast(usize, idx);
}
pub fn positions(self: *const Self, opts: IterOpts) PositionIterator {
return PositionIterator.init(self, opts.order);
}
pub fn indices(self: *const Self, opts: IterOpts) IndexIterator {
return IndexIterator{ .pos = self.positions(opts) };
}
pub fn values(self: *const Self, opts: IterOpts) ValueIterator {
return ValueIterator{ .pos = self.positions(opts) };
}
pub fn at(self: *const Self, pos: [N]u32) T {
return self.data[self.index(pos)];
}
pub fn setAt(self: *const Self, pos: [N]u32, val: T) void {
self.data[self.index(pos)] = val;
}
pub fn fill(self: *const Self, val: T) void {
var iter = self.indices(.{});
while (true) {
if (iter.next()) |i| {
self.data[i] = val;
} else break;
}
}
pub fn sum(self: *const Self) T {
const info = @typeInfo(T);
if (!(info == .Int or info == .Float)) @compileError("only supported for int/float types");
var acc: T = 0;
var iter = self.values(.{});
while (true) {
if (iter.next()) |val| {
acc += val;
} else break;
}
return acc;
}
pub fn toOwnedSlice(self: *const Self, opts: struct {
data: ?[]T = null,
allocator: ?*const Allocator = null,
order: Order = .Major,
}) ![]T {
var dest: []T = undefined;
if (opts.data) |data| {
if (data.len < self.len) return NDError.BufferTooSmall;
dest = data;
} else if (opts.allocator) |allocator| {
dest = try allocator.alloc(T, self.len);
} else return NDError.MissingAllocator;
var d: usize = 0;
var iter = self.values(.{ .order = opts.order });
while (true) {
if (iter.next()) |val| {
dest[d] = val;
d += 1;
} else break;
}
return dest;
}
pub fn eq(self: *const Self, other: *const Self) bool {
if (!std.mem.eql(u32, self.shape[0..], other.shape[0..])) return false;
var ia = self.values(.{});
var ib = other.values(.{});
while (true) {
if (ia.next()) |va| {
if (ib.next()) |vb| {
if (va != vb) return false;
} else return false;
} else break;
}
return true;
}
pub fn eqApprox(self: *const Self, other: *const Self, tolerance: T) bool {
if (@typeInfo(T) != .Float) @compileError("only supported for float types");
if (!std.mem.eql(u32, self.shape[0..], other.shape[0..])) return false;
var ia = self.values(.{});
var ib = other.values(.{});
while (true) {
if (ia.next()) |va| {
if (ib.next()) |vb| {
if (!std.math.approxEqRel(T, va, vb, tolerance)) return false;
} else return false;
} else break;
}
return true;
}
pub fn hi(self: *const Self, pos: [N]?u32) !Self {
var newShape: [N]u32 = undefined;
for (pos) |p, i| {
if (p) |q| {
if (q < 1 or q > self.shape[i]) return NDError.OutOfBounds;
newShape[i] = q;
} else {
newShape[i] = self.shape[i];
}
}
return Self.init(.{
.allocator = self.allocator,
.data = self.data,
.offset = self.offset,
.shape = newShape,
.stride = self.stride,
});
}
pub fn lo(self: *const Self, pos: [N]?u32) !Self {
var off = self.offset;
var newShape: [N]u32 = undefined;
for (pos) |p, i| {
if (p) |q| {
if (q >= self.shape[i]) return NDError.OutOfBounds;
off += self.stride[i] * q;
newShape[i] = self.shape[i] - q;
} else {
newShape[i] = self.shape[i];
}
}
return Self.init(.{
.allocator = self.allocator,
.data = self.data,
.offset = off,
.shape = newShape,
.stride = self.stride,
});
}
/// Picks one or more axes from given ndarray and returns new a ndarray
/// with / reduced dimensions. The new array is using the same data buffer.
///
/// @param M - the number of axes to pick.
/// @param axes - partial coordinates defining the picked axes.
/// A `null` coord means the respective axis remains unchanged.
/// The array MUST contain exactly `M` non-null values.
pub fn pick(self: *const Self, comptime M: usize, axes: [N]?u32) !NDArray(N - M, T) {
if (M < 1) @compileError("require at least 1 dimension");
if (M >= N) @compileError("too many dimensions");
const K = N - M;
var newDim: usize = 0;
for (axes) |a| {
if (a == null) newDim += 1;
}
if (newDim != K) return NDError.InvalidPick;
var newShape: [K]u32 = undefined;
var newStride: [K]isize = undefined;
var off = self.offset;
var j: usize = 0;
for (axes) |axis, i| {
if (axis) |a| {
if (a >= self.shape[i]) return NDError.OutOfBounds;
off += self.stride[i] * a;
} else {
newShape[j] = self.shape[i];
newStride[j] = self.stride[i];
j += 1;
}
}
return NDArray(K, T).init(.{
.allocator = self.allocator,
.data = self.data,
.offset = off,
.shape = newShape,
.stride = newStride,
});
}
pub fn reshape(self: *const Self, comptime M: usize, opts: struct {
shape: [M]u32,
stride: ?[M]isize = null,
offset: ?isize = null,
}) !NDArray(M, T) {
const A = NDArray(M, T);
if (A.length(opts.shape) > self.data.len) return NDError.BufferTooSmall;
return try A.init(.{
.allocator = self.allocator,
.data = self.data,
.offset = if (opts.offset) |x| x else self.offset,
.shape = opts.shape,
.stride = opts.stride,
});
}
pub fn step(self: *const Self, steps: [N]?i32) !Self {
var newShape: [N]u32 = undefined;
var newStride: [N]isize = undefined;
var off = self.offset;
for (steps) |ss, i| {
if (ss) |s| {
var t = s;
if (s < 0) {
off += self.stride[i] * (self.shape[i] - 1);
t = -s;
}
newShape[i] = @divTrunc(self.shape[i], @intCast(u32, t));
newStride[i] = self.stride[i] * s;
} else {
newShape[i] = self.shape[i];
newStride[i] = self.stride[i];
}
}
return Self.init(.{
.allocator = self.allocator,
.data = self.data,
.offset = off,
.shape = newShape,
.stride = newStride,
});
}
pub fn transpose(self: *const Self, order: [N]u32) !Self {
var newShape: [N]u32 = undefined;
var newStride: [N]isize = undefined;
for (order) |o, i| {
if (o >= N) return NDError.OutOfBounds;
newShape[i] = self.shape[o];
newStride[i] = self.stride[o];
}
return Self.init(.{
.allocator = self.allocator,
.data = self.data,
.offset = self.offset,
.shape = newShape,
.stride = newStride,
});
}
pub fn print(self: *const Self) void {
std.debug.print("NDArray({},{})[shape={d} stride={d} offset={d} len={d}]\n", .{
N,
T,
self.shape,
self.stride,
self.offset,
self.len,
});
}
fn length(shape: [N]u32) usize {
var len: usize = 1;
for (shape) |s| len *= s;
return len;
}
fn shapeToStride(shape: [N]u32) [N]isize {
var stride = [_]isize{0} ** N;
var s: isize = 1;
for (shape) |_, i| {
const j = N - 1 - i;
stride[j] = s;
s *= @intCast(isize, shape[j]);
}
return stride;
}
fn strideOrder(stride: [N]isize) [N]u8 {
const Item = struct { s: isize, i: usize };
var res: [N]u8 = undefined;
var indexed: [N]Item = undefined;
for (indexed) |_, i| {
indexed[i] = .{ .s = stride[i], .i = i };
}
const cmp = struct {
fn inner(_: void, a: Item, b: Item) bool {
return iabs(a.s) < iabs(b.s);
}
};
std.sort.sort(Item, indexed[0..], {}, cmp.inner);
for (indexed) |x, i| {
res[i] = @intCast(u8, x.i);
}
return res;
}
};
}
fn iabs(x: isize) isize {
return if (x >= 0) x else -x;
}
pub fn range(n: u32, comptime T: type, allocator: *const Allocator) !NDArray(1, T) {
const info = @typeInfo(T);
if (!(info == .Int or info == .Float)) @compileError("only int or float types supported");
var res = try NDArray(1, T).init(.{
.allocator = allocator,
.shape = .{n},
});
var iter = res.indices(.{});
var j: T = 0;
while (true) {
if (iter.next()) |i| {
res.data[i] = j;
j += 1;
} else break;
}
return res;
}
pub fn ones(comptime N: usize, comptime T: type, shape: [N]u32, allocator: *const Allocator) NDArray(N, T) {
var res = try NDArray(N, T).init(.{
.allocator = allocator,
.shape = shape,
});
res.fill(1);
return res;
}
const __allocator = &std.testing.allocator;
test "nd3 f32 init" {
var a = try NDArray(3, f32).init(.{
.shape = .{ 4, 4, 4 },
.stride = .{ 1, 4, 16 },
.allocator = __allocator,
});
std.debug.print("a.order {d}\n", .{a.order});
defer a.free();
try std.testing.expectEqual(f32, @TypeOf(a).T);
try std.testing.expectEqual(@as(u32, 3), @TypeOf(a).dim);
try std.testing.expectEqual(@as(usize, 4 * 4 * 4), a.len);
try std.testing.expectEqual(@as(usize, 16 + 4 + 1), a.index(.{ 1, 1, 1 }));
var bdata: [64]f32 = [_]f32{0} ** 64;
var b = try NDArray(3, f32).init(.{
.data = bdata[0..],
// .data = try std.heap.page_allocator.alloc(f32, 65),
// .allocator = std.heap.page_allocator,
.shape = .{ 4, 4, 4 },
});
std.debug.print("b.order {d}\n", .{b.order});
try std.testing.expectEqual([_]isize{ 16, 4, 1 }, b.stride);
b.setAt(.{ 0, 1, 1 }, 42);
try std.testing.expectEqual(@as(f32, 42), b.at(.{ 0, 1, 1 }));
defer b.free();
var p = try b.toOwnedSlice(.{ .allocator = __allocator });
std.debug.print("{d}\n", .{p});
__allocator.free(p);
b.stride = .{ 1, 4, 16 };
p = try b.toOwnedSlice(.{ .allocator = __allocator });
std.debug.print("{d}\n", .{p});
__allocator.free(p);
}
test "nd3 f32 iter" {
var a = try NDArray(3, f32).init(.{
.shape = .{ 4, 4, 4 },
.stride = .{ 1, 4, 16 },
.allocator = __allocator,
});
defer a.free();
std.debug.print("stride {d}, order {d}\n", .{ a.stride, a.order });
a.setAt(.{ 0, 1, 1 }, 23);
a.setAt(.{ 1, 1, 1 }, 42);
try std.testing.expect(a.eqApprox(&a, 1e-9));
var p = try a.toOwnedSlice(.{ .allocator = __allocator });
defer __allocator.free(p);
std.debug.print("{d}\n", .{p});
var i = a.values(.{});
while (true) {
if (i.next()) |pos| {
std.debug.print("next: {d}\n", .{pos});
} else break;
}
}
test "1d reshape" {
var a = try range(16, u32, __allocator);
defer a.free();
var b = try a.reshape(4, .{ .shape = .{ 2, 2, 2, 2 } });
b = try b.transpose(.{ 1, 0, 3, 2 });
std.debug.print("{d}", .{b.stride});
var i = b.values(.{ .order = .Major });
while (true) {
if (i.next()) |pos| {
std.debug.print("next: {d}\n", .{pos});
} else break;
}
}
test "2d trunc" {
var a = try range(16, u32, __allocator);
defer a.free();
var b = try a.reshape(2, .{ .shape = .{ 4, 4 } });
b = try b.lo(.{ 1, 2 });
b = try b.hi(.{ 2, 2 });
std.debug.print("{d}", .{b.shape});
var c = try b.toOwnedSlice(.{ .allocator = __allocator });
defer __allocator.free(c);
std.debug.print("{d}\n", .{c});
}
test "3d -> 2d pick" {
var a = try range(4 * 4 * 4, u32, __allocator);
defer a.free();
var b = try a.reshape(3, .{ .shape = .{ 4, 4, 4 } });
var c = try b.pick(2, .{ 1, null, 1 });
c.print();
var d = try c.toOwnedSlice(.{ .allocator = __allocator });
defer __allocator.free(d);
std.debug.print("{d}\n", .{d});
}
test "3d step" {
var a = try range(4 * 4 * 4, u32, __allocator);
defer a.free();
var b = try NDArray(3, u32).init(.{
.data = a.data,
.shape = .{ 4, 4, 4 },
// .stride = .{ 1, 4, 16 },
// .allocator = &std.heap.page_allocator,
});
std.debug.print("\n", .{});
b.print();
// var b2 = try a2.reshape(3, .{ .shape = .{ 4, 2, 4 } });
var c = try b.step(.{ 2, -2, -1 });
c.print();
var d = try c.toOwnedSlice(.{ .allocator = __allocator });
defer __allocator.free(d);
std.debug.print("{d}\n", .{d});
}
test "3d axis iter" {
var a = try range(4 * 4 * 4, u32, __allocator);
defer a.free();
var b = try NDArray(3, u32).init(.{
.data = a.data,
.shape = .{ 4, 4, 4 },
});
// var b = try a.reshape(3, .{ .shape = .{ 4, 4, 4 } });
b.print();
var c = try b.pick(1, .{ 0, null, null });
c.print();
std.debug.print("sum {d}\n", .{c.sum()});
var d = try c.toOwnedSlice(.{ .allocator = __allocator });
defer __allocator.free(d);
std.debug.print("{d}\n", .{d});
} | src/nd.zig |
const c = @import("c.zig").c;
// must be in sync with GLFW C constants in hat state group, search for "@defgroup hat_state Joystick hat states"
/// A bitmask of all Joystick hat states
///
/// See glfw.Joystick.getHats for how these are used.
pub const Hat = packed struct {
up: bool = false,
right: bool = false,
down: bool = false,
left: bool = false,
_reserved: u4 = 0,
pub inline fn centered(self: Hat) bool {
return self.up == false and self.right == false and self.down == false and self.left == false;
}
inline fn verifyIntType(comptime IntType: type) void {
comptime {
switch (@typeInfo(IntType)) {
.Int => {},
else => @compileError("Int was not of int type"),
}
}
}
pub inline fn toInt(self: Hat, comptime IntType: type) IntType {
verifyIntType(IntType);
return @intCast(IntType, @bitCast(u8, self));
}
pub inline fn fromInt(flags: anytype) Hat {
verifyIntType(@TypeOf(flags));
return @bitCast(Hat, @intCast(u8, flags));
}
};
/// Holds all GLFW hat values in their raw form.
pub const RawHat = struct {
pub const centered = c.GLFW_HAT_CENTERED;
pub const up = c.GLFW_HAT_UP;
pub const right = c.GLFW_HAT_RIGHT;
pub const down = c.GLFW_HAT_DOWN;
pub const left = c.GLFW_HAT_LEFT;
pub const right_up = right | up;
pub const right_down = right | down;
pub const left_up = left | up;
pub const left_down = left | down;
};
test "from int, single" {
const std = @import("std");
try std.testing.expectEqual(Hat{
.up = true,
.right = false,
.down = false,
.left = false,
._reserved = 0,
}, Hat.fromInt(RawHat.up));
}
test "from int, multi" {
const std = @import("std");
try std.testing.expectEqual(Hat{
.up = true,
.right = false,
.down = true,
.left = true,
._reserved = 0,
}, Hat.fromInt(RawHat.up | RawHat.down | RawHat.left));
}
test "to int, single" {
const std = @import("std");
var v = Hat{
.up = true,
.right = false,
.down = false,
.left = false,
._reserved = 0,
};
try std.testing.expectEqual(v.toInt(c_int), RawHat.up);
}
test "to int, multi" {
const std = @import("std");
var v = Hat{
.up = true,
.right = false,
.down = true,
.left = true,
._reserved = 0,
};
try std.testing.expectEqual(v.toInt(c_int), RawHat.up | RawHat.down | RawHat.left);
} | glfw/src/hat.zig |
const root = @import("root");
pub const ENABLE_PROFILER: bool = if (@hasDecl(root, "TC_ENABLE_PROFILER"))
root.TC_ENABLE_PROFILER
else
false;
/// Controls whether the shadow stack return routine checks the integrity of a
/// return address (and aborts on failure) or just discards a non-trustworthy
/// return address.
pub const ABORTING_SHADOWSTACK: bool = if (@hasDecl(root, "TC_ABORTING_SHADOWSTACK"))
root.TC_ABORTING_SHADOWSTACK
else
false;
pub const ShadowExcStackType = enum {
/// The minimum implementation that does not perform any actual checks.
Null,
/// Chooses the naïve, nondescript implementation that pushes exactly one
/// item on exception entry. In this implementation, exception entry chain
/// can cause some exception frames to be left unprotected.
Naive,
/// Disables nested exceptions. This greatly simplifies the shadow exception
/// stack algorithm, improving performance. The exception trampoline can also
/// be made smaller (`nonsecure_vector_unnest.S`).
///
/// When this option is selected, all exceptions must be configured with the
/// same group priority so none of them can preempt another.
Unnested,
/// The exception trampoline scans the stacks to make sure all active
/// exception frames are protected by the shadow stack.
Safe,
};
/// Selects the implementation of shadow exception stack to use.
pub const SHADOW_EXC_STACK_TYPE: ShadowExcStackType = if (@hasDecl(root, "TC_SHADOW_EXC_STACK_TYPE"))
root.TC_SHADOW_EXC_STACK_TYPE
else
ShadowExcStackType.Safe;
/// Compile-time log level.
pub const LOG_LEVEL: LogLevel = if (@hasDecl(root, "TC_LOG_LEVEL"))
if (@TypeOf(root.TC_LOG_LEVEL) == LogLevel)
root.TC_LOG_LEVEL
else
@field(LogLevel, root.TC_LOG_LEVEL)
else
LogLevel.Critical;
pub const LogLevel = enum(u8) {
/// This log level outputs every single log message.
Trace = 0,
/// Produces fewer log messages than `Trace`.
Warning = 1,
/// Only outputs important message, such as a profiling result when
/// `TC_ENABLE_PROFILER` is enabled.
Critical = 2,
/// Disables the log output. All log messages are removed at compile-time.
None = 3,
};
pub fn isLogLevelEnabled(level: LogLevel) bool {
return @enumToInt(level) >= @enumToInt(LOG_LEVEL);
}
/// A function for configuring MPU guard regions for a shadow stack.
///
/// The two parameters `start` and `end` specify the starting and ending
/// addresses of a shadow stack. `start` and `end` are aligned to 32-byte blocks
/// and `start` is less than `end`. The callee must configure MPU to ensure
/// memory access at the following ranges fails and triggers an exception:
///
/// - `start - 32 .. start`
/// - `end .. end + 32`
///
/// The intended way to implement this is to set up at least 3 MPU regions: the
/// first one at `start - 32 .. start`, the second one at `end .. end + 32`, and
/// the last one overlapping both of them. Memory access always fails regardless
/// of privileged/unprivileged modes in a region overlap.
pub const setShadowStackGuard: fn (usize, usize) void = root.tcSetShadowStackGuard;
/// A function for removing MPU guard regions for a shadow stack.
pub const resetShadowStackGuard: fn (usize, usize) void = root.tcResetShadowStackGuard; | src/monitor/options.zig |
const sf = @import("../sfml.zig");
const std = @import("std");
const VertexArray = @This();
// Constructors/destructors
/// Creates a vertex array from a slice of vertices
pub fn createFromSlice(vertex: []const sf.graphics.Vertex, primitive: sf.graphics.PrimitiveType) !VertexArray {
var va = sf.c.sfVertexArray_create();
if (va) |vert| {
sf.c.sfVertexArray_setPrimitiveType(vert, @enumToInt(primitive));
sf.c.sfVertexArray_resize(vert, vertex.len);
for (vertex) |v, i|
sf.c.sfVertexArray_getVertex(vert, i).* = @bitCast(sf.c.sfVertex, v);
return VertexArray{ ._ptr = vert };
} else return sf.Error.nullptrUnknownReason;
}
/// Destroys a vertex array
pub fn destroy(self: *VertexArray) void {
sf.c.sfVertexArray_destroy(self._ptr);
}
/// Copies the vertex array
pub fn copy(self: VertexArray) !VertexArray {
var va = sf.c.sfVertexArray_copy(self._ptr);
if (va) |vert| {
return VertexArray{ ._ptr = vert };
} else return sf.Error.nullptrUnknownReason;
}
// Wtf github copilot wrote that for me (all of the functions below here)
// Methods and getters/setters
/// Gets the vertex count of the vertex array
pub fn getVertexCount(self: VertexArray) usize {
return sf.c.sfVertexArray_getVertexCount(self._ptr);
}
/// Gets the vertex using its index
pub fn getVertex(self: VertexArray, index: usize) sf.graphics.Vertex {
var v = sf.c.sfVertexArray_getVertex(self._ptr, index);
std.debug.assert(index < self.getVertexCount());
return @bitCast(sf.graphics.Vertex, v.?.*);
}
/// Clears the vertex array
pub fn clear(self: *VertexArray) void {
sf.c.sfVertexArray_clear(self._ptr);
}
/// Resizes the vertex array to a given size
pub fn resize(self: *VertexArray, vertexCount: usize) void {
sf.c.sfVertexArray_resize(self._ptr, vertexCount);
}
/// Appends a vertex to the array
pub fn append(self: *VertexArray, vertex: sf.graphics.Vertex) void {
sf.c.sfVertexArray_append(self._ptr, @bitCast(sf.c.sfVertex, vertex));
}
/// Gets the primitives' type of this array
pub fn getPrimitiveType(self: VertexArray) sf.graphics.PrimitiveType {
return @intToEnum(sf.graphics.PrimitiveType, sf.c.sfVertexArray_getPrimitiveType(self._ptr));
}
/// Sets the primitives' type of this array
pub fn setPrimitiveType(self: *VertexArray, primitive: sf.graphics.PrimitiveType) void {
sf.c.sfVertexArray_setPrimitiveType(self._ptr, @enumToInt(primitive));
}
/// Gets the bounding rectangle of the vertex array
pub fn getBounds(self: VertexArray) sf.graphics.FloatRect {
return sf.graphics.FloatRect._fromCSFML(sf.c.sfVertexArray_getBounds(self._ptr));
}
/// Draw function
pub fn sfDraw(self: VertexArray, window: anytype, states: ?*sf.c.sfRenderStates) void {
switch (@TypeOf(window)) {
sf.graphics.RenderWindow => sf.c.sfRenderWindow_drawVertexArray(window._ptr, self._ptr, states),
sf.graphics.RenderTexture => sf.c.sfRenderTexture_drawVertexArray(window._ptr, self._ptr, states),
else => @compileError("window must be a render target"),
}
}
/// Pointer to the csfml structure
_ptr: *sf.c.sfVertexArray,
test "VertexArray: sane getters and setters" {
const tst = std.testing;
const va_slice = [_]sf.graphics.Vertex{
.{ .position = .{ .x = -1, .y = 0 }, .color = sf.graphics.Color.Red },
.{ .position = .{ .x = 1, .y = 0 }, .color = sf.graphics.Color.Green },
.{ .position = .{ .x = -1, .y = 1 }, .color = sf.graphics.Color.Blue },
};
var va = try createFromSlice(va_slice[0..], sf.graphics.PrimitiveType.Triangles);
defer va.destroy();
va.append(.{ .position = .{ .x = 1, .y = 1 }, .color = sf.graphics.Color.Yellow });
va.setPrimitiveType(sf.graphics.PrimitiveType.Quads);
try tst.expectEqual(@as(usize, 4), va.getVertexCount());
try tst.expectEqual(sf.graphics.PrimitiveType.Quads, va.getPrimitiveType());
try tst.expectEqual(sf.graphics.FloatRect{ .left = -1, .top = 0, .width = 2, .height = 1 }, va.getBounds());
va.resize(3);
va.setPrimitiveType(sf.graphics.PrimitiveType.TriangleFan);
try tst.expectEqual(@as(usize, 3), va.getVertexCount());
const vert = va.getVertex(0);
try tst.expectEqual(sf.system.Vector2f{ .x = -1, .y = 0 }, vert.position);
try tst.expectEqual(sf.graphics.Color.Red, vert.color);
va.clear();
try tst.expectEqual(@as(usize, 0), va.getVertexCount());
} | src/sfml/graphics/VertexArray.zig |
pub const P = [18]u32{
0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0,
0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b,
};
pub const S = [4][256]u32{
[_]u32{
0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96,
0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658,
0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e,
0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6,
0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c,
0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1,
0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a,
0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176,
0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706,
0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b,
0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c,
0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a,
0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760,
0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8,
0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33,
0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0,
0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777,
0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705,
0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e,
0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9,
0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f,
0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
}, [_]u32{
0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d,
0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65,
0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9,
0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d,
0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc,
0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908,
0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124,
0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908,
0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b,
0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa,
0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d,
0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5,
0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96,
0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca,
0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77,
0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054,
0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea,
0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646,
0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea,
0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e,
0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd,
0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
},
[_]u32{
0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7,
0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af,
0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4,
0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec,
0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332,
0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58,
0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22,
0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60,
0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99,
0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74,
0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3,
0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979,
0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa,
0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086,
0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24,
0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84,
0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09,
0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe,
0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0,
0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188,
0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8,
0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
}, [_]u32{
0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742,
0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79,
0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a,
0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1,
0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797,
0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6,
0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba,
0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5,
0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce,
0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd,
0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb,
0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc,
0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc,
0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a,
0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a,
0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b,
0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e,
0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623,
0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a,
0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3,
0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c,
0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6,
},
}; | src/sboxes.zig |
const builtin = @import("builtin");
const TypeId = builtin.TypeId;
const std = @import("std");
const math = std.math;
const inf_f16 = std.math.inf_f16;
const inf_f32 = std.math.inf_f32;
const inf_f64 = std.math.inf_f64;
const f16_max = std.math.f16_max;
const f32_max = std.math.f32_max;
const f64_max = std.math.f64_max;
const maxInt = std.math.maxInt;
const minInt = std.math.minInt;
const assert = std.debug.assert;
const warn = std.debug.warn;
const DBG = false;
// A bit mask to validate all paths are tested
// TODO: Validate when tests have concluded that paths_accu is the expected value.
var paths_accu: u64 = 0;
pub fn maxFloat(comptime T: type) T {
return switch (T) {
f16 => inf_f16,
f32 => inf_f32,
f64 => inf_f64,
else => @compileError("Expecting type to be a float"),
};
}
test "maxminvalue.maxFloat" {
assert(maxFloat(f16) == inf_f16);
assert(maxFloat(f32) == inf_f32);
assert(maxFloat(f64) == inf_f64);
}
/// Return the non-infinite max value
pub fn nonInfMaxFloat(comptime T: type) T {
return switch (T) {
f16 => f16_max,
f32 => f32_max,
f64 => f64_max,
else => @compileError("Expecting type to be a float"),
};
}
test "maxminvalue.nonInfMaxFloat" {
assert(nonInfMaxFloat(f16) == f16_max);
assert(nonInfMaxFloat(f32) == f32_max);
assert(nonInfMaxFloat(f64) == f64_max);
}
pub fn minFloat(comptime T: type) T {
return switch (T) {
f16 => -inf_f16,
f32 => -inf_f32,
f64 => -inf_f64,
else => @compileError("Expecting type to be a float"),
};
}
test "maxminvalue.minFloat" {
assert(minFloat(f16) == -inf_f16);
assert(minFloat(f32) == -inf_f32);
assert(minFloat(f64) == -inf_f64);
}
/// Return the non-infinite min value
pub fn nonInfMinFloat(comptime T: type) T {
return -nonInfMaxFloat(T);
}
test "maxminvalue.nonInfMinFloat" {
assert(nonInfMinFloat(f16) == -nonInfMaxFloat(f16));
assert(nonInfMinFloat(f32) == -nonInfMaxFloat(f32));
assert(nonInfMinFloat(f64) == -nonInfMaxFloat(f64));
}
pub fn maxValue(comptime T: type) T {
return switch (@typeId(T)) {
TypeId.Int => maxInt(T),
TypeId.Float => maxFloat(T),
else => @compileError("Expecting type to be a float or int"),
};
}
test "maxminvalue.maxValue.ints" {
assert(maxValue(u0) == 0);
assert(maxValue(u1) == 1);
assert(maxValue(u8) == 255);
assert(maxValue(u16) == 65535);
assert(maxValue(u32) == 4294967295);
assert(maxValue(u64) == 18446744073709551615);
assert(maxValue(i0) == 0);
assert(maxValue(i1) == 0);
assert(maxValue(i8) == 127);
assert(maxValue(i16) == 32767);
assert(maxValue(i32) == 2147483647);
assert(maxValue(i63) == 4611686018427387903);
assert(maxValue(i64) == 9223372036854775807);
assert(maxValue(f16) == inf_f16);
assert(maxValue(f32) == inf_f32);
assert(maxValue(f64) == inf_f64);
}
pub fn minValue(comptime T: type) T {
return switch (@typeId(T)) {
TypeId.Int => minInt(T),
TypeId.Float => minFloat(T),
else => @compileError("Expecting type to be a float or int"),
};
}
test "maxminvalue.minValue.ints" {
assert(minValue(u0) == 0);
assert(minValue(u1) == 0);
assert(minValue(u8) == 0);
assert(minValue(u16) == 0);
assert(minValue(u32) == 0);
assert(minValue(u63) == 0);
assert(minValue(u64) == 0);
assert(minValue(i0) == 0);
assert(minValue(i1) == -1);
assert(minValue(i8) == -128);
assert(minValue(i16) == -32768);
assert(minValue(i32) == -2147483648);
assert(minValue(i63) == -4611686018427387904);
assert(minValue(i64) == -9223372036854775808);
assert(minValue(f16) == -inf_f16);
assert(minValue(f32) == -inf_f32);
assert(minValue(f64) == -inf_f64);
}
test "maxminvalue.maxValue.floats" {
assert(maxValue(f16) == maxValue(f16));
assert(maxValue(f32) == maxValue(f16));
assert(maxValue(f64) == maxValue(f16));
assert(@intToFloat(f16, maxValue(i16)) < maxValue(f16));
assert(@intToFloat(f16, maxValue(u16)) == maxValue(f16));
assert(@intToFloat(f16, maxValue(u32)) == maxValue(f16));
assert(@intToFloat(f16, maxValue(u64)) == maxValue(f16));
assert(@intToFloat(f16, maxValue(u128)) == maxValue(f16));
assert(f32_max < maxValue(f32));
assert(maxValue(f16) == maxValue(f32));
assert(maxValue(f32) == maxValue(f32));
assert(maxValue(f64) == maxValue(f32));
assert(@intToFloat(f32, maxValue(i32)) < maxValue(f32));
assert(@intToFloat(f32, maxValue(u32)) < maxValue(f32));
assert(@intToFloat(f32, maxValue(u64)) < maxValue(f32));
assert(@intToFloat(f32, maxValue(u128)) == maxValue(f32));
assert(f64_max < maxValue(f64));
assert(maxValue(f16) == maxValue(f64));
assert(maxValue(f32) == maxValue(f64));
assert(maxValue(f64) == maxValue(f64));
assert(@intToFloat(f64, maxValue(i64)) < maxValue(f64));
assert(@intToFloat(f64, maxValue(u64)) < maxValue(f64));
assert(@intToFloat(f64, maxValue(u128)) < maxValue(f64));
}
test "maxminvalue.minValue.floats" {
assert(minValue(f16) < 0);
assert(minValue(f16) < maxValue(f16));
assert(@intToFloat(f16, minValue(i16)) > minValue(f16));
assert(@intToFloat(f16, minValue(i32)) == minValue(f16));
assert(@intToFloat(f16, minValue(i64)) == minValue(f16));
assert(@intToFloat(f16, minValue(i128)) == minValue(f16));
assert(minValue(f32) < 0);
assert(minValue(f32) < maxValue(f32));
assert(@intToFloat(f32, minValue(i16)) > minValue(f32));
assert(@intToFloat(f32, minValue(i32)) > minValue(f32));
assert(@intToFloat(f32, minValue(i64)) > minValue(f32));
assert(@intToFloat(f32, minValue(i128)) > minValue(f32));
assert(minValue(f64) < 0);
assert(minValue(f64) < maxValue(f64));
assert(@intToFloat(f64, minValue(i16)) > minValue(f64));
assert(@intToFloat(f64, minValue(i32)) > minValue(f64));
assert(@intToFloat(f64, minValue(i64)) > minValue(f64));
assert(@intToFloat(f64, minValue(i128)) > minValue(f64));
}
pub fn nonInfMaxValue(comptime T: type) T {
return switch (@typeId(T)) {
TypeId.Int => maxValue(T),
TypeId.Float => nonInfMaxFloat(T),
else => @compileError("Expecting type to be a float or int"),
};
}
test "maxminvalue.nonInfMaxValue" {
assert(nonInfMaxValue(u0) == maxValue(u0));
assert(nonInfMaxValue(i1) == maxValue(i1));
assert(nonInfMaxValue(u32) == maxValue(u32));
assert(nonInfMaxValue(i32) == maxValue(i32));
assert(nonInfMaxValue(u127) == maxValue(u127));
assert(nonInfMaxValue(i127) == maxValue(i127));
assert(nonInfMaxValue(u128) == maxValue(u128));
assert(nonInfMaxValue(i128) == maxValue(i128));
assert(nonInfMaxValue(f16) == f16_max);
assert(nonInfMaxValue(f32) == f32_max);
assert(nonInfMaxValue(f64) == f64_max);
}
pub fn nonInfMinValue(comptime T: type) T {
return switch (@typeId(T)) {
TypeId.Int => minValue(T),
TypeId.Float => nonInfMinFloat(T),
else => @compileError("Expecting type to be a float or int"),
};
}
test "maxminvalue.nonInfMinValue" {
assert(nonInfMinValue(u0) == minValue(u0));
assert(nonInfMinValue(i1) == minValue(i1));
assert(nonInfMinValue(u32) == minValue(u32));
assert(nonInfMinValue(i32) == minValue(i32));
assert(nonInfMinValue(u127) == minValue(u127));
assert(nonInfMinValue(u128) == minValue(u128));
assert(nonInfMinValue(f16) == -math.f16_max);
assert(nonInfMinValue(f32) == -math.f32_max);
assert(nonInfMinValue(f64) == -math.f64_max);
}
/// Numeric cast
pub fn numCast(comptime T: type, v: var) T {
const Tv = @typeOf(v);
return switch (@typeId(T)) {
TypeId.Float => switch (@typeId(Tv)) {
TypeId.ComptimeFloat, TypeId.Float => @floatCast(T, v),
TypeId.ComptimeInt, TypeId.Int => @intToFloat(T, v),
else => @compileError("Expected Float or Int type"),
},
TypeId.Int => switch (@typeId(Tv)) {
TypeId.ComptimeFloat, TypeId.Float => @floatToInt(T, v),
TypeId.ComptimeInt, TypeId.Int => @intCast(T, v),
else => @compileError("Expected Float or Int type"),
},
else => @compileError("Expected Float or Int type"),
};
}
test "numCast" {
var oneF32: f32 = 1.0;
var oneU32: u32 = 1;
assert(oneF32 == numCast(f32, oneU32));
assert(oneU32 == numCast(u32, oneF32));
assert(1 == @floatToInt(i65, oneF32));
assert(0 == numCast(u0, 0));
assert(0 == numCast(u1, 0));
assert(1 == numCast(u1, 1));
assert(1 == numCast(u128, 1));
assert(0 == numCast(i1, 0));
assert(-1 == numCast(i1, -1));
assert(0 == numCast(i128, 0));
assert(-1 == numCast(i128, -1));
assert(1 == numCast(f16, 1));
assert(1 == numCast(f32, 1));
assert(1 == numCast(f64, 1));
}
/// Saturating cast of numeric types.
pub fn saturateCast(comptime T: type, v: var) T {
const LargestFloatType = f64;
const LargestIntType = i128;
const LargestUintType = u128;
const Tv = @typeOf(v);
var paths: u64 = 0;
defer {
if (DBG) paths_accu = paths_accu | paths;
if (DBG) warn("paths_accu={x} paths={x}\n", paths_accu, paths);
}
// We have to special case u0
switch (T) {
u0 => {
if (DBG) paths = 0x1000000;
return 0;
},
else => {},
}
switch (Tv) {
u0 => {
if (DBG) paths = 0x0800000;
return 0;
},
else => {},
}
var r: T = 0;
switch (@typeId(T)) {
TypeId.Float => switch (@typeId(Tv)) {
TypeId.ComptimeFloat, TypeId.Float => {
if (v < 0.0) {
if (v >= nonInfMinValue(T)) {
if (DBG) paths = paths | 0x0000001;
r = numCast(T, v);
} else {
if (DBG) paths = paths | 0x0000002;
r = nonInfMinValue(T);
}
} else {
if (v <= nonInfMaxValue(T)) {
if (DBG) paths = paths | 0x0000004;
r = numCast(T, v);
} else {
if (DBG) paths = paths | 0x0000008;
r = nonInfMaxValue(T);
}
}
},
TypeId.ComptimeInt, TypeId.Int => {
var vFloat = @intToFloat(LargestFloatType, v);
if (v < 0) {
const minFloatT = @floatCast(LargestFloatType, nonInfMinValue(T));
if (vFloat >= minFloatT) {
if (DBG) paths = paths | 0x0000010;
r = numCast(T, v);
} else {
if (DBG) paths = paths | 0x0000020;
r = nonInfMinValue(T);
}
} else {
const maxFloatT = @floatCast(LargestFloatType, nonInfMaxValue(T));
if (vFloat <= maxFloatT) {
if (DBG) paths = paths | 0x0000040;
r = numCast(T, v);
} else {
if (DBG) paths = paths | 0x0000080;
r = nonInfMaxValue(T);
}
}
},
else => @compileError("Expected Float or Int type"),
},
TypeId.Int => switch (@typeId(Tv)) {
TypeId.ComptimeFloat, TypeId.Float => {
if (v < 0.0) {
const minFloatT = @intToFloat(LargestFloatType, nonInfMinValue(T));
if (v >= minFloatT) {
if (DBG) paths = paths | 0x0000100;
r = numCast(T, v);
} else {
if (DBG) paths = paths | 0x0000200;
r = nonInfMinValue(T);
}
} else {
const maxFloatT = @intToFloat(LargestFloatType, nonInfMaxValue(T));
if (v <= maxFloatT) {
if (DBG) paths = paths | 0x0000400;
r = numCast(T, v);
} else {
if (DBG) paths = paths | 0x0000800;
r = nonInfMaxValue(T);
}
}
},
TypeId.ComptimeInt, TypeId.Int => {
if (Tv.is_signed == T.is_signed) {
if (v < 0) {
if (v >= nonInfMinValue(T)) {
if (DBG) paths = paths | 0x0001000;
r = numCast(T, v);
} else {
if (DBG) paths = paths | 0x0002000;
r = nonInfMinValue(T);
}
} else {
if (v <= nonInfMaxValue(T)) {
if (DBG) paths = paths | 0x0004000;
r = numCast(T, v);
} else {
if (DBG) paths = paths | 0x0008000;
r = nonInfMaxValue(T);
}
}
} else if (Tv.is_signed) {
if (v < 0) {
if (DBG) paths = paths | 0x0010000;
r = 0;
} else {
if (T.bit_count >= Tv.bit_count) {
if (DBG) paths = paths | 0x0020000;
r = numCast(T, v);
} else {
if (v < numCast(Tv, nonInfMaxValue(T))) {
if (DBG) paths = paths | 0x0040000;
r = numCast(T, v);
} else {
if (DBG) paths = paths | 0x0080000;
r = nonInfMaxValue(T);
}
}
}
} else {
if (T.bit_count > Tv.bit_count) {
if (DBG) paths = paths | 0x0100000;
r = numCast(T, v);
} else {
if (v > numCast(Tv, nonInfMaxValue(T))) {
if (DBG) paths = paths | 0x0200000;
r = nonInfMaxValue(T);
} else {
if (DBG) paths = paths | 0x0400000;
r = numCast(T, v);
}
}
}
},
else => @compileError("Expected Float or Int type"),
},
else => @compileError("Expected Float or Int type"),
}
return r;
}
test "saturateCast.floats" {
if (DBG) warn("\n");
assert(f16(0) == saturateCast(f16, u0(0))); // 0x0400000
assert(f32(0) == saturateCast(f32, u0(0))); // 0x0400000
assert(f64(0) == saturateCast(f64, u0(0))); // 0x0400000
assert(f128(0) == saturateCast(f128, u0(0))); // 0x0400000
assert(nonInfMinValue(u0) == saturateCast(u0, minValue(f64))); // 0x0800000
assert(nonInfMinValue(u0) == saturateCast(u0, nonInfMinValue(f64))); // 0x0800000
assert(0 == saturateCast(u0, f64(-0.0))); // 0x0800000
assert(0 == saturateCast(u0, f64(0.0))); // 0x0800000
assert(0 == saturateCast(u0, f64(1))); // 0x0800000
assert(0 == saturateCast(u0, f64(1123))); // 0x0800000
assert(nonInfMaxValue(u0) == saturateCast(u0, nonInfMaxValue(f64))); // 0x0800000
assert(nonInfMaxValue(u0) == saturateCast(u0, maxValue(f64))); // 0x0800000
assert(-1000.123 == saturateCast(f32, f64(-1000.123))); // 0x0000001
assert(-1.0 == saturateCast(f32, f64(-1.0))); // 0x0000001
assert(nonInfMinValue(f64) == saturateCast(f64, nonInfMinValue(f64))); // 0x0000001
assert(-1000.123 == saturateCast(f64, f64(-1000.123))); // 0x0000001
assert(-1.0 == saturateCast(f64, f64(-1.0))); // 0x0000001
assert(nonInfMinValue(f32) == saturateCast(f32, minValue(f64))); // 0x0000002
assert(nonInfMinValue(f32) == saturateCast(f32, nonInfMinValue(f64))); // 0x0000002
assert(nonInfMinValue(f64) == saturateCast(f64, minValue(f64))); // 0x0000002
assert(-0.0 == saturateCast(f32, f64(-0.0))); // 0x0000004
assert(0.0 == saturateCast(f32, f64(0.0))); // 0x0000004
assert(1 == saturateCast(f32, f64(1))); // 0x0000004
assert(1000.123 == saturateCast(f32, f64(1000.123))); // 0x0000004
assert(-0.0 == saturateCast(f64, f64(-0.0))); // 0x0000004
assert(0.0 == saturateCast(f64, f64(0.0))); // 0x0000004
assert(1 == saturateCast(f64, f64(1))); // 0x0000004
assert(1000.123 == saturateCast(f64, f64(1000.123))); // 0x0000004
assert(nonInfMaxValue(f64) == saturateCast(f64, nonInfMaxValue(f64))); // 0x0000004
// $ zig test modules/zig-misc/src/maxmin_value.zig --test-filter saturateCast
// lld: error: undefined symbol: __truncdfhf2
// >>> referenced by maxmin_value.zig:233 (/home/wink/prgs/graphics/zig-3d-soft-engine/modules/zig-misc/src/maxmin_value.zig:233)
// >>> zig-cache/test.o:(numCast.107)
//assert(nonInfMaxValue(f16) == saturateCast(f16, maxValue(f64))); // 0x0000008 FAILS
assert(nonInfMaxValue(f32) == saturateCast(f32, nonInfMaxValue(f64))); // 0x0000008
assert(nonInfMaxValue(f32) == saturateCast(f32, maxValue(f64))); // 0x0000008
assert(nonInfMaxValue(f64) == saturateCast(f64, maxValue(f64))); // 0x0000008
assert(f32(-1) == saturateCast(f32, i2(-1))); // 0x0000010
assert(f64(math.minInt(i128)) == saturateCast(f64, i128(math.minInt(i128))));// 0x0000010
assert(f32(math.minInt(i128)) == saturateCast(f32, i128(math.minInt(i128))));// 0x0000010
assert(nonInfMinValue(f16) == saturateCast(f16, i128(math.minInt(i128)))); // 0x0000020
assert(f16(0) == saturateCast(f16, u1(0))); // 0x0000040
assert(f16(0) == saturateCast(f16, i2(0))); // 0x0000040
assert(f32(0) == saturateCast(f32, i32(0))); // 0x0000040
assert(f64(123) == saturateCast(f64, i64(123))); // 0x0000040
assert(f64(math.maxInt(i128)) == saturateCast(f32, i128(math.maxInt(i128))));// 0x0000040
assert(f64(math.maxInt(u128)) == saturateCast(f64, u128(math.maxInt(u128))));// 0x0000040
assert(-1 == saturateCast(i1, f64(-1.0))); // 0x0000080
assert(-1123 == saturateCast(i32, f64(-1123.9))); // 0x0000080
assert(-1 == saturateCast(i32, f64(-1.0))); // 0x0000080
assert(-1123 == saturateCast(i32, f64(-1123.1))); // 0x0000080
assert(-1123 == saturateCast(i128, f64(-1123.1))); // 0x0000080
assert(-1123 == saturateCast(i128, f64(-1123.9))); // 0x0000080
assert(-1 == saturateCast(i128, f64(-1.0))); // 0x0000080
assert(nonInfMaxValue(f16) == saturateCast(f16, u128(math.maxInt(u128))));// 0x0000080
assert(nonInfMaxValue(f32) == saturateCast(f32, u128(math.maxInt(u128))));// 0x0000080
assert(nonInfMinValue(i128) == saturateCast(i128, minValue(f64))); // 0x0000100
assert(nonInfMinValue(i128) == saturateCast(i128, nonInfMinValue(f64)));// 0x0000100
assert(nonInfMinValue(i1) == saturateCast(i1, minValue(f64))); // 0x0000100
assert(nonInfMinValue(i1) == saturateCast(i1, nonInfMinValue(f64))); // 0x0000100
assert(-1 == saturateCast(i1, f64(-1123.1))); // 0x0000100
assert(-1 == saturateCast(i1, f64(-1123.9))); // 0x0000100
assert(nonInfMinValue(i32) == saturateCast(i32, nonInfMinValue(f64))); // 0x0000100
assert(nonInfMinValue(i32) == saturateCast(i32, minValue(f64))); // 0x0000100
assert(nonInfMinValue(u1) == saturateCast(u1, minValue(f64))); // 0x0000100
assert(nonInfMinValue(u1) == saturateCast(u1, nonInfMinValue(f64))); // 0x0000100
assert(nonInfMinValue(u32) == saturateCast(u32, minValue(f64))); // 0x0000100
assert(nonInfMinValue(u32) == saturateCast(u32, nonInfMinValue(f64))); // 0x0000100
assert(nonInfMinValue(u128) == saturateCast(u128, minValue(f64))); // 0x0000100
assert(nonInfMinValue(u128) == saturateCast(u128, nonInfMinValue(f64)));// 0x0000100
assert(1123 == saturateCast(i32, f64(1123.9))); // 0x0000200
assert(0 == saturateCast(u1, f64(-0.0))); // 0x0000200
assert(0 == saturateCast(i1, f64(-0.0))); // 0x0000200
assert(0 == saturateCast(i1, f64(0.0))); // 0x0000200
assert(0 == saturateCast(i32, f64(-0.0))); // 0x0000200
assert(0 == saturateCast(i32, f64(0.0))); // 0x0000200
assert(1 == saturateCast(i32, f64(1))); // 0x0000200
assert(1123 == saturateCast(i32, f64(1123.1))); // 0x0000200
assert(1123 == saturateCast(i32, f64(1123.9))); // 0x0000200
assert(0 == saturateCast(u32, f64(-0.0))); // 0x0000200
assert(0 == saturateCast(u32, f64(0.0))); // 0x0000200
assert(1 == saturateCast(u32, f64(1))); // 0x0000200
assert(1123 == saturateCast(u32, f64(1123))); // 0x0000200
assert(0 == saturateCast(u128, f64(-0.0))); // 0x0000200
assert(0 == saturateCast(u128, f64(0.0))); // 0x0000200
assert(1 == saturateCast(u128, f64(1))); // 0x0000200
assert(1123 == saturateCast(u128, f64(1123))); // 0x0000200
// Fixed with ziglang/zig PR #1820 (https://github.com/ziglang/zig/pull/1820) if and when it gets merged
// Compiler bug for any i65..i128
// $ zig test modules/zig-misc/src/maxmin_value.zig
// lld: error: undefined symbol: __fixdfti
// >>> referenced by maxmin_value.zig:237 (/home/wink/prgs/graphics/zig-3d-soft-engine/modules/zig-misc/src/maxmin_value.zig:237)
// >>> zig-cache/test.o:(numCast.104)
assert(1 == saturateCast(i65, f64(1.0))); // 0x0000200
assert(1 == saturateCast(i128, f64(1.0))); // 0x0000200
assert(0 == saturateCast(i128, f64(-0.0))); // 0x0000200
assert(0 == saturateCast(i128, f64(0.0))); // 0x0000200
assert(1 == saturateCast(i128, f64(1.0))); // 0x0000200
assert(1123 == saturateCast(i128, f64(1123.1))); // 0x0000200
assert(1123 == saturateCast(i128, f64(1123.9))); // 0x0000200
assert(0 == saturateCast(u1, f64(0.0))); // 0x0000200
assert(1 == saturateCast(u1, f64(1))); // 0x0000200
assert(1 == saturateCast(u1, f64(1123))); // 0x0000400
assert(1 == saturateCast(u1, f64(1123.9))); // 0x0000400
assert(0 == saturateCast(i1, f64(1))); // 0x0000400
assert(0 == saturateCast(i1, f64(1123.1))); // 0x0000400
assert(0 == saturateCast(i1, f64(1123.9))); // 0x0000400
assert(nonInfMaxValue(i1) == saturateCast(i1, nonInfMaxValue(f64))); // 0x0000400
assert(nonInfMaxValue(i1) == saturateCast(i1, maxValue(f64))); // 0x0000400
assert(nonInfMaxValue(i32) == saturateCast(i32, nonInfMaxValue(f64))); // 0x0000400
assert(nonInfMaxValue(i32) == saturateCast(i32, maxValue(f64))); // 0x0000400
assert(nonInfMaxValue(i32) == saturateCast(i32, maxValue(f64))); // 0x0000400
assert(nonInfMaxValue(i128) == saturateCast(i128, nonInfMaxValue(f64)));// 0x0000400
assert(nonInfMaxValue(i128) == saturateCast(i128, maxValue(f64))); // 0x0000400
assert(nonInfMaxValue(u1) == saturateCast(u1, nonInfMaxValue(f64))); // 0x0000400
assert(nonInfMaxValue(u1) == saturateCast(u1, maxValue(f64))); // 0x0000400
assert(nonInfMaxValue(u32) == saturateCast(u32, nonInfMaxValue(f64))); // 0x0000400
assert(nonInfMaxValue(u32) == saturateCast(u32, maxValue(f64))); // 0x0000400
assert(nonInfMaxValue(u128) == saturateCast(u128, nonInfMaxValue(f64)));// 0x0000400
assert(nonInfMaxValue(u128) == saturateCast(u128, maxValue(f64))); // 0x0000400
}
test "saturateCast.ints" {
if (DBG) warn("\n");
// u0 special case
assert(u1(0) == saturateCast(u1, u0(0))); // 0x0400000
assert(u0(0) == saturateCast(u0, i8(127))); // 0x0800000
assert(u0(0) == saturateCast(u0, i8(-128))); // 0x0800000
// signs equal
assert(i1(-1) == saturateCast(i1, i1(-1))); // 0x0001000
assert(i8(-128) == saturateCast(i8, i8(-128))); // 0x0001000
assert(i8(-64) == saturateCast(i8, i7(-64))); // 0x0001000
assert(i1(-1) == saturateCast(i1, i8(-128))); // 0x0002000
assert(i7(-64) == saturateCast(i7, i8(-128))); // 0x0002000
assert(u8(0) == saturateCast(u8, u8(0))); // 0x0004000
assert(u8(255) == saturateCast(u8, u8(255))); // 0x0004000
assert(u7(0) == saturateCast(u7, u8(0))); // 0x0004000
assert(u8(0) == saturateCast(u8, u7(0))); // 0x0004000
assert(u8(127) == saturateCast(u8, u7(127))); // 0x0004000
assert(i1(0) == saturateCast(i1, i1(0))); // 0x0004000
assert(i8(0) == saturateCast(i8, i8(0))); // 0x0004000
assert(i8(127) == saturateCast(i8, i8(127))); // 0x0004000
assert(i7(0) == saturateCast(i7, i8(0))); // 0x0004000
assert(i8(0) == saturateCast(i8, i7(0))); // 0x0004000
assert(i8(63) == saturateCast(i8, i7(63))); // 0x0004000
assert(u7(127) == saturateCast(u7, u8(255))); // 0x0008000
assert(i1(0) == saturateCast(i1, i8(1))); // 0x0008000
assert(i7(63) == saturateCast(i7, i8(127))); // 0x0008000
// signs != v is signed
assert(u1(0) == saturateCast(u1, i8(-128))); // 0x0010000
assert(u7(0) == saturateCast(u7, i8(-128))); // 0x0010000
assert(u128(0) == saturateCast(u128, i8(-128)));// 0x0010000
assert(u8(0) == saturateCast(u8, i8(0))); // 0x0020000
assert(u128(127) == saturateCast(u128, i8(127)));// 0x0020000
assert(u8(127) == saturateCast(u8, i8(127))); // 0x0020000
assert(u128(0) == saturateCast(u128, i8(0))); // 0x0020000
assert(u128(0) == saturateCast(u128, i8(0))); // 0x0020000
assert(u128(math.maxInt(i128)) == saturateCast(u128, i128(math.maxInt(i128)))); // 0x0020000
assert(u1(0) == saturateCast(u1, i8(0))); // 0x0040000
assert(u7(0) == saturateCast(u7, i8(0))); // 0x0040000
assert(u7(127) == saturateCast(u7, i8(127))); // 0x0080000
assert(u1(1) == saturateCast(u1, i8(127))); // 0x0080000
assert(u6(63) == saturateCast(u6, i8(127))); // 0x0080000
assert(u7(127) == saturateCast(u7, i8(127))); // 0x0080000
assert(u8(255) == saturateCast(u8, i9(255))); // 0x0080000
// signs != v is unsigned
assert(i8(0) == saturateCast(i8, u7(0))); // 0x0100000
assert(i8(127) == saturateCast(i8, u7(127))); // 0x0100000
assert(i128(255) == saturateCast(i128, u8(255)));// 0x0100000
assert(i1(0) == saturateCast(i1, u8(127))); // 0x0200000
assert(i7(63) == saturateCast(i7, u8(128))); // 0x0200000
assert(i8(127) == saturateCast(i8, u8(255))); // 0x0200000
assert(i8(127) == saturateCast(i8, u9(256))); // 0x0200000
assert(i1(0) == saturateCast(i1, u128(math.maxInt(u128)))); // 0x0200000
assert(i1(0) == saturateCast(i1, u1(0))); // 0x0400000
assert(i1(0) == saturateCast(i1, u8(0))); // 0x0400000
assert(i7(0) == saturateCast(i7, u8(0))); // 0x0400000
assert(i7(1) == saturateCast(i7, u8(1))); // 0x0400000
} | src/maxmin_value.zig |
const std = @import("std");
const assert = std.debug.assert;
const mem = std.mem;
const os = std.os;
const config = @import("config.zig");
const log = std.log.scoped(.message_bus);
const vr = @import("vr.zig");
const Header = vr.Header;
const Journal = vr.Journal;
const Replica = vr.Replica;
const Client = @import("client.zig").Client;
const RingBuffer = @import("ring_buffer.zig").RingBuffer;
const IO = @import("io.zig").IO;
const MessagePool = @import("message_pool.zig").MessagePool;
pub const Message = MessagePool.Message;
const SendQueue = RingBuffer(*Message, config.connection_send_queue_max);
pub const MessageBusReplica = MessageBusImpl(.replica);
pub const MessageBusClient = MessageBusImpl(.client);
const ProcessType = enum { replica, client };
fn MessageBusImpl(comptime process_type: ProcessType) type {
return struct {
const Self = @This();
pool: MessagePool,
io: *IO,
cluster: u128,
configuration: []std.net.Address,
/// The Replica or Client process that will receive messages from this Self.
process: switch (process_type) {
.replica => struct {
replica: *Replica,
/// Used to store messages sent by a process to itself for delivery in flush().
send_queue: SendQueue = .{},
/// The file descriptor for the process on which to accept connections.
accept_fd: os.socket_t,
accept_completion: IO.Completion = undefined,
/// The connection reserved for the currently in progress accept operation.
/// This is non-null exactly when an accept operation is submitted.
accept_connection: ?*Connection = null,
/// Map from client id to the currently active connection for that client.
/// This is used to make lookup of client connections when sending messages
/// efficient and to ensure old client connections are dropped if a new one
/// is established.
clients: std.AutoHashMapUnmanaged(u128, *Connection) = .{},
},
.client => struct {
client: *Client,
},
},
/// This slice is allocated with a fixed size in the init function and never reallocated.
connections: []Connection,
/// Number of connections currently in use (i.e. connection.peer != .none).
connections_used: usize = 0,
/// Map from replica index to the currently active connection for that replica, if any.
/// The connection for the process replica if any will always be null.
replicas: []?*Connection,
/// The number of outgoing `connect()` attempts for a given replica:
/// Reset to zero after a successful `on_connect()`.
replicas_connect_attempts: []u4,
/// Used to apply full jitter when calculating exponential backoff:
/// Seeded with the process' replica index or client ID.
prng: std.rand.DefaultPrng,
/// Initialize the Self for the given cluster, configuration and replica/client process.
pub fn init(
allocator: *mem.Allocator,
cluster: u128,
configuration: []std.net.Address,
process: switch (process_type) {
.replica => u16,
.client => u128,
},
io: *IO,
) !Self {
// There must be enough connections for all replicas and at least one client.
assert(config.connections_max > configuration.len);
const connections = try allocator.alloc(Connection, config.connections_max);
errdefer allocator.free(connections);
mem.set(Connection, connections, .{});
const replicas = try allocator.alloc(?*Connection, configuration.len);
errdefer allocator.free(replicas);
mem.set(?*Connection, replicas, null);
const replicas_connect_attempts = try allocator.alloc(u4, configuration.len);
errdefer allocator.free(replicas_connect_attempts);
mem.set(u4, replicas_connect_attempts, 0);
const prng_seed = switch (process_type) {
.replica => process,
.client => @truncate(u64, process),
};
var self: Self = .{
.pool = try MessagePool.init(allocator),
.io = io,
.cluster = cluster,
.configuration = configuration,
.process = switch (process_type) {
.replica => .{
.replica = undefined,
.accept_fd = try init_tcp(configuration[process]),
},
.client => .{ .client = undefined },
},
.connections = connections,
.replicas = replicas,
.replicas_connect_attempts = replicas_connect_attempts,
.prng = std.rand.DefaultPrng.init(prng_seed),
};
// Pre-allocate enough memory to hold all possible connections in the client map.
if (process_type == .replica) {
try self.process.clients.ensureCapacity(allocator, config.connections_max);
}
return self;
}
/// TODO This is required by the Client.
pub fn deinit(self: *Self) void {}
fn init_tcp(address: std.net.Address) !os.socket_t {
const fd = try os.socket(
address.any.family,
os.SOCK_STREAM | os.SOCK_CLOEXEC,
os.IPPROTO_TCP,
);
errdefer os.close(fd);
const set = struct {
fn set(_fd: os.socket_t, level: u32, option: u32, value: c_int) !void {
try os.setsockopt(_fd, level, option, &mem.toBytes(value));
}
}.set;
try set(fd, os.SOL_SOCKET, os.SO_REUSEADDR, 1);
if (config.tcp_rcvbuf > 0) {
// Requires CAP_NET_ADMIN privilege (settle for SO_RCVBUF in the event of an EPERM):
set(fd, os.SOL_SOCKET, os.SO_RCVBUFFORCE, config.tcp_rcvbuf) catch |err| {
switch (err) {
error.PermissionDenied => {
try set(fd, os.SOL_SOCKET, os.SO_RCVBUF, config.tcp_rcvbuf);
},
else => return err,
}
};
}
if (config.tcp_sndbuf > 0) {
// Requires CAP_NET_ADMIN privilege (settle for SO_SNDBUF in the event of an EPERM):
set(fd, os.SOL_SOCKET, os.SO_SNDBUFFORCE, config.tcp_sndbuf) catch |err| {
switch (err) {
error.PermissionDenied => {
try set(fd, os.SOL_SOCKET, os.SO_SNDBUF, config.tcp_sndbuf);
},
else => return err,
}
};
}
if (config.tcp_keepalive) {
try set(fd, os.SOL_SOCKET, os.SO_KEEPALIVE, 1);
try set(fd, os.IPPROTO_TCP, os.TCP_KEEPIDLE, config.tcp_keepidle);
try set(fd, os.IPPROTO_TCP, os.TCP_KEEPINTVL, config.tcp_keepintvl);
try set(fd, os.IPPROTO_TCP, os.TCP_KEEPCNT, config.tcp_keepcnt);
}
if (config.tcp_user_timeout > 0) {
try set(fd, os.IPPROTO_TCP, os.TCP_USER_TIMEOUT, config.tcp_user_timeout);
}
if (config.tcp_nodelay) {
try set(fd, os.IPPROTO_TCP, os.TCP_NODELAY, 1);
}
try os.bind(fd, &address.any, address.getOsSockLen());
try os.listen(fd, config.tcp_backlog);
return fd;
}
pub fn tick(self: *Self) void {
switch (process_type) {
.replica => {
// Each replica is responsible for connecting to replicas that come
// after it in the configuration. This ensures that replicas never try
// to connect to each other at the same time.
var replica: u16 = self.process.replica.replica + 1;
while (replica < self.replicas.len) : (replica += 1) {
self.maybe_connect_to_replica(replica);
}
// Only replicas accept connections from other replicas and clients:
self.maybe_accept();
// Even though we call this after delivering all messages received over
// a socket, it is necessary to call here as well in case a replica sends
// a message to itself in Replica.tick().
self.flush_send_queue();
},
.client => {
// The client connects to all replicas.
var replica: u16 = 0;
while (replica < self.replicas.len) : (replica += 1) {
self.maybe_connect_to_replica(replica);
}
},
}
}
fn maybe_connect_to_replica(self: *Self, replica: u16) void {
// We already have a connection to the given replica.
if (self.replicas[replica] != null) {
assert(self.connections_used > 0);
return;
}
// Obtain a connection struct for our new replica connection.
// If there is a free connection, use that. Otherwise drop
// a client or unknown connection to make space. Prefer dropping
// a client connection to an unknown one as the unknown peer may
// be a replica. Since shutting a connection down does not happen
// instantly, simply return after starting the shutdown and try again
// on the next tick().
for (self.connections) |*connection| {
if (connection.state == .free) {
assert(connection.peer == .none);
// This will immediately add the connection to self.replicas,
// or else will return early if a socket file descriptor cannot be obtained:
// TODO See if we can clean this up to remove/expose the early return branch.
connection.connect_to_replica(self, replica);
return;
}
}
// If there is already a connection being shut down, no need to kill another.
for (self.connections) |*connection| {
if (connection.state == .terminating) return;
}
log.notice("all connections in use but not all replicas are connected, " ++
"attempting to disconnect a client", .{});
for (self.connections) |*connection| {
if (connection.peer == .client) {
connection.terminate(self, .shutdown);
return;
}
}
log.notice("failed to disconnect a client as no peer was a known client, " ++
"attempting to disconnect an unknown peer.", .{});
for (self.connections) |*connection| {
if (connection.peer == .unknown) {
connection.terminate(self, .shutdown);
return;
}
}
// We assert that the max number of connections is greater
// than the number of replicas in init().
unreachable;
}
fn maybe_accept(self: *Self) void {
comptime assert(process_type == .replica);
if (self.process.accept_connection != null) return;
// All connections are currently in use, do nothing.
if (self.connections_used == self.connections.len) return;
assert(self.connections_used < self.connections.len);
self.process.accept_connection = for (self.connections) |*connection| {
if (connection.state == .free) {
assert(connection.peer == .none);
connection.state = .accepting;
break connection;
}
} else unreachable;
self.io.accept(
*Self,
self,
on_accept,
&self.process.accept_completion,
self.process.accept_fd,
os.SOCK_CLOEXEC,
);
}
fn on_accept(
self: *Self,
completion: *IO.Completion,
result: IO.AcceptError!os.socket_t,
) void {
comptime assert(process_type == .replica);
assert(self.process.accept_connection != null);
defer self.process.accept_connection = null;
const fd = result catch |err| {
self.process.accept_connection.?.state = .free;
// TODO: some errors should probably be fatal
log.err("accept failed: {}", .{err});
return;
};
self.process.accept_connection.?.on_accept(self, fd);
}
pub fn get_message(self: *Self) ?*Message {
return self.pool.get_message();
}
pub fn unref(self: *Self, message: *Message) void {
self.pool.unref(message);
}
/// Returns true if the target replica is connected and has space in its send queue.
pub fn can_send_to_replica(self: *Self, replica: u16) bool {
if (process_type == .replica and replica == self.process.replica.replica) {
return !self.process.send_queue.full();
} else {
const connection = self.replicas[replica] orelse return false;
return connection.state == .connected and !connection.send_queue.full();
}
}
pub fn send_header_to_replica(self: *Self, replica: u16, header: Header) void {
assert(header.size == @sizeOf(Header));
if (!self.can_send_to_replica(replica)) {
log.debug("cannot send to replica {}, dropping", .{replica});
return;
}
const message = self.pool.get_header_only_message() orelse {
log.debug("no header only message available, " ++
"dropping message to replica {}", .{replica});
return;
};
defer self.unref(message);
message.header.* = header;
const body = message.buffer[@sizeOf(Header)..message.header.size];
// The order matters here because checksum depends on checksum_body:
message.header.set_checksum_body(body);
message.header.set_checksum();
self.send_message_to_replica(replica, message);
}
pub fn send_message_to_replica(self: *Self, replica: u16, message: *Message) void {
// Messages sent by a process to itself are delivered directly in flush():
if (process_type == .replica and replica == self.process.replica.replica) {
self.process.send_queue.push(message.ref()) catch |err| switch (err) {
error.NoSpaceLeft => {
self.unref(message);
log.notice("process' message queue full, dropping message", .{});
},
};
} else if (self.replicas[replica]) |connection| {
connection.send_message(self, message);
} else {
log.debug("no active connection to replica {}, " ++
"dropping message with header {}", .{ replica, message.header });
}
}
pub fn send_header_to_client(self: *Self, client_id: u128, header: Header) void {
assert(header.size == @sizeOf(Header));
// TODO Do not allocate a message if we know we cannot send to the client.
const message = self.pool.get_header_only_message() orelse {
log.debug("no header only message available, " ++
"dropping message to client {}", .{client_id});
return;
};
defer self.unref(message);
message.header.* = header;
const body = message.buffer[@sizeOf(Header)..message.header.size];
// The order matters here because checksum depends on checksum_body:
message.header.set_checksum_body(body);
message.header.set_checksum();
self.send_message_to_client(client_id, message);
}
/// Try to send the message to the client with the given id.
/// If the client is not currently connected, the message is silently dropped.
pub fn send_message_to_client(self: *Self, client_id: u128, message: *Message) void {
comptime assert(process_type == .replica);
if (self.process.clients.get(client_id)) |connection| {
connection.send_message(self, message);
} else {
log.debug("no connection to client {x}", .{client_id});
}
}
/// Deliver messages the replica has sent to itself.
pub fn flush_send_queue(self: *Self) void {
comptime assert(process_type == .replica);
// There are currently 3 cases in which a replica will send a message to itself:
// 1. In on_request, the leader sends a prepare to itself, and
// subsequent prepare timeout retries will never resend to self.
// 2. In on_prepare, after writing to storage, the leader sends a
// prepare_ok back to itself.
// 3. In on_start_view_change, after receiving a quorum of start_view_change
// messages, the new leader sends a do_view_change to itself.
// Therefore we should never enter an infinite loop here. To catch the case in which we
// do so that we can learn from it, assert that we never iterate more than 100 times.
var i: usize = 0;
while (i < 100) : (i += 1) {
if (self.process.send_queue.empty()) return;
var copy = self.process.send_queue;
self.process.send_queue = .{};
while (copy.pop()) |message| {
defer self.unref(message);
// TODO Rewrite ConcurrentRanges to not use async:
// This nosuspend is only safe because we do not do any async disk IO yet.
nosuspend await async self.process.replica.on_message(message);
}
}
unreachable;
}
/// Calculates exponential backoff with full jitter according to the formula:
/// `sleep = random_between(0, min(cap, base * 2 ** attempt))`
///
/// `attempt` is zero-based.
/// `attempt` is tracked as a u4 to flush out any overflow bugs sooner rather than later.
pub fn exponential_backoff_with_full_jitter_in_ms(self: *Self, attempt: u4) u63 {
assert(config.connection_delay_min < config.connection_delay_max);
// Calculate the capped exponential backoff component: `min(cap, base * 2 ** attempt)`
const base: u63 = config.connection_delay_min;
const cap: u63 = config.connection_delay_max - config.connection_delay_min;
const exponential_backoff = std.math.min(
cap,
// A "1" shifted left gives any power of two:
// 1<<0 = 1, 1<<1 = 2, 1<<2 = 4, 1<<3 = 8:
base * std.math.shl(u63, 1, attempt),
);
const jitter = self.prng.random.uintAtMostBiased(u63, exponential_backoff);
const ms = base + jitter;
assert(ms >= config.connection_delay_min);
assert(ms <= config.connection_delay_max);
return ms;
}
/// Used to send/receive messages to/from a client or fellow replica.
const Connection = struct {
/// The peer is determined by inspecting the first message header
/// received.
peer: union(enum) {
/// No peer is currently connected.
none: void,
/// A connection is established but an unambiguous header has not yet been received.
unknown: void,
/// The peer is a client with the given id.
client: u128,
/// The peer is a replica with the given id.
replica: u16,
} = .none,
state: enum {
/// The connection is not in use, with peer set to `.none`.
free,
/// The connection has been reserved for an in progress accept operation,
/// with peer set to `.none`.
accepting,
/// The peer is a replica and a connect operation has been started
/// but not yet competed.
connecting,
/// The peer is fully connected and may be a client, replica, or unknown.
connected,
/// The connection is being terminated but cleanup has not yet finished.
terminating,
} = .free,
/// This is guaranteed to be valid only while state is connected.
/// It will be reset to -1 during the shutdown process and is always -1 if the
/// connection is unused (i.e. peer == .none). We use -1 instead of undefined here
/// for safety to ensure an error if the invalid value is ever used, instead of
/// potentially performing an action on an active fd.
fd: os.socket_t = -1,
/// This completion is used for all recv operations.
/// It is also used for the initial connect when establishing a replica connection.
recv_completion: IO.Completion = undefined,
/// True exactly when the recv_completion has been submitted to the IO abstraction
/// but the callback has not yet been run.
recv_submitted: bool = false,
/// The Message with the buffer passed to the kernel for recv operations.
recv_message: ?*Message = null,
/// The number of bytes in `recv_message` that have been received and need parsing.
recv_progress: usize = 0,
/// The number of bytes in `recv_message` that have been parsed.
recv_parsed: usize = 0,
/// True if we have already checked the header checksum of the message we
/// are currently receiving/parsing.
recv_checked_header: bool = false,
/// This completion is used for all send operations.
send_completion: IO.Completion = undefined,
/// True exactly when the send_completion has been submitted to the IO abstraction
/// but the callback has not yet been run.
send_submitted: bool = false,
/// Number of bytes of the current message that have already been sent.
send_progress: usize = 0,
/// The queue of messages to send to the client or replica peer.
send_queue: SendQueue = .{},
/// Attempt to connect to a replica.
/// The slot in the Message.replicas slices is immediately reserved.
/// Failure is silent and returns the connection to an unused state.
pub fn connect_to_replica(self: *Connection, bus: *Self, replica: u16) void {
if (process_type == .replica) assert(replica != bus.process.replica.replica);
assert(self.peer == .none);
assert(self.state == .free);
assert(self.fd == -1);
// The first replica's network address family determines the
// family for all other replicas:
const family = bus.configuration[0].any.family;
self.fd = os.socket(family, os.SOCK_STREAM | os.SOCK_CLOEXEC, 0) catch return;
self.peer = .{ .replica = replica };
self.state = .connecting;
bus.connections_used += 1;
assert(bus.replicas[replica] == null);
bus.replicas[replica] = self;
var attempts = &bus.replicas_connect_attempts[replica];
const ms = bus.exponential_backoff_with_full_jitter_in_ms(attempts.*);
// Saturate the counter at its maximum value if the addition wraps:
attempts.* +%= 1;
if (attempts.* == 0) attempts.* -%= 1;
log.debug("connecting to replica {} in {}ms...", .{ self.peer.replica, ms });
assert(!self.recv_submitted);
self.recv_submitted = true;
bus.io.timeout(
*Self,
bus,
on_connect_with_exponential_backoff,
// We use `recv_completion` for the connection `timeout()` and `connect()` calls
&self.recv_completion,
ms * std.time.ns_per_ms,
);
}
fn on_connect_with_exponential_backoff(
bus: *Self,
completion: *IO.Completion,
result: IO.TimeoutError!void,
) void {
const self = @fieldParentPtr(Connection, "recv_completion", completion);
assert(self.recv_submitted);
self.recv_submitted = false;
if (self.state == .terminating) {
self.maybe_close(bus);
return;
}
assert(self.state == .connecting);
result catch unreachable;
log.debug("connecting to replica {}...", .{self.peer.replica});
assert(!self.recv_submitted);
self.recv_submitted = true;
bus.io.connect(
*Self,
bus,
on_connect,
// We use `recv_completion` for the connection `timeout()` and `connect()` calls
&self.recv_completion,
self.fd,
bus.configuration[self.peer.replica],
);
}
fn on_connect(
bus: *Self,
completion: *IO.Completion,
result: IO.ConnectError!void,
) void {
const self = @fieldParentPtr(Connection, "recv_completion", completion);
assert(self.recv_submitted);
self.recv_submitted = false;
if (self.state == .terminating) {
self.maybe_close(bus);
return;
}
assert(self.state == .connecting);
self.state = .connected;
result catch |err| {
log.err("error connecting to replica {}: {}", .{ self.peer.replica, err });
self.terminate(bus, .close);
return;
};
log.info("connected to replica {}", .{self.peer.replica});
bus.replicas_connect_attempts[self.peer.replica] = 0;
self.assert_recv_send_initial_state(bus);
// This will terminate the connection if there are no messages available:
self.get_recv_message_and_recv(bus);
// A message may have been queued for sending while we were connecting:
// TODO Should we relax recv() and send() to return if `self.state != .connected`?
if (self.state == .connected) self.send(bus);
}
/// Given a newly accepted fd, start receiving messages on it.
/// Callbacks will be continuously re-registered until terminate() is called.
pub fn on_accept(self: *Connection, bus: *Self, fd: os.socket_t) void {
assert(self.peer == .none);
assert(self.state == .accepting);
assert(self.fd == -1);
self.peer = .unknown;
self.state = .connected;
self.fd = fd;
bus.connections_used += 1;
self.assert_recv_send_initial_state(bus);
self.get_recv_message_and_recv(bus);
assert(self.send_queue.empty());
}
fn assert_recv_send_initial_state(self: *Connection, bus: *Self) void {
assert(bus.connections_used > 0);
assert(self.peer == .unknown or self.peer == .replica);
assert(self.state == .connected);
assert(self.fd != -1);
assert(self.recv_submitted == false);
assert(self.recv_message == null);
assert(self.recv_progress == 0);
assert(self.recv_parsed == 0);
assert(self.send_submitted == false);
assert(self.send_progress == 0);
}
/// Add a message to the connection's send queue, starting a send operation
/// if the queue was previously empty.
pub fn send_message(self: *Connection, bus: *Self, message: *Message) void {
assert(self.peer == .client or self.peer == .replica);
switch (self.state) {
.connected, .connecting => {},
.terminating => return,
.free, .accepting => unreachable,
}
self.send_queue.push(message.ref()) catch |err| switch (err) {
error.NoSpaceLeft => {
bus.unref(message);
log.notice("message queue for peer {} full, dropping message", .{
self.peer,
});
return;
},
};
// If the connection has not yet been established we can't send yet.
// Instead on_connect() will call send().
if (self.state == .connecting) {
assert(self.peer == .replica);
return;
}
// If there is no send operation currently in progress, start one.
if (!self.send_submitted) self.send(bus);
}
/// Clean up an active connection and reset it to its initial, unused, state.
/// This reset does not happen instantly as currently in progress operations
/// must first be stopped. The `how` arg allows the caller to specify if a
/// shutdown syscall should be made or not before proceeding to wait for
/// currently in progress operations to complete and close the socket.
/// I'll be back! (when the Connection is reused after being fully closed)
pub fn terminate(self: *Connection, bus: *Self, how: enum { shutdown, close }) void {
assert(self.peer != .none);
assert(self.state != .free);
assert(self.fd != -1);
switch (how) {
.shutdown => {
// The shutdown syscall will cause currently in progress send/recv
// operations to be gracefully closed while keeping the fd open.
const rc = os.linux.shutdown(self.fd, os.SHUT_RDWR);
switch (os.errno(rc)) {
0 => {},
os.EBADF => unreachable,
os.EINVAL => unreachable,
os.ENOTCONN => {
// This should only happen if we for some reason decide to terminate
// a connection while a connect operation is in progress.
// This is fine though, we simply continue with the logic below and
// wait for the connect operation to finish.
// TODO: This currently happens in other cases if the
// connection was closed due to an error. We need to intelligently
// decide whether to shutdown or close directly based on the error
// before these assertions may be re-enabled.
//assert(self.state == .connecting);
//assert(self.recv_submitted);
//assert(!self.send_submitted);
},
os.ENOTSOCK => unreachable,
else => |err| os.unexpectedErrno(err) catch {},
}
},
.close => {},
}
assert(self.state != .terminating);
self.state = .terminating;
self.maybe_close(bus);
}
fn parse_messages(self: *Connection, bus: *Self) void {
assert(self.peer != .none);
assert(self.state == .connected);
assert(self.fd != -1);
while (self.parse_message(bus)) |message| {
defer bus.unref(message);
self.on_message(bus, message);
}
}
fn parse_message(self: *Connection, bus: *Self) ?*Message {
const data = self.recv_message.?.buffer[self.recv_parsed..self.recv_progress];
if (data.len < @sizeOf(Header)) {
self.get_recv_message_and_recv(bus);
return null;
}
const header = mem.bytesAsValue(Header, data[0..@sizeOf(Header)]);
if (!self.recv_checked_header) {
if (!header.valid_checksum()) {
log.err("invalid header checksum received from {}", .{self.peer});
self.terminate(bus, .shutdown);
return null;
}
if (header.size < @sizeOf(Header) or header.size > config.message_size_max) {
log.err("header with invalid size {d} received from peer {}", .{
header.size,
self.peer,
});
self.terminate(bus, .shutdown);
return null;
}
if (header.cluster != bus.cluster) {
log.err("message addressed to the wrong cluster: {}", .{header.cluster});
self.terminate(bus, .shutdown);
return null;
}
switch (process_type) {
// Replicas may forward messages from clients or from other replicas so we
// may receive messages from a peer before we know who they are:
// This has the same effect as an asymmetric network where, for a short time
// bounded by the time it takes to ping, we can hear from a peer before we
// can send back to them.
.replica => self.maybe_set_peer(bus, header),
// The client connects only to replicas and should set peer when connecting:
.client => assert(self.peer == .replica),
}
self.recv_checked_header = true;
}
if (data.len < header.size) {
self.get_recv_message_and_recv(bus);
return null;
}
// At this point we know that we have the full message in our buffer.
// We will now either deliver this message or terminate the connection
// due to an error, so reset recv_checked_header for the next message.
assert(self.recv_checked_header);
self.recv_checked_header = false;
const body = data[@sizeOf(Header)..header.size];
if (!header.valid_checksum_body(body)) {
log.err("invalid body checksum received from {}", .{self.peer});
self.terminate(bus, .shutdown);
return null;
}
self.recv_parsed += header.size;
// Return the parsed message using zero-copy if we can, or copy if the client is
// pipelining:
// If this is the first message but there are messages in the pipeline then we
// copy the message so that its sector padding (if any) will not overwrite the
// front of the pipeline. If this is not the first message then we must copy
// the message to a new message as each message needs to have its own unique
// `references` and `header` metadata.
if (self.recv_progress == header.size) return self.recv_message.?.ref();
const message = bus.get_message() orelse {
// TODO Decrease the probability of this happening by:
// 1. using a header-only message if possible.
// 2. determining a true upper limit for static allocation.
log.err("no free buffer available to deliver message from {}", .{self.peer});
self.terminate(bus, .shutdown);
return null;
};
mem.copy(u8, message.buffer, data[0..header.size]);
return message;
}
/// Forward a received message to `Process.on_message()`.
/// Zero any `.prepare` sector padding up to the nearest sector multiple after the body.
fn on_message(self: *Connection, bus: *Self, message: *Message) void {
if (message == self.recv_message.?) {
assert(self.recv_parsed == message.header.size);
assert(self.recv_parsed == self.recv_progress);
} else if (self.recv_parsed == message.header.size) {
assert(self.recv_parsed < self.recv_progress);
} else {
assert(self.recv_parsed > message.header.size);
assert(self.recv_parsed <= self.recv_progress);
}
if (message.header.command == .request or message.header.command == .prepare) {
const sector_ceil = Journal.sector_ceil(message.header.size);
if (message.header.size != sector_ceil) {
assert(message.header.size < sector_ceil);
assert(message.buffer.len == config.message_size_max + config.sector_size);
mem.set(u8, message.buffer[message.header.size..sector_ceil], 0);
}
}
switch (process_type) {
.replica => {
// TODO Rewrite ConcurrentRanges to not use async:
// This nosuspend is only safe because we do not do any async disk IO yet.
nosuspend await async bus.process.replica.on_message(message);
// Flush any messages queued by `process.on_message()` above immediately:
// This optimization is critical for throughput, otherwise messages from a
// process to itself would be delayed until the next `tick()`.
bus.flush_send_queue();
},
.client => bus.process.client.on_message(message),
}
}
fn maybe_set_peer(self: *Connection, bus: *Self, header: *const Header) void {
comptime assert(process_type == .replica);
assert(bus.cluster == header.cluster);
assert(bus.connections_used > 0);
assert(self.peer != .none);
assert(self.state == .connected);
assert(self.fd != -1);
if (self.peer != .unknown) return;
switch (header.peer_type()) {
.unknown => return,
.replica => {
self.peer = .{ .replica = header.replica };
// If there is a connection to this replica, terminate and replace it:
if (bus.replicas[self.peer.replica]) |old| {
assert(old.peer == .replica);
assert(old.peer.replica == self.peer.replica);
assert(old.state != .free);
if (old.state != .terminating) old.terminate(bus, .shutdown);
}
bus.replicas[self.peer.replica] = self;
log.info("connection from replica {}", .{self.peer.replica});
},
.client => {
self.peer = .{ .client = header.client };
const result = bus.process.clients.getOrPutAssumeCapacity(header.client);
// If there is a connection to this client, terminate and replace it:
if (result.found_existing) {
const old = result.value_ptr.*;
assert(old.peer == .client);
assert(old.peer.client == self.peer.client);
assert(old.state == .connected or old.state == .terminating);
if (old.state != .terminating) old.terminate(bus, .shutdown);
}
result.value_ptr.* = self;
log.info("connection from client {}", .{self.peer.client});
},
}
}
/// Acquires a free message if necessary and then calls `recv()`.
/// Terminates the connection if a free message cannot be obtained.
/// If the connection has a `recv_message` and the message being parsed is
/// at pole position then calls `recv()` immediately, otherwise copies any
/// partially received message into a new Message and sets `recv_message`,
/// releasing the old one.
fn get_recv_message_and_recv(self: *Connection, bus: *Self) void {
if (self.recv_message != null and self.recv_parsed == 0) {
self.recv(bus);
return;
}
const new_message = bus.get_message() orelse {
// TODO Decrease the probability of this happening by:
// 1. using a header-only message if possible.
// 2. determining a true upper limit for static allocation.
log.err("no free buffer available to recv message from {}", .{self.peer});
self.terminate(bus, .shutdown);
return;
};
defer bus.unref(new_message);
if (self.recv_message) |recv_message| {
defer bus.unref(recv_message);
assert(self.recv_progress > 0);
assert(self.recv_parsed > 0);
const data = recv_message.buffer[self.recv_parsed..self.recv_progress];
mem.copy(u8, new_message.buffer, data);
self.recv_progress = data.len;
self.recv_parsed = 0;
} else {
assert(self.recv_progress == 0);
assert(self.recv_parsed == 0);
}
self.recv_message = new_message.ref();
self.recv(bus);
}
fn recv(self: *Connection, bus: *Self) void {
assert(self.peer != .none);
assert(self.state == .connected);
assert(self.fd != -1);
assert(!self.recv_submitted);
self.recv_submitted = true;
assert(self.recv_progress < config.message_size_max);
bus.io.recv(
*Self,
bus,
on_recv,
&self.recv_completion,
self.fd,
self.recv_message.?.buffer[self.recv_progress..config.message_size_max],
os.MSG_NOSIGNAL,
);
}
fn on_recv(bus: *Self, completion: *IO.Completion, result: IO.RecvError!usize) void {
const self = @fieldParentPtr(Connection, "recv_completion", completion);
assert(self.recv_submitted);
self.recv_submitted = false;
if (self.state == .terminating) {
self.maybe_close(bus);
return;
}
assert(self.state == .connected);
const bytes_received = result catch |err| {
// TODO: maybe don't need to close on *every* error
log.err("error receiving from {}: {}", .{ self.peer, err });
self.terminate(bus, .shutdown);
return;
};
// No bytes received means that the peer closed its side of the connection.
if (bytes_received == 0) {
log.info("peer performed an orderly shutdown: {}", .{self.peer});
self.terminate(bus, .close);
return;
}
self.recv_progress += bytes_received;
self.parse_messages(bus);
}
fn send(self: *Connection, bus: *Self) void {
assert(self.peer == .client or self.peer == .replica);
assert(self.state == .connected);
assert(self.fd != -1);
const message = self.send_queue.peek() orelse return;
assert(!self.send_submitted);
self.send_submitted = true;
bus.io.send(
*Self,
bus,
on_send,
&self.send_completion,
self.fd,
message.buffer[self.send_progress..message.header.size],
os.MSG_NOSIGNAL,
);
}
fn on_send(bus: *Self, completion: *IO.Completion, result: IO.SendError!usize) void {
const self = @fieldParentPtr(Connection, "send_completion", completion);
assert(self.send_submitted);
self.send_submitted = false;
assert(self.peer == .client or self.peer == .replica);
if (self.state == .terminating) {
self.maybe_close(bus);
return;
}
assert(self.state == .connected);
self.send_progress += result catch |err| {
// TODO: maybe don't need to close on *every* error
log.err("error sending message to replica at {}: {}", .{ self.peer, err });
self.terminate(bus, .shutdown);
return;
};
assert(self.send_progress <= self.send_queue.peek().?.header.size);
// If the message has been fully sent, move on to the next one.
if (self.send_progress == self.send_queue.peek().?.header.size) {
self.send_progress = 0;
const message = self.send_queue.pop().?;
bus.unref(message);
}
self.send(bus);
}
fn maybe_close(self: *Connection, bus: *Self) void {
assert(self.peer != .none);
assert(self.state == .terminating);
// If a recv or send operation is currently submitted to the kernel,
// submitting a close would cause a race. Therefore we must wait for
// any currently submitted operation to complete.
if (self.recv_submitted or self.send_submitted) return;
self.send_submitted = true;
self.recv_submitted = true;
// We can free resources now that there is no longer any I/O in progress.
while (self.send_queue.pop()) |message| {
bus.unref(message);
}
if (self.recv_message) |message| {
bus.unref(message);
self.recv_message = null;
}
assert(self.fd != -1);
defer self.fd = -1;
// It's OK to use the send completion here as we know that no send
// operation is currently in progress.
bus.io.close(*Self, bus, on_close, &self.send_completion, self.fd);
}
fn on_close(bus: *Self, completion: *IO.Completion, result: IO.CloseError!void) void {
const self = @fieldParentPtr(Connection, "send_completion", completion);
assert(self.send_submitted);
assert(self.recv_submitted);
assert(self.peer != .none);
assert(self.state == .terminating);
// Reset the connection to its initial state.
defer {
assert(self.recv_message == null);
assert(self.send_queue.empty());
switch (self.peer) {
.none => unreachable,
.unknown => {},
.client => switch (process_type) {
.replica => assert(bus.process.clients.remove(self.peer.client)),
.client => unreachable,
},
.replica => {
// A newer replica connection may have replaced this one:
if (bus.replicas[self.peer.replica] == self) {
bus.replicas[self.peer.replica] = null;
} else {
// A newer replica connection may even leapfrog this connection and
// then be terminated and set to null before we can get here:
assert(bus.replicas[self.peer.replica] != null or
bus.replicas[self.peer.replica] == null);
}
},
}
bus.connections_used -= 1;
self.* = .{};
}
result catch |err| {
log.err("error closing connection to {}: {}", .{ self.peer, err });
return;
};
}
};
};
} | src/message_bus.zig |
const std = @import("std");
const utils = @import("utils.zig");
const is_space_or_tab = utils.is_space_or_tab;
const is_num = utils.is_num;
const is_end_of_line = utils. is_end_of_line;
pub const TAB_TO_SPACES = 4;
pub const SPACES_PER_INDENT = 4;
pub const TokenKind = enum {
Invalid,
Hash,
Asterisk,
Underscore,
Asterisk_double,
Underscore_double,
Tilde,
Tilde_double, // ~~
Dash,
Plus,
Period,
Comma,
Colon,
Colon_open_bracket,
Equals,
Bar,
Caret,
// TODO rename tokens to their function if they only have one single functionality?
Dollar,
Dollar_double,
Exclamation_open_bracket, // ![
Open_paren,
Close_paren,
Open_bracket,
Close_bracket,
Close_bracket_colon, // ]:
// open_brace,
// close_brace,
Open_angle_bracket,
Close_angle_bracket,
Double_quote,
Double_quote_triple,
Single_quote,
Backtick,
Backtick_double,
Backtick_triple,
// TODO change the rest to also have their meaning/effect as their name
// (if they have max. 2 different effects)
Run_codespan,
Run_codespan_alt,
Backslash,
Space,
Tab,
Newline,
Increase_indent,
Decrease_indent,
Hard_line_break, // \ in front of a line break
Comment, // //
Digits,
Text,
Builtin_call,
Eof,
pub inline fn name(self: TokenKind) []const u8 {
return switch (self) {
.Invalid => "(invalid)",
.Hash => "#",
.Asterisk => "*",
.Underscore => "_",
.Asterisk_double => "**",
.Underscore_double => "__",
.Tilde => "~",
.Tilde_double => "~~", // ~~
.Dash => "-",
.Plus => "+",
.Period => ".",
.Comma => ",",
.Colon => ":",
.Colon_open_bracket => ":[",
.Bar => "|",
.Equals => "=",
.Caret => "^",
.Dollar => "$",
.Dollar_double => "$$",
.Exclamation_open_bracket => "![", // ![
.Open_paren => "(",
.Close_paren => ")",
.Open_bracket => "[",
.Close_bracket => "]",
.Close_bracket_colon => "]:",
// open_brace,
// close_brace,
.Open_angle_bracket => "<",
.Close_angle_bracket => ">",
.Double_quote => "\"",
.Double_quote_triple => "\"\"\"",
.Single_quote => "'",
.Backtick => "`",
.Backtick_triple => "``",
.Backtick_double => "```",
.Run_codespan => ">`",
.Run_codespan_alt => ">``",
.Backslash => "\\",
.Space => " ",
.Tab => "\\t",
.Newline => "\\n",
.Increase_indent => "(increase_indent)",
.Decrease_indent => "(decrease_indent)",
.Hard_line_break => "(hard_line_break)",
.Comment => "(comment)",
.Digits => "(digits)",
.Text => "(text)",
.Builtin_call => "(@keyword)",
.Eof => "(EOF)",
};
}
pub inline fn ends_line(self: TokenKind) bool {
return switch (self) {
.Eof, .Newline => true,
else => false,
};
}
};
pub const Token = struct {
token_kind: TokenKind,
start: u32,
// exclusive end offset so we can use start..end when slicing
end: u32,
column: u16,
line_nr: u32,
pub inline fn len(self: *const Token) u32 {
return self.end - self.start;
}
/// get string content from token
/// bytes: md file text content
pub inline fn text(self: *Token, bytes: []const u8) []const u8 {
// make sure we don't call this on sth. that is not 'printable'
std.debug.assert(switch (self.token_kind) {
.Decrease_indent, .Eof => false,
else => true });
return switch (self.token_kind) {
.Tab => " " ** TAB_TO_SPACES,
.Increase_indent => " " ** SPACES_PER_INDENT,
.Newline => "\n",
.Text, .Digits, .Comment => bytes[self.start..self.end],
else => return self.token_kind.name(),
};
}
};
pub const Tokenizer = struct {
allocator: *std.mem.Allocator,
// can't have const filename inside struct unless declaring new global type
// after looking at zig stdlib that statement might not be true?
filename: []const u8,
bytes: []const u8,
// we don't really need usize just use u32; supporting >4GiB md files would be bananas
index: u32,
// commented out since id have to set this when using peek_next_byte too
// NOTE: zig needs 1 extra bit for optional non-pointer values to check if
// it has a payload/is non-null
current_byte: ?u8,
line_count: u32,
last_line_end_idx: u32,
indent_idx: u8,
new_indent_idx: u8,
indent_stack: [50]i16,
pub const Error = error {
UnmachtingDedent,
BlankLineContainsWhiteSpace,
SuddenEndOfFile,
};
pub fn init(allocator: *std.mem.Allocator, filename: []const u8) !Tokenizer {
// TODO skip BOM if present
const file = try std.fs.cwd().openFile(filename, .{ .read = true });
defer file.close();
// there's also file.readAll that requires a pre-allocated buffer
// TODO dynamically sized buffer
// TODO just pass buffer and filename, loading of the file should be done elsewhere
const contents = try file.reader().readAllAlloc(
allocator,
20 * 1024 * 1024, // max_size 2MiB, returns error.StreamTooLong if file is larger
);
// need to initialize explicitly or leave it undefined
// no zero init since it doesn't adhere to the language's principles
// due to zero initialization "not being meaningful"
// (but there is std.meta.zeroes)
var tokenizer = Tokenizer{
.allocator = allocator,
.filename = filename,
.bytes = contents,
.index = 0,
.current_byte = contents[0],
.line_count = 1,
.last_line_end_idx = 0,
.indent_idx = 0,
.new_indent_idx = 0,
.indent_stack = undefined,
};
tokenizer.indent_stack[0] = 0;
return tokenizer;
}
pub fn deinit(self: *Tokenizer) void {
self.allocator.free(self.bytes);
}
inline fn advance_to_next_byte(self: *Tokenizer) void {
if (self.index + 1 < self.bytes.len) {
self.index += 1;
self.current_byte = self.bytes[self.index];
} else {
// advance index beyond bytes length here as well?
self.current_byte = null;
}
}
/// caller has to make sure advancing the index doesn't go beyond bytes' length
inline fn prechecked_advance_to_next_byte(self: *Tokenizer) void {
self.index += 1;
self.current_byte = self.bytes[self.index];
}
inline fn peek_next_byte(self: *Tokenizer) ?u8 {
if (self.index + 1 < self.bytes.len) {
return self.bytes[self.index + 1];
} else {
return null;
}
}
fn eat_spaces_or_tabs(self: *Tokenizer) void {
while (self.peek_next_byte()) |char| : (self.index += 1) {
if (!is_space_or_tab(char)) {
// self.index will point to last space/tab char so self.next_byte
// returns the first non-whitespace byte or newline
break;
}
}
}
inline fn report_error(comptime err_msg: []const u8, args: anytype) void {
std.log.err(err_msg, args);
}
pub fn get_token(self: *Tokenizer) Error!Token {
var tok = Token{
.token_kind = TokenKind.Invalid,
.start = self.index,
.end = self.index + 1,
.column = @intCast(u16, self.index - self.last_line_end_idx),
.line_nr = self.line_count,
};
// we already advanced to the first non-whitespace byte but we still
// need to emit indentation change tokens
if (self.indent_idx < self.new_indent_idx) {
tok.token_kind = TokenKind.Increase_indent;
const ind_delta = self.indent_stack[self.indent_idx + 1] - self.indent_stack[self.indent_idx];
self.indent_idx += 1;
tok.column = @intCast(u16, self.indent_stack[self.indent_idx]);
tok.start = self.last_line_end_idx + tok.column;
tok.end = tok.start + @intCast(u16, ind_delta);
return tok;
} else if (self.indent_idx > self.new_indent_idx) {
tok.token_kind = TokenKind.Decrease_indent;
const ind_delta = self.indent_stack[self.indent_idx - 1] - self.indent_stack[self.indent_idx];
self.indent_idx -= 1;
tok.column = @intCast(u16, self.indent_stack[self.indent_idx]);
tok.start = self.last_line_end_idx + tok.column;
// -% -> wrapping subtraction
tok.end = @intCast(u32, @intCast(i64, tok.start) - ind_delta);
return tok;
}
if (self.current_byte) |char| {
if (char == '\r') {
if (self.peek_next_byte() != @as(u8, '\n')) {
// MacOS classic uses just \r as line break
// -> replace \r with \n
self.current_byte = @as(u8, '\n');
return self.get_token();
} else {
// ignore \r on DOS (\r\n line break)
self.advance_to_next_byte();
return self.get_token();
}
}
tok.token_kind = switch (char) {
'\n' => blk: {
// since line/col info is only needed on error we only store the
// line number and compute the col on demand
self.line_count += 1;
self.last_line_end_idx = self.index;
var indent_spaces: i16 = 0;
while (self.peek_next_byte()) |next_byte| : (self.prechecked_advance_to_next_byte()) {
switch (next_byte) {
' ' => indent_spaces += 1,
'\t' => indent_spaces += TAB_TO_SPACES,
else => break,
}
}
// only change indent_status if it's not a blank line
// NOTE: got rid of this since a blank line between blockquotes would
// swallow the +Indent -Indent
// make blank lines containing whitespace an error instead
// (similar to e.g. PEP8 W293 in python, but more extreme)
// TODO is this too obnoxious?
if (self.peek_next_byte()) |next_byte| { // need this due to compiler bug involving optionals
if (indent_spaces > 0 and
(next_byte == @as(u8, '\n') or next_byte == @as(u8, '\r'))) {
Tokenizer.report_error(
"ln:{}: Blank line contains whitespace!\n",
.{ self.line_count }); // not tok.line_nr since its the next line
return Error.BlankLineContainsWhiteSpace;
}
}
// dont emit any token for change in indentation level here since we first
// need the newline token
// check if amount of spaces changed changed
// TODO keep this v?
// (beyond a threshold of >1 space only when INCREASING indent)
const indent_delta: i16 = indent_spaces - self.indent_stack[self.indent_idx];
if (indent_delta > 1) {
self.new_indent_idx = self.indent_idx + 1;
self.indent_stack[self.new_indent_idx] = indent_spaces;
} else if (indent_delta < 0) {
var new_indent_idx = self.indent_idx;
while (self.indent_stack[new_indent_idx] != indent_spaces) : (
new_indent_idx -= 1) {
if (new_indent_idx == 0) {
Tokenizer.report_error(
"ln:{}: No indentation level matches the last indent!\n",
.{ self.line_count }); // not tok.line_nr since its the next line
return Error.UnmachtingDedent;
}
}
self.new_indent_idx = new_indent_idx;
}
break :blk TokenKind.Newline;
},
' ' => .Space,
'0'...'9' => blk: {
while (self.peek_next_byte()) |next_byte| : (self.prechecked_advance_to_next_byte()) {
if (!is_num(next_byte)) {
break;
}
}
break :blk .Digits;
},
'#' => .Hash,
'*' => blk: {
if (self.peek_next_byte() == @intCast(u8, '*')) {
self.prechecked_advance_to_next_byte();
break :blk TokenKind.Asterisk_double;
} else {
break :blk TokenKind.Asterisk;
}
},
'_' => blk: {
if (self.peek_next_byte() == @intCast(u8, '_')) {
self.prechecked_advance_to_next_byte();
break :blk TokenKind.Underscore_double;
} else {
break :blk TokenKind.Underscore;
}
},
'~' => blk: {
if (self.peek_next_byte() == @intCast(u8, '~')) {
self.prechecked_advance_to_next_byte();
break :blk TokenKind.Tilde_double;
} else {
break :blk TokenKind.Tilde;
}
},
'-' => .Dash,
'+' => .Plus,
'.' => .Period,
',' => .Comma,
':' => blk: {
if (self.peek_next_byte() == @intCast(u8, '[')) {
self.prechecked_advance_to_next_byte();
break :blk TokenKind.Colon_open_bracket;
} else {
break :blk TokenKind.Colon;
}
},
'|' => .Bar,
'^' => .Caret,
'=' => .Equals,
'$' => blk: {
if (self.peek_next_byte() == @as(u8, '$')) {
self.prechecked_advance_to_next_byte();
break :blk TokenKind.Dollar_double;
} else {
break :blk TokenKind.Dollar;
}
},
'!' => blk: {
if (self.peek_next_byte() == @as(u8, '[')) {
self.prechecked_advance_to_next_byte();
break :blk TokenKind.Exclamation_open_bracket;
} else {
break :blk TokenKind.Text;
}
},
'(' => .Open_paren,
')' => .Close_paren,
'[' => .Open_bracket,
']' => blk: {
if (self.peek_next_byte() == @intCast(u8, ':')) {
self.prechecked_advance_to_next_byte();
break :blk TokenKind.Close_bracket_colon;
} else {
break :blk TokenKind.Close_bracket;
}
},
'<' => .Open_angle_bracket,
'>' => blk: {
if (self.peek_next_byte() == @as(u8, '`')) {
self.prechecked_advance_to_next_byte();
if (self.peek_next_byte() == @as(u8, '`')) {
self.prechecked_advance_to_next_byte();
break :blk TokenKind.Run_codespan_alt;
}
break :blk TokenKind.Run_codespan;
} else {
break :blk TokenKind.Close_angle_bracket;
}
},
'"' => blk: {
if (self.peek_next_byte() == @as(u8, '"')) {
self.prechecked_advance_to_next_byte();
if (self.peek_next_byte() == @as(u8, '"')) {
self.prechecked_advance_to_next_byte();
break :blk TokenKind.Double_quote_triple;
} else {
break :blk TokenKind.Text;
}
} else {
break :blk TokenKind.Double_quote;
}
},
'\'' => .Single_quote,
'`' => blk: {
if (self.peek_next_byte() == @intCast(u8, '`')) {
self.prechecked_advance_to_next_byte();
if (self.peek_next_byte() == @intCast(u8, '`')) {
self.prechecked_advance_to_next_byte();
break :blk TokenKind.Backtick_triple;
} else {
break :blk TokenKind.Backtick_double;
}
} else {
break :blk TokenKind.Backtick;
}
},
'%' => blk: {
// type of '%' is apparently comptime_int so we need to cast it to u8 to
// be able to compare it
if (self.peek_next_byte() == @intCast(u8, '%')) {
self.prechecked_advance_to_next_byte();
// commented out till end of line
while (self.peek_next_byte()) |commented_byte| : (self.index += 1) {
if (is_end_of_line(commented_byte)) {
break;
}
}
// need to use the enum name here otherwise type inference breaks somehow
break :blk TokenKind.Comment;
} else {
break :blk TokenKind.Text;
}
},
'\\' => blk: {
// \ escapes following byte
// currently only emits one single Text token for a single byte only
// below triggers zig compiler bug: https://github.com/ziglang/zig/issues/6059
// if (self.current_byte == @intCast(u8, '\r') or
// self.current_byte == @intCast(u8, '\n')) {
// make sure we don't consume the line break so we still hit the
// correct switch prong next call
// backslash followed by \n (or \r but that is handled before the switch)
// is a hard line break
// NOTE: make sure we don't actually consume the \n
if (self.peek_next_byte()) |next_byte| {
if (next_byte == @as(u8, '\n') or next_byte == @as(u8, '\r')) {
break :blk TokenKind.Hard_line_break;
}
}
self.advance_to_next_byte();
tok.start = self.index;
break :blk TokenKind.Text;
},
'@' => blk: {
if (self.peek_next_byte()) |next_byte| {
self.prechecked_advance_to_next_byte();
if (!utils.is_lowercase(next_byte)) {
break :blk TokenKind.Text;
}
} else {
break :blk TokenKind.Text;
}
// haven't hit eof but we're still on '@'
self.prechecked_advance_to_next_byte();
while (self.peek_next_byte()) |next_byte| : (self.prechecked_advance_to_next_byte()) {
switch (next_byte) {
'a'...'z', 'A'...'Z', '0'...'9', '_' => continue,
else => break,
}
} else {
// else -> break not hit
Tokenizer.report_error(
"ln:{}: Hit unexpected EOF while parsing builtin keyword (@keyword(...))\n",
.{ self.line_count });
return Error.SuddenEndOfFile;
}
break :blk TokenKind.Builtin_call;
},
// assuming text (no keywords without leading symbol (e.g. @) currently)
else => blk: {
// consume everything that's not an inline style
while (self.peek_next_byte()) |next_byte| : (self.prechecked_advance_to_next_byte()) {
switch (next_byte) {
' ', '\t', '\r', '\n', '_', '*', '/', '\\', '`', '.',
'<', '[', ']', ')', '"', '~', '^', '$', '=' , ',', '@' => break,
else => {},
}
}
break :blk .Text;
},
};
tok.end = self.index + 1;
} else {
tok.token_kind = .Eof;
}
self.advance_to_next_byte();
return tok;
}
}; | src/tokenizer.zig |
const std = @import("std");
const encode = @import("encode.zig");
const value = @import("value.zig");
const testing = std.testing;
const Format = @import("format.zig").Format;
const EncodeError = encode.EncodeError;
pub fn encodeValue(allocator: *std.mem.Allocator, v: value.Value) EncodeError![]u8 {
return switch (v) {
.int => |val| encode.writeIntAny(allocator, val),
.uint => |val| encode.writeUintAny(allocator, val),
.nil => encode.writeNil(allocator),
.bool => |val| encode.writeBool(allocator, val),
.float => |val| encode.writeFloatAny(allocator, val),
.string => |val| encode.writeStrAny(allocator, val),
.binary => |val| encode.writeBinAny(allocator, val),
.array => |val| encodeArrayValue(allocator, val),
.map => |val| encodeMapValue(allocator, val),
};
}
fn encodeMapValue(allocator: *std.mem.Allocator, v: std.StringHashMap(value.Value)) EncodeError![]u8 {
if (v.count() <= encode.fix_map_max) {
return encodeFixMapValue(allocator, v);
} else if (v.count() <= encode.map16_max) {
return encodeMap16Value(allocator, v);
}
return encodeMap32Value(allocator, v);
}
fn encodeFixMapValue(allocator: *std.mem.Allocator, v: std.StringHashMap(value.Value)) EncodeError![]u8 {
var entries = try encodeMapValueEntries(allocator, v);
var out = try allocator.alloc(u8, 1 + entries.len);
out[0] = (Format{ .fix_map = @intCast(u8, v.count()) }).toUint8();
std.mem.copy(u8, out[1..], entries);
// now release the elems and joined elems
allocator.free(entries);
return out;
}
fn encodeMap16Value(allocator: *std.mem.Allocator, v: std.StringHashMap(value.Value)) EncodeError![]u8 {
var entries = try encodeMapValueEntries(allocator, v);
var out = try allocator.alloc(u8, 1 + @sizeOf(u16) + entries.len);
out[0] = Format.map16.toUint8();
std.mem.writeIntBig(u16, out[1 .. 1 + @sizeOf(u16)], @intCast(u16, v.count()));
std.mem.copy(u8, out[1 + @sizeOf(u16) ..], entries);
// now release the elems and joined elems
allocator.free(entries);
return out;
}
fn encodeMap32Value(allocator: *std.mem.Allocator, v: std.StringHashMap(value.Value)) EncodeError![]u8 {
var entries = try encodeMapValueEntries(allocator, v);
var out = try allocator.alloc(u8, 1 + @sizeOf(u32) + entries.len);
out[0] = Format.map32.toUint8();
std.mem.writeIntBig(u32, out[1 .. 1 + @sizeOf(u32)], @intCast(u32, v.count()));
std.mem.copy(u8, out[1 + @sizeOf(u32) ..], entries);
// now release the elems and joined elems
allocator.free(entries);
return out;
}
fn encodeMapValueEntries(allocator: *std.mem.Allocator, v: std.StringHashMap(value.Value)) EncodeError![]u8 {
// allocate twice the size as we space for each keys
// and values.
var entries = try allocator.alloc([]u8, v.count() * 2);
var i: usize = 0;
var it = v.iterator();
while (it.next()) |entry| {
// FIXME(): we have a memory leak here most likely
// in the case we return an error the error is not
// freed, but knowing that the only error which can happen
// in encodeValue is an OutOfMemory error, it's quite
// certain we would not recover anyway. Will take care of
// this later
var encodedkey = try encode.writeStrAny(allocator, entry.key);
entries[i] = encodedkey;
var encodedvalue = try encodeValue(allocator, entry.value);
entries[i + 1] = encodedvalue;
i += 2;
}
// FIXME(): see previous comment, same concerns.
var out = try std.mem.join(allocator, &[_]u8{}, entries);
// free the slice of encoded elements as they are not required anymore
for (entries) |e| {
allocator.free(e);
}
allocator.free(entries);
return out;
}
fn encodeArrayValue(
allocator: *std.mem.Allocator,
v: std.ArrayList(value.Value),
) EncodeError![]u8 {
if (v.items.len <= encode.fix_array_max) {
return encodeFixArrayValue(allocator, v);
} else if (v.items.len <= encode.array16_max) {
return encodeArray16Value(allocator, v);
}
return encodeArray32Value(allocator, v);
}
fn encodeFixArrayValue(
allocator: *std.mem.Allocator,
v: std.ArrayList(value.Value),
) EncodeError![]u8 {
var elems = try encodeArrayValueElements(allocator, v);
var out = try allocator.alloc(u8, 1 + elems.len);
out[0] = (Format{ .fix_array = @intCast(u8, v.items.len) }).toUint8();
std.mem.copy(u8, out[1..], elems);
// now release the elems and joined elems
allocator.free(elems);
return out;
}
fn encodeArray16Value(allocator: *std.mem.Allocator, v: std.ArrayList(value.Value)) EncodeError![]u8 {
var elems = try encodeArrayValueElements(allocator, v);
var out = try allocator.alloc(u8, 1 + @sizeOf(u16) + elems.len);
out[0] = Format.array16.toUint8();
std.mem.writeIntBig(u16, out[1 .. 1 + @sizeOf(u16)], @intCast(u16, v.items.len));
std.mem.copy(u8, out[1 + @sizeOf(u16) ..], elems);
// now release the elems and joined elems
allocator.free(elems);
return out;
}
fn encodeArray32Value(allocator: *std.mem.Allocator, v: std.ArrayList(value.Value)) EncodeError![]u8 {
var elems = try encodeArrayValueElements(allocator, v);
var out = try allocator.alloc(u8, 1 + @sizeOf(u32) + elems.len);
out[0] = Format.array32.toUint8();
std.mem.writeIntBig(u32, out[1 .. 1 + @sizeOf(u32)], @intCast(u32, v.items.len));
std.mem.copy(u8, out[1 + @sizeOf(u32) ..], elems);
// now release the elems and joined elems
allocator.free(elems);
return out;
}
fn encodeArrayValueElements(allocator: *std.mem.Allocator, v: std.ArrayList(value.Value)) EncodeError![]u8 {
var elems = try allocator.alloc([]u8, v.items.len);
var i: usize = 0;
while (i < v.items.len) {
// FIXME(): we have a memory leak here most likely
// in the case we return an error the error is not
// freed, but knowing that the only error which can happen
// in encodeValue is an OutOfMemory error, it's quite
// certain we would not recover anyway. Will take care of
// this later
var encoded = try encodeValue(allocator, v.items[i]);
elems[i] = encoded;
i += 1;
}
// FIXME(): see previous comment, same concerns.
var out = try std.mem.join(allocator, &[_]u8{}, elems);
// free the slice of encoded elements as they are not required anymore
for (elems) |e| {
allocator.free(e);
}
allocator.free(elems);
return out;
}
test "encode value: nil" {
const hex = "c0";
var bytes: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(bytes[0..], hex);
var encoded = try encodeValue(std.testing.allocator, .nil);
testing.expect(std.mem.eql(u8, bytes[0..], encoded));
std.testing.allocator.free(encoded);
}
test "encode value: bool false" {
const hex = "c2";
var bytes: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(bytes[0..], hex);
var encoded = try encodeValue(std.testing.allocator, value.Value{ .bool = false });
testing.expect(std.mem.eql(u8, bytes[0..], encoded));
std.testing.allocator.free(encoded);
}
test "encode value: bool true" {
const hex = "c3";
var bytes: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(bytes[0..], hex);
var encoded = try encodeValue(std.testing.allocator, value.Value{ .bool = true });
testing.expect(std.mem.eql(u8, bytes[0..], encoded));
std.testing.allocator.free(encoded);
}
test "encode value: fix positive int" {
const hex = "64"; // 100
var bytes: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(bytes[0..], hex);
var encoded = try encodeValue(std.testing.allocator, value.Value{ .uint = 100 });
testing.expect(std.mem.eql(u8, bytes[0..], encoded));
std.testing.allocator.free(encoded);
}
test "encode value: uint8" {
const hex = "cc80"; // 128
var bytes: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(bytes[0..], hex);
var encoded = try encodeValue(std.testing.allocator, value.Value{ .uint = 128 });
testing.expect(std.mem.eql(u8, bytes[0..], encoded));
std.testing.allocator.free(encoded);
}
test "encode value: uint16" {
const hex = "cd0640"; // 1600
var bytes: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(bytes[0..], hex);
var encoded = try encodeValue(std.testing.allocator, value.Value{ .uint = 1600 });
testing.expect(std.mem.eql(u8, bytes[0..], encoded));
std.testing.allocator.free(encoded);
}
test "encode value: uint32" {
const hex = "ce00bbdef8"; // 12312312
var bytes: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(bytes[0..], hex);
var encoded = try encodeValue(std.testing.allocator, value.Value{ .uint = 12312312 });
testing.expect(std.mem.eql(u8, bytes[0..], encoded));
std.testing.allocator.free(encoded);
}
test "encode value: uint64" {
const hex = "cf0000001caab5c3b3"; // 123123123123
var bytes: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(bytes[0..], hex);
var encoded = try encodeValue(std.testing.allocator, value.Value{ .uint = 123123123123 });
testing.expect(std.mem.eql(u8, bytes[0..], encoded));
std.testing.allocator.free(encoded);
}
test "encode value: negative fix int" {
const hex = "e0"; // -32
var bytes: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(bytes[0..], hex);
var encoded = try encodeValue(std.testing.allocator, value.Value{ .int = -32 });
testing.expect(std.mem.eql(u8, bytes[0..], encoded));
std.testing.allocator.free(encoded);
}
test "encode value: int8" {
const hex = "d085"; // -123
var bytes: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(bytes[0..], hex);
var encoded = try encodeValue(std.testing.allocator, value.Value{ .int = -123 });
testing.expect(std.mem.eql(u8, bytes[0..], encoded));
std.testing.allocator.free(encoded);
}
test "encode value: int16" {
const hex = "d1fb30"; // -1232
var bytes: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(bytes[0..], hex);
var encoded = try encodeValue(std.testing.allocator, value.Value{ .int = -1232 });
testing.expect(std.mem.eql(u8, bytes[0..], encoded));
std.testing.allocator.free(encoded);
}
test "encode value: int32" {
const hex = "d2fffe1eb4"; // -123212
var bytes: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(bytes[0..], hex);
var encoded = try encodeValue(std.testing.allocator, value.Value{ .int = -123212 });
testing.expect(std.mem.eql(u8, bytes[0..], encoded));
std.testing.allocator.free(encoded);
}
test "encode value: int64" {
const hex = "d3fffffffd2198eb05"; // -12321232123
var bytes: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(bytes[0..], hex);
var encoded = try encodeValue(std.testing.allocator, value.Value{ .int = -12321232123 });
testing.expect(std.mem.eql(u8, bytes[0..], encoded));
std.testing.allocator.free(encoded);
}
test "encode value: fix str" {
const hex = "ab68656c6c6f20776f726c64"; // "hello world"
var bytes: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(bytes[0..], hex);
var encoded = try encodeValue(std.testing.allocator, value.Value{ .string = "hello world" });
testing.expect(std.mem.eql(u8, bytes[0..], encoded));
std.testing.allocator.free(encoded);
}
test "encode value: str8" {
const hex = "d92368656c6c6f20776f726c642068656c6c6f20776f726c642068656c6c6f20776f726c64"; // "hello world hello world hello world"
var bytes: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(bytes[0..], hex);
var encoded = try encodeValue(std.testing.allocator, value.Value{ .string = "hello world hello world hello world" });
testing.expect(std.mem.eql(u8, bytes[0..], encoded));
std.testing.allocator.free(encoded);
}
test "encode value: str16" {
const hex = "da0132617364617364617364617364617364617364617364617364617364617364617364617364617364617364617364617364647361617364617364617364617364617364617364617364617364617364617364617364617364617364617364617364617364647361617364617364617364617364617364617364617364617364617364617364617364617364617364617364617364617364647361617364617364617364617364617364617364617364617364617364617364617364617364617364617364617364617364647361617364617364617364617364617364617364617364617364617364617364617364617364617364617364617364617364617364617364617364617364617364617364617364617364617364617364647361617364617364617364617364617364617364647361"; // "hello world hello world hello world"
var bytes: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(bytes[0..], hex);
var encoded = try encodeValue(std.testing.allocator, value.Value{ .string = "asdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasddsaasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasddsaasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasddsaasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasddsaasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasddsaasdasdasdasdasdasddsa" });
testing.expect(std.mem.eql(u8, bytes[0..], encoded));
std.testing.allocator.free(encoded);
}
// FIXME(): this test is working as expected, but the encoded float is
// f32 while the reference example generate r64...
// test "encode value: fix array" {
// const hex = "942ac3a6737472696e67cb404535c28f5c28f6"; // "[42, true, "string", 42.42]"
// var bytes: [hex.len / 2]u8 = undefined;
// try std.fmt.hexToBytes(bytes[0..], hex);
// var values = [4]value.Value{ .{ .uint = 42 }, .{ .bool = true }, .{ .string = "string" }, .{ .float = 42.42 } };
// var encoded = try encodeValue(std.testing.allocator, value.Value{ .array = values[0..] });
// testing.expect(std.mem.eql(u8, bytes[0..], encoded));
// std.testing.allocator.free(encoded);
// } | src/encode_value.zig |
const std = @import("std");
// Dross-zig
const Dross = @import("dross_zig.zig");
usingnamespace Dross;
const Player = @import("sandbox/player.zig").Player;
// -------------------------------------------
// Allocator
// Application Infomation
const APP_TITLE = "Dross-Zig Application";
const APP_WINDOW_WIDTH = 1280;
const APP_WINDOW_HEIGHT = 720;
const APP_VIEWPORT_WIDTH = 320;
const APP_VIEWPORT_HEIGHT = 180;
// Application related
var app: *Application = undefined;
var allocator: *std.mem.Allocator = undefined;
// Gameplay related
var camera: *Camera2d = undefined;
var player: *Player = undefined;
var quad_position_two: Vector3 = undefined;
var indicator_position: Vector3 = undefined;
var quad_sprite_two: *Sprite = undefined;
var indicator_sprite: *Sprite = undefined;
var sprite_sheet_example: *Sprite = undefined;
// Colors
const background_color: Color = .{
.r = 0.27843,
.g = 0.27843,
.b = 0.27843,
};
const ground_color: Color = .{
.r = 0.08235,
.g = 0.12157,
.b = 0.14510,
.a = 1.0,
};
const white: Color = .{
.r = 1.0,
.g = 1.0,
.b = 1.0,
};
//const ground_color: Color = .{
// .r = 0.58431,
// .g = 0.47834,
// .b = 0.36471,
//};
const ground_position: Vector3 = Vector3.new(0.0, 0.0, 0.0);
const ground_scale: Vector3 = Vector3.new(20.0, 1.0, 0.0);
const indentity_scale: Vector3 = Vector3.new(1.0, 1.0, 0.0);
const max_random = 20.0;
const random_count = 8000.0;
var random_positions: []Vector3 = undefined;
var random_colors: []Color = undefined;
pub fn main() anyerror!u8 {
// create a general purpose allocator
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
allocator = &gpa.allocator;
defer {
const leaked = gpa.deinit();
if (leaked) @panic("[Dross-Application Name]: Memory leak detected!");
}
// Create the application
app = try Application.new(
allocator,
APP_TITLE,
APP_WINDOW_WIDTH,
APP_WINDOW_HEIGHT,
APP_VIEWPORT_WIDTH,
APP_VIEWPORT_HEIGHT,
);
// Clean up the allocated application before exiting
defer Application.free(allocator, app);
// Setup
camera = try Camera2d.new(allocator);
defer Camera2d.free(allocator, camera);
player = try Player.new(allocator);
quad_sprite_two = try Sprite.new(allocator, "enemy_01_idle", "assets/sprites/s_enemy_01_idle.png", Vector2.zero(), Vector2.new(16.0, 16.0), Vector2.new(1.0, 1.0));
indicator_sprite = try Sprite.new(allocator, "indicator", "assets/sprites/s_ui_indicator.png", Vector2.zero(), Vector2.new(16.0, 16.0), Vector2.new(1.0, 1.0));
//quad_sprite_two.*.setOrigin(Vector2.new(7.0, 14.0));
//indicator_sprite.*.setOrigin(Vector2.new(8.0, 11.0));
//indicator_sprite.*.setAngle(30.0);
defer Player.free(allocator, player);
defer Sprite.free(allocator, quad_sprite_two);
defer Sprite.free(allocator, indicator_sprite);
quad_position_two = Vector3.new(2.0, 1.0, 1.0);
indicator_position = Vector3.new(5.0, 1.0, -1.0);
Renderer.changeClearColor(background_color);
var random_positions_arr: [random_count]Vector3 = undefined;
var random_colors_arr: [random_count]Color = undefined;
var count: usize = random_count;
var index: usize = 0;
while (index < count) : (index += 1) {
random_positions_arr[index] = try Vector3.random(max_random);
random_colors_arr[index] = try Color.random();
}
random_positions = random_positions_arr[0..];
random_colors = random_colors_arr[0..];
// Begin the game loop
app.run(update, render, gui_render);
return 0;
}
/// Defines what game-level tick/update logic you want to control in the game.
pub fn update(delta: f64) anyerror!void {
const delta32 = @floatCast(f32, delta);
const speed: f32 = 8.0 * delta32;
const rotational_speed = 100.0 * delta32;
const scale_speed = 10.0 * delta32;
const max_scale = 5.0;
const movement_smoothing = 0.6;
player.update(delta32);
//const quad_old_scale = quad_sprite_two.*.scale();
//const indicator_old_angle = indicator_sprite.*.angle();
//indicator_sprite.setAngle(indicator_old_angle + rotational_speed);
// const window_size = Application.windowSize();
// const zoom = camera.*.zoom();
// const old_camera_position = camera.*.position();
// const camera_smoothing = 0.075;
// const new_camera_position = Vector3.new(
// Math.lerp(old_camera_position.x(), -quad_position.x(), camera_smoothing),
// Math.lerp(old_camera_position.y(), -quad_position.y(), camera_smoothing),
// 0.0,
// );
// camera.*.setPosition(new_camera_position);
}
/// Defines the game-level rendering
pub fn render() anyerror!void {
player.render();
Renderer.drawSprite(quad_sprite_two, quad_position_two);
Renderer.drawSprite(indicator_sprite, indicator_position);
Renderer.drawColoredQuad(ground_position, ground_scale, ground_color);
//Renderer.drawColoredQuad(player.position, indentity_scale, ground_color);
//Renderer.drawColoredQuad(indicator_position, indentity_scale, ground_color);
//Renderer.drawColoredQuad(quad_position_two, indentity_scale, ground_color);
//var count: usize = random_count;
//var index: usize = 0;
//while (index < count) : (index += 1) {
// Renderer.drawColoredQuad(random_positions[index], indentity_scale, random_colors[index]);
//}
}
/// Defines the game-level gui rendering
pub fn gui_render() anyerror!void {
//const user_message: []const u8 = "[Application-requested render] ";
//const ass_string: []const u8 = "Eat Ass, ";
//const skate_string: []const u8 = "Skate Fast";
//const user_width = getStringWidth(user_message, 1.0);
//const user_height = getStringHeight(user_message, 1.0);
//const ass_width = getStringWidth(ass_string, 1.0);
//Renderer.drawText(user_message, 5.0, 5.0, 1.0, white);
//Renderer.drawText(ass_string, 5.0, 5.0 + user_height, 1.0, white);
//Renderer.drawText(skate_string, 5.0 + ass_width, 5.0 + user_height, 1.0, white);
//const stupid_message: []const u8 = "I want to run a test to see how many textured quads it'll take to slow this down.";
//const stupid_height = getStringHeight(stupid_message, 1.0);
//const count: usize = 20;
//var index: usize = 0;
//while (index < count) : (index += 1) {
// Renderer.drawText(stupid_message, 5.0, 5.0 + (stupid_height * @intToFloat(f32, index)), 1.0, white);
//}
} | src/main.zig |
const std = @import("std");
const example_input = @embedFile("./example_input.txt");
const puzzle_input = @embedFile("./puzzle_input.txt");
pub fn main() void {
std.debug.print("--- Part One ---\n", .{});
std.debug.print("Result: {d}\n", .{part1(puzzle_input)});
std.debug.print("--- Part Two ---\n", .{});
std.debug.print("Result: {d}\n", .{part2(puzzle_input)});
}
fn part1(input: []const u8) usize {
var lines = std.mem.tokenize(u8, input, "\n");
var depth: usize = 0;
var horizontal_position: usize = 0;
while (lines.next()) |line| {
var parts = std.mem.split(u8, line, " ");
const op = parts.next().?;
const arg = std.fmt.parseInt(usize, parts.next().?, 10) catch unreachable;
if (std.mem.eql(u8, op, "forward")) {
horizontal_position += arg;
} else if (std.mem.eql(u8, op, "down")) {
depth += arg;
} else if (std.mem.eql(u8, op, "up")) {
depth -= arg;
}
}
return depth * horizontal_position;
}
test "day02 part1 - example input" {
try std.testing.expectEqual(@as(usize, 150), part1(example_input));
}
test "day02 part1 - puzzle input" {
try std.testing.expectEqual(@as(usize, 2_187_380), part1(puzzle_input));
}
fn part2(input: []const u8) usize {
var lines = std.mem.tokenize(u8, input, "\n");
var depth: usize = 0;
var horizontal_position: usize = 0;
var aim: usize = 0;
while (lines.next()) |line| {
var parts = std.mem.split(u8, line, " ");
const op = parts.next().?;
const arg = std.fmt.parseInt(usize, parts.next().?, 10) catch unreachable;
if (std.mem.eql(u8, op, "forward")) {
horizontal_position += arg;
depth += arg * aim;
} else if (std.mem.eql(u8, op, "down")) {
aim += arg;
} else if (std.mem.eql(u8, op, "up")) {
aim -= arg;
}
}
return depth * horizontal_position;
}
test "day02 part2 - example input" {
try std.testing.expectEqual(@as(usize, 900), part2(example_input));
}
test "day02 part2 - puzzle input" {
try std.testing.expectEqual(@as(usize, 2_086_357_770), part2(puzzle_input));
} | src/day02/day02.zig |
//! This struct represents a kernel thread, and acts as a namespace for concurrency
//! primitives that operate on kernel threads. For concurrency primitives that support
//! both evented I/O and async I/O, see the respective names in the top level std namespace.
const std = @import("std.zig");
const os = std.os;
const assert = std.debug.assert;
const target = std.Target.current;
const Atomic = std.atomic.Atomic;
pub const AutoResetEvent = @import("Thread/AutoResetEvent.zig");
pub const Futex = @import("Thread/Futex.zig");
pub const ResetEvent = @import("Thread/ResetEvent.zig");
pub const StaticResetEvent = @import("Thread/StaticResetEvent.zig");
pub const Mutex = @import("Thread/Mutex.zig");
pub const Semaphore = @import("Thread/Semaphore.zig");
pub const Condition = @import("Thread/Condition.zig");
pub const spinLoopHint = @compileError("deprecated: use std.atomic.spinLoopHint");
pub const use_pthreads = target.os.tag != .windows and std.builtin.link_libc;
const Thread = @This();
const Impl = if (target.os.tag == .windows)
WindowsThreadImpl
else if (use_pthreads)
PosixThreadImpl
else if (target.os.tag == .linux)
LinuxThreadImpl
else
UnsupportedImpl;
impl: Impl,
/// Represents a unique ID per thread.
pub const Id = u64;
/// Returns the platform ID of the callers thread.
/// Attempts to use thread locals and avoid syscalls when possible.
pub fn getCurrentId() Id {
return Impl.getCurrentId();
}
pub const CpuCountError = error{
PermissionDenied,
SystemResources,
Unexpected,
};
/// Returns the platforms view on the number of logical CPU cores available.
pub fn getCpuCount() CpuCountError!usize {
return Impl.getCpuCount();
}
/// Configuration options for hints on how to spawn threads.
pub const SpawnConfig = struct {
// TODO compile-time call graph analysis to determine stack upper bound
// https://github.com/ziglang/zig/issues/157
/// Size in bytes of the Thread's stack
stack_size: usize = 16 * 1024 * 1024,
};
pub const SpawnError = error{
/// A system-imposed limit on the number of threads was encountered.
/// There are a number of limits that may trigger this error:
/// * the RLIMIT_NPROC soft resource limit (set via setrlimit(2)),
/// which limits the number of processes and threads for a real
/// user ID, was reached;
/// * the kernel's system-wide limit on the number of processes and
/// threads, /proc/sys/kernel/threads-max, was reached (see
/// proc(5));
/// * the maximum number of PIDs, /proc/sys/kernel/pid_max, was
/// reached (see proc(5)); or
/// * the PID limit (pids.max) imposed by the cgroup "process num‐
/// ber" (PIDs) controller was reached.
ThreadQuotaExceeded,
/// The kernel cannot allocate sufficient memory to allocate a task structure
/// for the child, or to copy those parts of the caller's context that need to
/// be copied.
SystemResources,
/// Not enough userland memory to spawn the thread.
OutOfMemory,
/// `mlockall` is enabled, and the memory needed to spawn the thread
/// would exceed the limit.
LockedMemoryLimitExceeded,
Unexpected,
};
/// Spawns a new thread which executes `function` using `args` and returns a handle the spawned thread.
/// `config` can be used as hints to the platform for now to spawn and execute the `function`.
/// The caller must eventually either call `join()` to wait for the thread to finish and free its resources
/// or call `detach()` to excuse the caller from calling `join()` and have the thread clean up its resources on completion`.
pub fn spawn(config: SpawnConfig, comptime function: anytype, args: anytype) SpawnError!Thread {
if (std.builtin.single_threaded) {
@compileError("Cannot spawn thread when building in single-threaded mode");
}
const impl = try Impl.spawn(config, function, args);
return Thread{ .impl = impl };
}
/// Represents a kernel thread handle.
/// May be an integer or a pointer depending on the platform.
pub const Handle = Impl.ThreadHandle;
/// Retrns the handle of this thread
pub fn getHandle(self: Thread) Handle {
return self.impl.getHandle();
}
/// Release the obligation of the caller to call `join()` and have the thread clean up its own resources on completion.
/// Once called, this consumes the Thread object and invoking any other functions on it is considered undefined behavior.
pub fn detach(self: Thread) void {
return self.impl.detach();
}
/// Waits for the thread to complete, then deallocates any resources created on `spawn()`.
/// Once called, this consumes the Thread object and invoking any other functions on it is considered undefined behavior.
pub fn join(self: Thread) void {
return self.impl.join();
}
/// State to synchronize detachment of spawner thread to spawned thread
const Completion = Atomic(enum(u8) {
running,
detached,
completed,
});
/// Used by the Thread implementations to call the spawned function with the arguments.
fn callFn(comptime f: anytype, args: anytype) switch (Impl) {
WindowsThreadImpl => std.os.windows.DWORD,
LinuxThreadImpl => u8,
PosixThreadImpl => ?*c_void,
else => unreachable,
} {
const default_value = if (Impl == PosixThreadImpl) null else 0;
const bad_fn_ret = "expected return type of startFn to be 'u8', 'noreturn', 'void', or '!void'";
switch (@typeInfo(@typeInfo(@TypeOf(f)).Fn.return_type.?)) {
.NoReturn => {
@call(.{}, f, args);
},
.Void => {
@call(.{}, f, args);
return default_value;
},
.Int => |info| {
if (info.bits != 8) {
@compileError(bad_fn_ret);
}
const status = @call(.{}, f, args);
if (Impl != PosixThreadImpl) {
return status;
}
// pthreads don't support exit status, ignore value
_ = status;
return default_value;
},
.ErrorUnion => |info| {
if (info.payload != void) {
@compileError(bad_fn_ret);
}
@call(.{}, f, args) catch |err| {
std.debug.warn("error: {s}\n", .{@errorName(err)});
if (@errorReturnTrace()) |trace| {
std.debug.dumpStackTrace(trace.*);
}
};
return default_value;
},
else => {
@compileError(bad_fn_ret);
},
}
}
/// We can't compile error in the `Impl` switch statement as its eagerly evaluated.
/// So instead, we compile-error on the methods themselves for platforms which don't support threads.
const UnsupportedImpl = struct {
pub const ThreadHandle = void;
fn getCurrentId() u64 {
return unsupported({});
}
fn getCpuCount() !usize {
return unsupported({});
}
fn spawn(config: SpawnConfig, comptime f: anytype, args: anytype) !Impl {
return unsupported(.{ config, f, args });
}
fn getHandle(self: Impl) ThreadHandle {
return unsupported(self);
}
fn detach(self: Impl) void {
return unsupported(self);
}
fn join(self: Impl) void {
return unsupported(self);
}
fn unsupported(unusued: anytype) noreturn {
@compileLog("Unsupported operating system", target.os.tag);
_ = unusued;
unreachable;
}
};
const WindowsThreadImpl = struct {
const windows = os.windows;
pub const ThreadHandle = windows.HANDLE;
fn getCurrentId() u64 {
return windows.kernel32.GetCurrentThreadId();
}
fn getCpuCount() !usize {
// Faster than calling into GetSystemInfo(), even if amortized.
return windows.peb().NumberOfProcessors;
}
thread: *ThreadCompletion,
const ThreadCompletion = struct {
completion: Completion,
heap_ptr: windows.PVOID,
heap_handle: windows.HANDLE,
thread_handle: windows.HANDLE = undefined,
fn free(self: ThreadCompletion) void {
const status = windows.kernel32.HeapFree(self.heap_handle, 0, self.heap_ptr);
assert(status != 0);
}
};
fn spawn(config: SpawnConfig, comptime f: anytype, args: anytype) !Impl {
const Args = @TypeOf(args);
const Instance = struct {
fn_args: Args,
thread: ThreadCompletion,
fn entryFn(raw_ptr: windows.PVOID) callconv(.C) windows.DWORD {
const self = @ptrCast(*@This(), @alignCast(@alignOf(@This()), raw_ptr));
defer switch (self.thread.completion.swap(.completed, .SeqCst)) {
.running => {},
.completed => unreachable,
.detached => self.thread.free(),
};
return callFn(f, self.fn_args);
}
};
const heap_handle = windows.kernel32.GetProcessHeap() orelse return error.OutOfMemory;
const alloc_bytes = @alignOf(Instance) + @sizeOf(Instance);
const alloc_ptr = windows.kernel32.HeapAlloc(heap_handle, 0, alloc_bytes) orelse return error.OutOfMemory;
errdefer assert(windows.kernel32.HeapFree(heap_handle, 0, alloc_ptr) != 0);
const instance_bytes = @ptrCast([*]u8, alloc_ptr)[0..alloc_bytes];
const instance = std.heap.FixedBufferAllocator.init(instance_bytes).allocator.create(Instance) catch unreachable;
instance.* = .{
.fn_args = args,
.thread = .{
.completion = Completion.init(.running),
.heap_ptr = alloc_ptr,
.heap_handle = heap_handle,
},
};
// Windows appears to only support SYSTEM_INFO.dwAllocationGranularity minimum stack size.
// Going lower makes it default to that specified in the executable (~1mb).
// Its also fine if the limit here is incorrect as stack size is only a hint.
var stack_size = std.math.cast(u32, config.stack_size) catch std.math.maxInt(u32);
stack_size = std.math.max(64 * 1024, stack_size);
instance.thread.thread_handle = windows.kernel32.CreateThread(
null,
stack_size,
Instance.entryFn,
@ptrCast(*c_void, instance),
0,
null,
) orelse {
const errno = windows.kernel32.GetLastError();
return windows.unexpectedError(errno);
};
return Impl{ .thread = &instance.thread };
}
fn getHandle(self: Impl) ThreadHandle {
return self.thread.thread_handle;
}
fn detach(self: Impl) void {
windows.CloseHandle(self.thread.thread_handle);
switch (self.thread.completion.swap(.detached, .SeqCst)) {
.running => {},
.completed => self.thread.free(),
.detached => unreachable,
}
}
fn join(self: Impl) void {
windows.WaitForSingleObjectEx(self.thread.thread_handle, windows.INFINITE, false) catch unreachable;
windows.CloseHandle(self.thread.thread_handle);
assert(self.thread.completion.load(.SeqCst) == .completed);
self.thread.free();
}
};
const PosixThreadImpl = struct {
const c = std.c;
pub const ThreadHandle = c.pthread_t;
fn getCurrentId() Id {
switch (target.os.tag) {
.linux => {
return LinuxThreadImpl.getCurrentId();
},
.macos, .ios, .watchos, .tvos => {
var thread_id: u64 = undefined;
// Pass thread=null to get the current thread ID.
assert(c.pthread_threadid_np(null, &thread_id) == 0);
return thread_id;
},
.dragonfly => {
return @bitCast(u32, c.lwp_gettid());
},
.netbsd => {
return @bitCast(u32, c._lwp_self());
},
.freebsd => {
return @bitCast(u32, c.pthread_getthreadid_np());
},
.openbsd => {
return @bitCast(u32, c.getthrid());
},
.haiku => {
return @bitCast(u32, c.find_thread(null));
},
else => {
return @ptrToInt(c.pthread_self());
},
}
}
fn getCpuCount() !usize {
switch (target.os.tag) {
.linux => {
return LinuxThreadImpl.getCpuCount();
},
.openbsd => {
var count: c_int = undefined;
var count_size: usize = @sizeOf(c_int);
const mib = [_]c_int{ os.CTL_HW, os.HW_NCPUONLINE };
os.sysctl(&mib, &count, &count_size, null, 0) catch |err| switch (err) {
error.NameTooLong, error.UnknownName => unreachable,
else => |e| return e,
};
return @intCast(usize, count);
},
.haiku => {
var count: u32 = undefined;
var system_info: os.system_info = undefined;
_ = os.system.get_system_info(&system_info); // always returns B_OK
count = system_info.cpu_count;
return @intCast(usize, count);
},
else => {
var count: c_int = undefined;
var count_len: usize = @sizeOf(c_int);
const name = if (comptime target.isDarwin()) "hw.logicalcpu" else "hw.ncpu";
os.sysctlbynameZ(name, &count, &count_len, null, 0) catch |err| switch (err) {
error.NameTooLong, error.UnknownName => unreachable,
else => |e| return e,
};
return @intCast(usize, count);
},
}
}
handle: ThreadHandle,
fn spawn(config: SpawnConfig, comptime f: anytype, args: anytype) !Impl {
const Args = @TypeOf(args);
const allocator = std.heap.c_allocator;
const Instance = struct {
fn entryFn(raw_arg: ?*c_void) callconv(.C) ?*c_void {
// @alignCast() below doesn't support zero-sized-types (ZST)
if (@sizeOf(Args) < 1) {
return callFn(f, @as(Args, undefined));
}
const args_ptr = @ptrCast(*Args, @alignCast(@alignOf(Args), raw_arg));
defer allocator.destroy(args_ptr);
return callFn(f, args_ptr.*);
}
};
const args_ptr = try allocator.create(Args);
args_ptr.* = args;
errdefer allocator.destroy(args_ptr);
var attr: c.pthread_attr_t = undefined;
if (c.pthread_attr_init(&attr) != 0) return error.SystemResources;
defer assert(c.pthread_attr_destroy(&attr) == 0);
// Use the same set of parameters used by the libc-less impl.
const stack_size = std.math.max(config.stack_size, 16 * 1024);
assert(c.pthread_attr_setstacksize(&attr, stack_size) == 0);
assert(c.pthread_attr_setguardsize(&attr, std.mem.page_size) == 0);
var handle: c.pthread_t = undefined;
switch (c.pthread_create(
&handle,
&attr,
Instance.entryFn,
if (@sizeOf(Args) > 1) @ptrCast(*c_void, args_ptr) else undefined,
)) {
0 => return Impl{ .handle = handle },
os.EAGAIN => return error.SystemResources,
os.EPERM => unreachable,
os.EINVAL => unreachable,
else => |err| return os.unexpectedErrno(err),
}
}
fn getHandle(self: Impl) ThreadHandle {
return self.handle;
}
fn detach(self: Impl) void {
switch (c.pthread_detach(self.handle)) {
0 => {},
os.EINVAL => unreachable, // thread handle is not joinable
os.ESRCH => unreachable, // thread handle is invalid
else => unreachable,
}
}
fn join(self: Impl) void {
switch (c.pthread_join(self.handle, null)) {
0 => {},
os.EINVAL => unreachable, // thread handle is not joinable (or another thread is already joining in)
os.ESRCH => unreachable, // thread handle is invalid
os.EDEADLK => unreachable, // two threads tried to join each other
else => unreachable,
}
}
};
const LinuxThreadImpl = struct {
const linux = os.linux;
pub const ThreadHandle = i32;
threadlocal var tls_thread_id: ?Id = null;
fn getCurrentId() Id {
return tls_thread_id orelse {
const tid = @bitCast(u32, linux.gettid());
tls_thread_id = tid;
return tid;
};
}
fn getCpuCount() !usize {
const cpu_set = try os.sched_getaffinity(0);
// TODO: should not need this usize cast
return @as(usize, os.CPU_COUNT(cpu_set));
}
thread: *ThreadCompletion,
const ThreadCompletion = struct {
completion: Completion = Completion.init(.running),
child_tid: Atomic(i32) = Atomic(i32).init(1),
parent_tid: i32 = undefined,
mapped: []align(std.mem.page_size) u8,
/// Calls `munmap(mapped.ptr, mapped.len)` then `exit(1)` without touching the stack (which lives in `mapped.ptr`).
/// Ported over from musl libc's pthread detached implementation:
/// https://github.com/ifduyue/musl/search?q=__unmapself
fn freeAndExit(self: *ThreadCompletion) noreturn {
switch (target.cpu.arch) {
.i386 => asm volatile (
\\ movl $91, %%eax
\\ movl %[ptr], %%ebx
\\ movl %[len], %%ecx
\\ int $128
\\ movl $1, %%eax
\\ movl $0, %%ebx
\\ int $128
:
: [ptr] "r" (@ptrToInt(self.mapped.ptr)),
[len] "r" (self.mapped.len)
: "memory"
),
.x86_64 => asm volatile (
\\ movq $11, %%rax
\\ movq %[ptr], %%rbx
\\ movq %[len], %%rcx
\\ syscall
\\ movq $60, %%rax
\\ movq $1, %%rdi
\\ syscall
:
: [ptr] "r" (@ptrToInt(self.mapped.ptr)),
[len] "r" (self.mapped.len)
: "memory"
),
.arm, .armeb, .thumb, .thumbeb => asm volatile (
\\ mov r7, #91
\\ mov r0, %[ptr]
\\ mov r1, %[len]
\\ svc 0
\\ mov r7, #1
\\ mov r0, #0
\\ svc 0
:
: [ptr] "r" (@ptrToInt(self.mapped.ptr)),
[len] "r" (self.mapped.len)
: "memory"
),
.aarch64, .aarch64_be, .aarch64_32 => asm volatile (
\\ mov x8, #215
\\ mov x0, %[ptr]
\\ mov x1, %[len]
\\ svc 0
\\ mov x8, #93
\\ mov x0, #0
\\ svc 0
:
: [ptr] "r" (@ptrToInt(self.mapped.ptr)),
[len] "r" (self.mapped.len)
: "memory"
),
.mips, .mipsel => asm volatile (
\\ move $sp, $25
\\ li $2, 4091
\\ move $4, %[ptr]
\\ move $5, %[len]
\\ syscall
\\ li $2, 4001
\\ li $4, 0
\\ syscall
:
: [ptr] "r" (@ptrToInt(self.mapped.ptr)),
[len] "r" (self.mapped.len)
: "memory"
),
.mips64, .mips64el => asm volatile (
\\ li $2, 4091
\\ move $4, %[ptr]
\\ move $5, %[len]
\\ syscall
\\ li $2, 4001
\\ li $4, 0
\\ syscall
:
: [ptr] "r" (@ptrToInt(self.mapped.ptr)),
[len] "r" (self.mapped.len)
: "memory"
),
.powerpc, .powerpcle, .powerpc64, .powerpc64le => asm volatile (
\\ li 0, 91
\\ mr %[ptr], 3
\\ mr %[len], 4
\\ sc
\\ li 0, 1
\\ li 3, 0
\\ sc
\\ blr
:
: [ptr] "r" (@ptrToInt(self.mapped.ptr)),
[len] "r" (self.mapped.len)
: "memory"
),
.riscv64 => asm volatile (
\\ li a7, 215
\\ mv a0, %[ptr]
\\ mv a1, %[len]
\\ ecall
\\ li a7, 93
\\ mv a0, zero
\\ ecall
:
: [ptr] "r" (@ptrToInt(self.mapped.ptr)),
[len] "r" (self.mapped.len)
: "memory"
),
else => |cpu_arch| @compileError("Unsupported linux arch: " ++ @tagName(cpu_arch)),
}
unreachable;
}
};
fn spawn(config: SpawnConfig, comptime f: anytype, args: anytype) !Impl {
const Args = @TypeOf(args);
const Instance = struct {
fn_args: Args,
thread: ThreadCompletion,
fn entryFn(raw_arg: usize) callconv(.C) u8 {
const self = @intToPtr(*@This(), raw_arg);
defer switch (self.thread.completion.swap(.completed, .SeqCst)) {
.running => {},
.completed => unreachable,
.detached => self.thread.freeAndExit(),
};
return callFn(f, self.fn_args);
}
};
var guard_offset: usize = undefined;
var stack_offset: usize = undefined;
var tls_offset: usize = undefined;
var instance_offset: usize = undefined;
const map_bytes = blk: {
var bytes: usize = std.mem.page_size;
guard_offset = bytes;
bytes += std.math.max(std.mem.page_size, config.stack_size);
bytes = std.mem.alignForward(bytes, std.mem.page_size);
stack_offset = bytes;
bytes = std.mem.alignForward(bytes, linux.tls.tls_image.alloc_align);
tls_offset = bytes;
bytes += linux.tls.tls_image.alloc_size;
bytes = std.mem.alignForward(bytes, @alignOf(Instance));
instance_offset = bytes;
bytes += @sizeOf(Instance);
bytes = std.mem.alignForward(bytes, std.mem.page_size);
break :blk bytes;
};
// map all memory needed without read/write permissions
// to avoid committing the whole region right away
const mapped = os.mmap(
null,
map_bytes,
os.PROT_NONE,
os.MAP_PRIVATE | os.MAP_ANONYMOUS,
-1,
0,
) catch |err| switch (err) {
error.MemoryMappingNotSupported => unreachable,
error.AccessDenied => unreachable,
error.PermissionDenied => unreachable,
else => |e| return e,
};
assert(mapped.len >= map_bytes);
errdefer os.munmap(mapped);
// map everything but the guard page as read/write
os.mprotect(
mapped[guard_offset..],
os.PROT_READ | os.PROT_WRITE,
) catch |err| switch (err) {
error.AccessDenied => unreachable,
else => |e| return e,
};
// Prepare the TLS segment and prepare a user_desc struct when needed on i386
var tls_ptr = os.linux.tls.prepareTLS(mapped[tls_offset..]);
var user_desc: if (target.cpu.arch == .i386) os.linux.user_desc else void = undefined;
if (target.cpu.arch == .i386) {
defer tls_ptr = @ptrToInt(&user_desc);
user_desc = .{
.entry_number = os.linux.tls.tls_image.gdt_entry_number,
.base_addr = tls_ptr,
.limit = 0xfffff,
.seg_32bit = 1,
.contents = 0, // Data
.read_exec_only = 0,
.limit_in_pages = 1,
.seg_not_present = 0,
.useable = 1,
};
}
const instance = @ptrCast(*Instance, @alignCast(@alignOf(Instance), &mapped[instance_offset]));
instance.* = .{
.fn_args = args,
.thread = .{ .mapped = mapped },
};
const flags: u32 = os.CLONE_THREAD | os.CLONE_DETACHED |
os.CLONE_VM | os.CLONE_FS | os.CLONE_FILES |
os.CLONE_PARENT_SETTID | os.CLONE_CHILD_CLEARTID |
os.CLONE_SIGHAND | os.CLONE_SYSVSEM | os.CLONE_SETTLS;
switch (linux.getErrno(linux.clone(
Instance.entryFn,
@ptrToInt(&mapped[stack_offset]),
flags,
@ptrToInt(instance),
&instance.thread.parent_tid,
tls_ptr,
&instance.thread.child_tid.value,
))) {
0 => return Impl{ .thread = &instance.thread },
os.EAGAIN => return error.ThreadQuotaExceeded,
os.EINVAL => unreachable,
os.ENOMEM => return error.SystemResources,
os.ENOSPC => unreachable,
os.EPERM => unreachable,
os.EUSERS => unreachable,
else => |err| return os.unexpectedErrno(err),
}
}
fn getHandle(self: Impl) ThreadHandle {
return self.thread.parent_tid;
}
fn detach(self: Impl) void {
switch (self.thread.completion.swap(.detached, .SeqCst)) {
.running => {},
.completed => self.join(),
.detached => unreachable,
}
}
fn join(self: Impl) void {
defer os.munmap(self.thread.mapped);
var spin: u8 = 10;
while (true) {
const tid = self.thread.child_tid.load(.SeqCst);
if (tid == 0) {
break;
}
if (spin > 0) {
spin -= 1;
std.atomic.spinLoopHint();
continue;
}
switch (linux.getErrno(linux.futex_wait(
&self.thread.child_tid.value,
linux.FUTEX_WAIT,
tid,
null,
))) {
0 => continue,
os.EINTR => continue,
os.EAGAIN => continue,
else => unreachable,
}
}
}
};
test "std.Thread" {
// Doesn't use testing.refAllDecls() since that would pull in the compileError spinLoopHint.
_ = AutoResetEvent;
_ = Futex;
_ = ResetEvent;
_ = StaticResetEvent;
_ = Mutex;
_ = Semaphore;
_ = Condition;
}
fn testIncrementNotify(value: *usize, event: *ResetEvent) void {
value.* += 1;
event.set();
}
test "Thread.join" {
if (std.builtin.single_threaded) return error.SkipZigTest;
var value: usize = 0;
var event: ResetEvent = undefined;
try event.init();
defer event.deinit();
const thread = try Thread.spawn(.{}, testIncrementNotify, .{ &value, &event });
thread.join();
try std.testing.expectEqual(value, 1);
}
test "Thread.detach" {
if (std.builtin.single_threaded) return error.SkipZigTest;
var value: usize = 0;
var event: ResetEvent = undefined;
try event.init();
defer event.deinit();
const thread = try Thread.spawn(.{}, testIncrementNotify, .{ &value, &event });
thread.detach();
event.wait();
try std.testing.expectEqual(value, 1);
} | lib/std/Thread.zig |
const std = @import("std");
const wgi = @import("../WindowGraphicsInput/WindowGraphicsInput.zig");
const FrameBuffer = wgi.FrameBuffer;
const ImageType = wgi.ImageType;
const ShaderObject = wgi.ShaderObject;
const ShaderType = wgi.ShaderType;
const ShaderProgram = wgi.ShaderProgram;
const window = wgi.window;
const Buffer = wgi.Buffer;
const VertexMeta = wgi.VertexMeta;
const files = @import("../Files.zig");
const loadFileWithNullTerminator = files.loadFileWithNullTerminator;
var post_process_shader_vs_src: ?[]u8 = null;
var post_process_shader_fs_src: ?[]u8 = null;
var post_process_shader_program: ?ShaderProgram = null;
var post_process_shader_program_window_size_uniform_location: ?i32 = null;
var post_process_shader_program_contrast_uniform_location: ?i32 = null;
var post_process_shader_program_brightness_uniform_location: ?i32 = null;
var fbo: ?FrameBuffer = null;
pub fn loadSourceFiles(allocator: *std.mem.Allocator) !void {
post_process_shader_vs_src = try loadFileWithNullTerminator("StandardAssets" ++ files.path_seperator ++ "PostProcess.vs", allocator);
post_process_shader_fs_src = try loadFileWithNullTerminator("StandardAssets" ++ files.path_seperator ++ "PostProcess.fs", allocator);
}
fn createShaderProgram(allocator: *std.mem.Allocator) !void {
var post_process_vs: ShaderObject = try ShaderObject.init(([_]([]const u8){post_process_shader_vs_src.?})[0..], ShaderType.Vertex, allocator);
var post_process_fs: ShaderObject = try ShaderObject.init(([_]([]const u8){post_process_shader_fs_src.?})[0..], ShaderType.Fragment, allocator);
errdefer post_process_shader_program = null;
post_process_shader_program = try ShaderProgram.init(&post_process_vs, &post_process_fs, &[0][]const u8{}, allocator);
errdefer post_process_shader_program.?.free();
try post_process_shader_program.?.setUniform1i(try post_process_shader_program.?.getUniformLocation("framebuffer"), 0);
post_process_shader_program_window_size_uniform_location = try post_process_shader_program.?.getUniformLocation("window_dimensions");
post_process_shader_program_contrast_uniform_location = try post_process_shader_program.?.getUniformLocation("contrast");
post_process_shader_program_brightness_uniform_location = try post_process_shader_program.?.getUniformLocation("brightness");
post_process_vs.free();
post_process_fs.free();
}
fn createResources(window_width: u32, window_height: u32, allocator: *std.mem.Allocator) !void {
if (fbo == null) {
fbo = try FrameBuffer.init(wgi.ImageType.RG11FB10F, window_width, window_height, FrameBuffer.DepthType.F32, allocator);
} else if (fbo.?.textures[0].?.width != window_width or fbo.?.textures[0].?.height != window_height) {
try fbo.?.resize(window_width, window_height);
}
if (post_process_shader_program == null) {
try createShaderProgram(allocator);
}
}
pub fn startFrame(window_width: u32, window_height: u32, allocator: *std.mem.Allocator) !void {
if (window_width == 0 or window_height == 0) {
return error.InvalidWindowDimensions;
}
createResources(window_width, window_height, allocator) catch |e| {
std.debug.warn("Error creating post-process resources: {}\n", .{e});
return e;
};
try fbo.?.bind();
}
pub fn endFrame(window_width: u32, window_height: u32, brightness: f32, contrast: f32) !void {
wgi.disableDepthTesting();
wgi.disableDepthWriting();
FrameBuffer.bindDefaultFrameBuffer();
window.clear(true, false);
try post_process_shader_program.?.bind();
try post_process_shader_program.?.setUniform2f(post_process_shader_program_window_size_uniform_location.?, [2]f32{ @intToFloat(f32, window_width), @intToFloat(f32, window_height) });
try post_process_shader_program.?.setUniform1f(post_process_shader_program_brightness_uniform_location.?, brightness);
try post_process_shader_program.?.setUniform1f(post_process_shader_program_contrast_uniform_location.?, contrast);
try fbo.?.bindTexture();
try VertexMeta.drawWithoutData(VertexMeta.PrimitiveType.Triangles, 0, 3);
wgi.Texture2D.unbind(0);
} | src/RTRenderEngine/PostProcess.zig |
extern "document" fn query_selector(selector_ptr: [*]const u8, selector_len: usize) usize;
extern "document" fn create_element(tag_name_ptr: [*]const u8, tag_name_len: usize) usize;
extern "document" fn create_text_node(data_ptr: [*]const u8, data_len: usize) usize;
extern "element" fn set_attribute(element_id: usize, name_ptr: [*]const u8, name_len: usize, value_ptr: [*]const u8, value_len: usize) void;
extern "element" fn get_attribute(element_id: usize, name_ptr: [*]const u8, name_len: usize, value_ptr: *[*]u8, value_len: *usize) bool;
extern "event_target" fn add_event_listener(event_target_id: usize, event_ptr: [*]const u8, event_len: usize, event_id: usize) void;
extern "window" fn alert(msg_ptr: [*]const u8, msg_len: usize) void;
extern "node" fn append_child(node_id: usize, child_id: usize) usize;
extern "zig" fn release_object(object_id: usize) void;
const std = @import("std");
const eventId = enum(usize) {
Submit,
Clear,
};
var input_tag_node: u32 = undefined;
fn launch() !void {
const body_selector = "body";
const body_node = query_selector(body_selector, body_selector.len);
defer release_object(body_node);
if (body_node == 0) {
return error.QuerySelectorError;
}
const input_tag_name = "input";
input_tag_node = create_element(input_tag_name, input_tag_name.len);
// We don't release as we'll be referencing it later
if (input_tag_node == 0) {
return error.CreateElementError;
}
const input_tag_attribute_name = "value";
const input_tag_attribute_value = "Hello from Zig!";
set_attribute(input_tag_node, input_tag_attribute_name, input_tag_attribute_name.len, input_tag_attribute_value, input_tag_attribute_value.len);
const button_tag_name = "button";
const submit_button_node = create_element(button_tag_name, button_tag_name.len);
defer release_object(submit_button_node);
if (submit_button_node == 0) {
return error.CreateElementError;
}
const event_name = "click";
attach_listener(submit_button_node, event_name, eventId.Submit);
const submit_text_msg = "submit";
const submit_text_node = create_text_node(submit_text_msg, submit_text_msg.len);
defer release_object(submit_text_node);
if (submit_text_node == 0) {
return error.CreateTextNodeError;
}
const attached_submit_text_node = append_child(submit_button_node, submit_text_node);
defer release_object(attached_submit_text_node);
if (attached_submit_text_node == 0) {
return error.AppendChildError;
}
const clear_button_node = create_element(button_tag_name, button_tag_name.len);
defer release_object(clear_button_node);
if (clear_button_node == 0) {
return error.CreateElementError;
}
attach_listener(clear_button_node, event_name, eventId.Clear);
const clear_text_msg = "clear";
const clear_text_node = create_text_node(clear_text_msg, clear_text_msg.len);
defer release_object(clear_text_node);
if (clear_text_node == 0) {
return error.CreateTextNodeError;
}
const attached_clear_text_node = append_child(clear_button_node, clear_text_node);
defer release_object(attached_clear_text_node);
if (attached_clear_text_node == 0) {
return error.AppendChildError;
}
const attached_input_node = append_child(body_node, input_tag_node);
defer release_object(attached_input_node);
if (attached_input_node == 0) {
return error.AppendChildError;
}
const attached_submit_button_node = append_child(body_node, submit_button_node);
defer release_object(attached_submit_button_node);
if (attached_submit_button_node == 0) {
return error.AppendChildError;
}
const attached_clear_button_node = append_child(body_node, clear_button_node);
defer release_object(attached_clear_button_node);
if (attached_clear_button_node == 0) {
return error.AppendChildError;
}
}
fn attach_listener(node: usize, event_name: []const u8, event_id: eventId) void {
add_event_listener(node, event_name.ptr, event_name.len, @enumToInt(event_id));
}
export fn dispatchEvent(id: u32) void {
switch (@intToEnum(eventId, id)) {
eventId.Submit => on_submit_event(),
eventId.Clear => on_clear_event(),
}
}
fn on_clear_event() void {
const input_tag_attribute_name = "value";
const input_tag_attribute_value = "";
set_attribute(input_tag_node, input_tag_attribute_name, input_tag_attribute_name.len, input_tag_attribute_value, input_tag_attribute_value.len);
}
fn on_submit_event() void {
var attribute_ptr: [*]u8 = undefined;
var attribute_len: usize = undefined;
const input_tag_attribute_name = "value";
const success = get_attribute(input_tag_node, input_tag_attribute_name, input_tag_attribute_name.len, &attribute_ptr, &attribute_len);
if (success) {
const result = attribute_ptr[0..attribute_len];
defer std.heap.page_allocator.free(result);
alert(result.ptr, result.len);
}
}
export fn launch_export() bool {
launch() catch |err| return false;
return true;
}
export fn _wasm_alloc(len: usize) u32 {
var buf = std.heap.page_allocator.alloc(u8, len) catch |err| return 0;
return @ptrToInt(buf.ptr);
} | src/zigdom.zig |
const assert = @import("std").testing.expectEqual;
const MMIO = @import("../../common/mmio.zig").MMIO;
const name = "STM32F411";
pub const ADC_Common = extern struct {
pub const Address: u32 = 0x40012300;
pub const CSR = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 ADC Common status register
AWD1: bool, // bit offset: 0 desc: Analog watchdog flag of ADC 1
EOC1: bool, // bit offset: 1 desc: End of conversion of ADC 1
JEOC1: bool, // bit offset: 2 desc: Injected channel end of conversion of ADC 1
JSTRT1: bool, // bit offset: 3 desc: Injected channel Start flag of ADC 1
STRT1: bool, // bit offset: 4 desc: Regular channel Start flag of ADC 1
OVR1: bool, // bit offset: 5 desc: Overrun flag of ADC 1
reserved0: u2 = 0,
AWD2: bool, // bit offset: 8 desc: Analog watchdog flag of ADC 2
EOC2: bool, // bit offset: 9 desc: End of conversion of ADC 2
JEOC2: bool, // bit offset: 10 desc: Injected channel end of conversion of ADC 2
JSTRT2: bool, // bit offset: 11 desc: Injected channel Start flag of ADC 2
STRT2: bool, // bit offset: 12 desc: Regular channel Start flag of ADC 2
OVR2: bool, // bit offset: 13 desc: Overrun flag of ADC 2
reserved1: u2 = 0,
AWD3: bool, // bit offset: 16 desc: Analog watchdog flag of ADC 3
EOC3: bool, // bit offset: 17 desc: End of conversion of ADC 3
JEOC3: bool, // bit offset: 18 desc: Injected channel end of conversion of ADC 3
JSTRT3: bool, // bit offset: 19 desc: Injected channel Start flag of ADC 3
STRT3: bool, // bit offset: 20 desc: Regular channel Start flag of ADC 3
OVR3: bool, // bit offset: 21 desc: Overrun flag of ADC3
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCR = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 ADC common control register
reserved0: u8 = 0,
DELAY: u4, // bit offset: 8 desc: Delay between 2 sampling phases
reserved1: u1 = 0,
DDS: bool, // bit offset: 13 desc: DMA disable selection for multi-ADC mode
DMA: u2, // bit offset: 14 desc: Direct memory access mode for multi ADC mode
ADCPRE: u2, // bit offset: 16 desc: ADC prescaler
reserved2: u4 = 0,
VBATE: bool, // bit offset: 22 desc: VBAT enable
TSVREFE: bool, // bit offset: 23 desc: Temperature sensor and VREFINT enable
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const ADC1 = extern struct {
pub const Address: u32 = 0x40012000;
pub const SR = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 status register
AWD: bool, // bit offset: 0 desc: Analog watchdog flag
EOC: bool, // bit offset: 1 desc: Regular channel end of conversion
JEOC: bool, // bit offset: 2 desc: Injected channel end of conversion
JSTRT: bool, // bit offset: 3 desc: Injected channel start flag
STRT: bool, // bit offset: 4 desc: Regular channel start flag
OVR: bool, // bit offset: 5 desc: Overrun
padding26: u1 = 0,
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR1 = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 control register 1
AWDCH: u5, // bit offset: 0 desc: Analog watchdog channel select bits
EOCIE: bool, // bit offset: 5 desc: Interrupt enable for EOC
AWDIE: bool, // bit offset: 6 desc: Analog watchdog interrupt enable
JEOCIE: bool, // bit offset: 7 desc: Interrupt enable for injected channels
SCAN: bool, // bit offset: 8 desc: Scan mode
AWDSGL: bool, // bit offset: 9 desc: Enable the watchdog on a single channel in scan mode
JAUTO: bool, // bit offset: 10 desc: Automatic injected group conversion
DISCEN: bool, // bit offset: 11 desc: Discontinuous mode on regular channels
JDISCEN: bool, // bit offset: 12 desc: Discontinuous mode on injected channels
DISCNUM: u3, // bit offset: 13 desc: Discontinuous mode channel count
reserved0: u6 = 0,
JAWDEN: bool, // bit offset: 22 desc: Analog watchdog enable on injected channels
AWDEN: bool, // bit offset: 23 desc: Analog watchdog enable on regular channels
RES: u2, // bit offset: 24 desc: Resolution
OVRIE: bool, // bit offset: 26 desc: Overrun interrupt enable
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR2 = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 control register 2
ADON: bool, // bit offset: 0 desc: A/D Converter ON / OFF
CONT: bool, // bit offset: 1 desc: Continuous conversion
reserved0: u6 = 0,
DMA: bool, // bit offset: 8 desc: Direct memory access mode (for single ADC mode)
DDS: bool, // bit offset: 9 desc: DMA disable selection (for single ADC mode)
EOCS: bool, // bit offset: 10 desc: End of conversion selection
ALIGN: bool, // bit offset: 11 desc: Data alignment
reserved1: u4 = 0,
JEXTSEL: u4, // bit offset: 16 desc: External event select for injected group
JEXTEN: u2, // bit offset: 20 desc: External trigger enable for injected channels
JSWSTART: bool, // bit offset: 22 desc: Start conversion of injected channels
reserved2: u1 = 0,
EXTSEL: u4, // bit offset: 24 desc: External event select for regular group
EXTEN: u2, // bit offset: 28 desc: External trigger enable for regular channels
SWSTART: bool, // bit offset: 30 desc: Start conversion of regular channels
padding1: u1 = 0,
});
pub const SMPR1 = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 sample time register 1
SMPx_x: u32, // bit offset: 0 desc: Sample time bits
});
pub const SMPR2 = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 sample time register 2
SMPx_x: u32, // bit offset: 0 desc: Sample time bits
});
pub const JOFR1 = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 injected channel data offset register x
JOFFSET1: u12, // bit offset: 0 desc: Data offset for injected channel x
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const JOFR2 = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 injected channel data offset register x
JOFFSET2: u12, // bit offset: 0 desc: Data offset for injected channel x
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const JOFR3 = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 injected channel data offset register x
JOFFSET3: u12, // bit offset: 0 desc: Data offset for injected channel x
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const JOFR4 = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 injected channel data offset register x
JOFFSET4: u12, // bit offset: 0 desc: Data offset for injected channel x
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const HTR = MMIO(Address + 0x00000024, u32, packed struct { // byte offset: 36 watchdog higher threshold register
HT: u12, // bit offset: 0 desc: Analog watchdog higher threshold
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const LTR = MMIO(Address + 0x00000028, u32, packed struct { // byte offset: 40 watchdog lower threshold register
LT: u12, // bit offset: 0 desc: Analog watchdog lower threshold
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SQR1 = MMIO(Address + 0x0000002c, u32, packed struct { // byte offset: 44 regular sequence register 1
SQ13: u5, // bit offset: 0 desc: 13th conversion in regular sequence
SQ14: u5, // bit offset: 5 desc: 14th conversion in regular sequence
SQ15: u5, // bit offset: 10 desc: 15th conversion in regular sequence
SQ16: u5, // bit offset: 15 desc: 16th conversion in regular sequence
L: u4, // bit offset: 20 desc: Regular channel sequence length
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SQR2 = MMIO(Address + 0x00000030, u32, packed struct { // byte offset: 48 regular sequence register 2
SQ7: u5, // bit offset: 0 desc: 7th conversion in regular sequence
SQ8: u5, // bit offset: 5 desc: 8th conversion in regular sequence
SQ9: u5, // bit offset: 10 desc: 9th conversion in regular sequence
SQ10: u5, // bit offset: 15 desc: 10th conversion in regular sequence
SQ11: u5, // bit offset: 20 desc: 11th conversion in regular sequence
SQ12: u5, // bit offset: 25 desc: 12th conversion in regular sequence
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SQR3 = MMIO(Address + 0x00000034, u32, packed struct { // byte offset: 52 regular sequence register 3
SQ1: u5, // bit offset: 0 desc: 1st conversion in regular sequence
SQ2: u5, // bit offset: 5 desc: 2nd conversion in regular sequence
SQ3: u5, // bit offset: 10 desc: 3rd conversion in regular sequence
SQ4: u5, // bit offset: 15 desc: 4th conversion in regular sequence
SQ5: u5, // bit offset: 20 desc: 5th conversion in regular sequence
SQ6: u5, // bit offset: 25 desc: 6th conversion in regular sequence
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const JSQR = MMIO(Address + 0x00000038, u32, packed struct { // byte offset: 56 injected sequence register
JSQ1: u5, // bit offset: 0 desc: 1st conversion in injected sequence
JSQ2: u5, // bit offset: 5 desc: 2nd conversion in injected sequence
JSQ3: u5, // bit offset: 10 desc: 3rd conversion in injected sequence
JSQ4: u5, // bit offset: 15 desc: 4th conversion in injected sequence
JL: u2, // bit offset: 20 desc: Injected sequence length
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const JDR1 = MMIO(Address + 0x0000003c, u32, packed struct { // byte offset: 60 injected data register x
JDATA: u16, // bit offset: 0 desc: Injected data
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const JDR2 = MMIO(Address + 0x00000040, u32, packed struct { // byte offset: 64 injected data register x
JDATA: u16, // bit offset: 0 desc: Injected data
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const JDR3 = MMIO(Address + 0x00000044, u32, packed struct { // byte offset: 68 injected data register x
JDATA: u16, // bit offset: 0 desc: Injected data
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const JDR4 = MMIO(Address + 0x00000048, u32, packed struct { // byte offset: 72 injected data register x
JDATA: u16, // bit offset: 0 desc: Injected data
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DR = MMIO(Address + 0x0000004c, u32, packed struct { // byte offset: 76 regular data register
DATA: u16, // bit offset: 0 desc: Regular data
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const CRC = extern struct {
pub const Address: u32 = 0x40023000;
pub const DR = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 Data register
DR: u32, // bit offset: 0 desc: Data Register
});
pub const IDR = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 Independent Data register
IDR: u8, // bit offset: 0 desc: Independent Data register
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 Control register
CR: bool, // bit offset: 0 desc: Control regidter
padding31: u1 = 0,
padding30: u1 = 0,
padding29: u1 = 0,
padding28: u1 = 0,
padding27: u1 = 0,
padding26: u1 = 0,
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const DBG = extern struct {
pub const Address: u32 = 0xe0042000;
pub const DBGMCU_IDCODE = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 IDCODE
DEV_ID: u12, // bit offset: 0 desc: DEV_ID
reserved0: u4 = 0,
REV_ID: u16, // bit offset: 16 desc: REV_ID
});
pub const DBGMCU_CR = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 Control Register
DBG_SLEEP: bool, // bit offset: 0 desc: DBG_SLEEP
DBG_STOP: bool, // bit offset: 1 desc: DBG_STOP
DBG_STANDBY: bool, // bit offset: 2 desc: DBG_STANDBY
reserved0: u2 = 0,
TRACE_IOEN: bool, // bit offset: 5 desc: TRACE_IOEN
TRACE_MODE: u2, // bit offset: 6 desc: TRACE_MODE
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DBGMCU_APB1_FZ = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 Debug MCU APB1 Freeze registe
DBG_TIM2_STOP: bool, // bit offset: 0 desc: DBG_TIM2_STOP
DBG_TIM3_STOP: bool, // bit offset: 1 desc: DBG_TIM3 _STOP
DBG_TIM4_STOP: bool, // bit offset: 2 desc: DBG_TIM4_STOP
DBG_TIM5_STOP: bool, // bit offset: 3 desc: DBG_TIM5_STOP
reserved0: u6 = 0,
DBG_RTC_Stop: bool, // bit offset: 10 desc: RTC stopped when Core is halted
DBG_WWDG_STOP: bool, // bit offset: 11 desc: DBG_WWDG_STOP
DBG_IWDEG_STOP: bool, // bit offset: 12 desc: DBG_IWDEG_STOP
reserved1: u8 = 0,
DBG_I2C1_SMBUS_TIMEOUT: bool, // bit offset: 21 desc: DBG_J2C1_SMBUS_TIMEOUT
DBG_I2C2_SMBUS_TIMEOUT: bool, // bit offset: 22 desc: DBG_J2C2_SMBUS_TIMEOUT
DBG_I2C3SMBUS_TIMEOUT: bool, // bit offset: 23 desc: DBG_J2C3SMBUS_TIMEOUT
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DBGMCU_APB2_FZ = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 Debug MCU APB2 Freeze registe
DBG_TIM1_STOP: bool, // bit offset: 0 desc: TIM1 counter stopped when core is halted
reserved0: u15 = 0,
DBG_TIM9_STOP: bool, // bit offset: 16 desc: TIM9 counter stopped when core is halted
DBG_TIM10_STOP: bool, // bit offset: 17 desc: TIM10 counter stopped when core is halted
DBG_TIM11_STOP: bool, // bit offset: 18 desc: TIM11 counter stopped when core is halted
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const EXTI = extern struct {
pub const Address: u32 = 0x40013c00;
pub const IMR = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 Interrupt mask register (EXTI_IMR)
MR0: bool, // bit offset: 0 desc: Interrupt Mask on line 0
MR1: bool, // bit offset: 1 desc: Interrupt Mask on line 1
MR2: bool, // bit offset: 2 desc: Interrupt Mask on line 2
MR3: bool, // bit offset: 3 desc: Interrupt Mask on line 3
MR4: bool, // bit offset: 4 desc: Interrupt Mask on line 4
MR5: bool, // bit offset: 5 desc: Interrupt Mask on line 5
MR6: bool, // bit offset: 6 desc: Interrupt Mask on line 6
MR7: bool, // bit offset: 7 desc: Interrupt Mask on line 7
MR8: bool, // bit offset: 8 desc: Interrupt Mask on line 8
MR9: bool, // bit offset: 9 desc: Interrupt Mask on line 9
MR10: bool, // bit offset: 10 desc: Interrupt Mask on line 10
MR11: bool, // bit offset: 11 desc: Interrupt Mask on line 11
MR12: bool, // bit offset: 12 desc: Interrupt Mask on line 12
MR13: bool, // bit offset: 13 desc: Interrupt Mask on line 13
MR14: bool, // bit offset: 14 desc: Interrupt Mask on line 14
MR15: bool, // bit offset: 15 desc: Interrupt Mask on line 15
MR16: bool, // bit offset: 16 desc: Interrupt Mask on line 16
MR17: bool, // bit offset: 17 desc: Interrupt Mask on line 17
MR18: bool, // bit offset: 18 desc: Interrupt Mask on line 18
MR19: bool, // bit offset: 19 desc: Interrupt Mask on line 19
MR20: bool, // bit offset: 20 desc: Interrupt Mask on line 20
MR21: bool, // bit offset: 21 desc: Interrupt Mask on line 21
MR22: bool, // bit offset: 22 desc: Interrupt Mask on line 22
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const EMR = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 Event mask register (EXTI_EMR)
MR0: bool, // bit offset: 0 desc: Event Mask on line 0
MR1: bool, // bit offset: 1 desc: Event Mask on line 1
MR2: bool, // bit offset: 2 desc: Event Mask on line 2
MR3: bool, // bit offset: 3 desc: Event Mask on line 3
MR4: bool, // bit offset: 4 desc: Event Mask on line 4
MR5: bool, // bit offset: 5 desc: Event Mask on line 5
MR6: bool, // bit offset: 6 desc: Event Mask on line 6
MR7: bool, // bit offset: 7 desc: Event Mask on line 7
MR8: bool, // bit offset: 8 desc: Event Mask on line 8
MR9: bool, // bit offset: 9 desc: Event Mask on line 9
MR10: bool, // bit offset: 10 desc: Event Mask on line 10
MR11: bool, // bit offset: 11 desc: Event Mask on line 11
MR12: bool, // bit offset: 12 desc: Event Mask on line 12
MR13: bool, // bit offset: 13 desc: Event Mask on line 13
MR14: bool, // bit offset: 14 desc: Event Mask on line 14
MR15: bool, // bit offset: 15 desc: Event Mask on line 15
MR16: bool, // bit offset: 16 desc: Event Mask on line 16
MR17: bool, // bit offset: 17 desc: Event Mask on line 17
MR18: bool, // bit offset: 18 desc: Event Mask on line 18
MR19: bool, // bit offset: 19 desc: Event Mask on line 19
MR20: bool, // bit offset: 20 desc: Event Mask on line 20
MR21: bool, // bit offset: 21 desc: Event Mask on line 21
MR22: bool, // bit offset: 22 desc: Event Mask on line 22
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const RTSR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 Rising Trigger selection register (EXTI_RTSR)
TR0: bool, // bit offset: 0 desc: Rising trigger event configuration of line 0
TR1: bool, // bit offset: 1 desc: Rising trigger event configuration of line 1
TR2: bool, // bit offset: 2 desc: Rising trigger event configuration of line 2
TR3: bool, // bit offset: 3 desc: Rising trigger event configuration of line 3
TR4: bool, // bit offset: 4 desc: Rising trigger event configuration of line 4
TR5: bool, // bit offset: 5 desc: Rising trigger event configuration of line 5
TR6: bool, // bit offset: 6 desc: Rising trigger event configuration of line 6
TR7: bool, // bit offset: 7 desc: Rising trigger event configuration of line 7
TR8: bool, // bit offset: 8 desc: Rising trigger event configuration of line 8
TR9: bool, // bit offset: 9 desc: Rising trigger event configuration of line 9
TR10: bool, // bit offset: 10 desc: Rising trigger event configuration of line 10
TR11: bool, // bit offset: 11 desc: Rising trigger event configuration of line 11
TR12: bool, // bit offset: 12 desc: Rising trigger event configuration of line 12
TR13: bool, // bit offset: 13 desc: Rising trigger event configuration of line 13
TR14: bool, // bit offset: 14 desc: Rising trigger event configuration of line 14
TR15: bool, // bit offset: 15 desc: Rising trigger event configuration of line 15
TR16: bool, // bit offset: 16 desc: Rising trigger event configuration of line 16
TR17: bool, // bit offset: 17 desc: Rising trigger event configuration of line 17
TR18: bool, // bit offset: 18 desc: Rising trigger event configuration of line 18
TR19: bool, // bit offset: 19 desc: Rising trigger event configuration of line 19
TR20: bool, // bit offset: 20 desc: Rising trigger event configuration of line 20
TR21: bool, // bit offset: 21 desc: Rising trigger event configuration of line 21
TR22: bool, // bit offset: 22 desc: Rising trigger event configuration of line 22
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FTSR = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 Falling Trigger selection register (EXTI_FTSR)
TR0: bool, // bit offset: 0 desc: Falling trigger event configuration of line 0
TR1: bool, // bit offset: 1 desc: Falling trigger event configuration of line 1
TR2: bool, // bit offset: 2 desc: Falling trigger event configuration of line 2
TR3: bool, // bit offset: 3 desc: Falling trigger event configuration of line 3
TR4: bool, // bit offset: 4 desc: Falling trigger event configuration of line 4
TR5: bool, // bit offset: 5 desc: Falling trigger event configuration of line 5
TR6: bool, // bit offset: 6 desc: Falling trigger event configuration of line 6
TR7: bool, // bit offset: 7 desc: Falling trigger event configuration of line 7
TR8: bool, // bit offset: 8 desc: Falling trigger event configuration of line 8
TR9: bool, // bit offset: 9 desc: Falling trigger event configuration of line 9
TR10: bool, // bit offset: 10 desc: Falling trigger event configuration of line 10
TR11: bool, // bit offset: 11 desc: Falling trigger event configuration of line 11
TR12: bool, // bit offset: 12 desc: Falling trigger event configuration of line 12
TR13: bool, // bit offset: 13 desc: Falling trigger event configuration of line 13
TR14: bool, // bit offset: 14 desc: Falling trigger event configuration of line 14
TR15: bool, // bit offset: 15 desc: Falling trigger event configuration of line 15
TR16: bool, // bit offset: 16 desc: Falling trigger event configuration of line 16
TR17: bool, // bit offset: 17 desc: Falling trigger event configuration of line 17
TR18: bool, // bit offset: 18 desc: Falling trigger event configuration of line 18
TR19: bool, // bit offset: 19 desc: Falling trigger event configuration of line 19
TR20: bool, // bit offset: 20 desc: Falling trigger event configuration of line 20
TR21: bool, // bit offset: 21 desc: Falling trigger event configuration of line 21
TR22: bool, // bit offset: 22 desc: Falling trigger event configuration of line 22
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SWIER = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 Software interrupt event register (EXTI_SWIER)
SWIER0: bool, // bit offset: 0 desc: Software Interrupt on line 0
SWIER1: bool, // bit offset: 1 desc: Software Interrupt on line 1
SWIER2: bool, // bit offset: 2 desc: Software Interrupt on line 2
SWIER3: bool, // bit offset: 3 desc: Software Interrupt on line 3
SWIER4: bool, // bit offset: 4 desc: Software Interrupt on line 4
SWIER5: bool, // bit offset: 5 desc: Software Interrupt on line 5
SWIER6: bool, // bit offset: 6 desc: Software Interrupt on line 6
SWIER7: bool, // bit offset: 7 desc: Software Interrupt on line 7
SWIER8: bool, // bit offset: 8 desc: Software Interrupt on line 8
SWIER9: bool, // bit offset: 9 desc: Software Interrupt on line 9
SWIER10: bool, // bit offset: 10 desc: Software Interrupt on line 10
SWIER11: bool, // bit offset: 11 desc: Software Interrupt on line 11
SWIER12: bool, // bit offset: 12 desc: Software Interrupt on line 12
SWIER13: bool, // bit offset: 13 desc: Software Interrupt on line 13
SWIER14: bool, // bit offset: 14 desc: Software Interrupt on line 14
SWIER15: bool, // bit offset: 15 desc: Software Interrupt on line 15
SWIER16: bool, // bit offset: 16 desc: Software Interrupt on line 16
SWIER17: bool, // bit offset: 17 desc: Software Interrupt on line 17
SWIER18: bool, // bit offset: 18 desc: Software Interrupt on line 18
SWIER19: bool, // bit offset: 19 desc: Software Interrupt on line 19
SWIER20: bool, // bit offset: 20 desc: Software Interrupt on line 20
SWIER21: bool, // bit offset: 21 desc: Software Interrupt on line 21
SWIER22: bool, // bit offset: 22 desc: Software Interrupt on line 22
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const PR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 Pending register (EXTI_PR)
PR0: bool, // bit offset: 0 desc: Pending bit 0
PR1: bool, // bit offset: 1 desc: Pending bit 1
PR2: bool, // bit offset: 2 desc: Pending bit 2
PR3: bool, // bit offset: 3 desc: Pending bit 3
PR4: bool, // bit offset: 4 desc: Pending bit 4
PR5: bool, // bit offset: 5 desc: Pending bit 5
PR6: bool, // bit offset: 6 desc: Pending bit 6
PR7: bool, // bit offset: 7 desc: Pending bit 7
PR8: bool, // bit offset: 8 desc: Pending bit 8
PR9: bool, // bit offset: 9 desc: Pending bit 9
PR10: bool, // bit offset: 10 desc: Pending bit 10
PR11: bool, // bit offset: 11 desc: Pending bit 11
PR12: bool, // bit offset: 12 desc: Pending bit 12
PR13: bool, // bit offset: 13 desc: Pending bit 13
PR14: bool, // bit offset: 14 desc: Pending bit 14
PR15: bool, // bit offset: 15 desc: Pending bit 15
PR16: bool, // bit offset: 16 desc: Pending bit 16
PR17: bool, // bit offset: 17 desc: Pending bit 17
PR18: bool, // bit offset: 18 desc: Pending bit 18
PR19: bool, // bit offset: 19 desc: Pending bit 19
PR20: bool, // bit offset: 20 desc: Pending bit 20
PR21: bool, // bit offset: 21 desc: Pending bit 21
PR22: bool, // bit offset: 22 desc: Pending bit 22
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const FLASH = extern struct {
pub const Address: u32 = 0x40023c00;
pub const ACR = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 Flash access control register
LATENCY: u3, // bit offset: 0 desc: Latency
reserved0: u5 = 0,
PRFTEN: bool, // bit offset: 8 desc: Prefetch enable
ICEN: bool, // bit offset: 9 desc: Instruction cache enable
DCEN: bool, // bit offset: 10 desc: Data cache enable
ICRST: bool, // bit offset: 11 desc: Instruction cache reset
DCRST: bool, // bit offset: 12 desc: Data cache reset
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const KEYR = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 Flash key register
KEY: u32, // bit offset: 0 desc: FPEC key
});
pub const OPTKEYR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 Flash option key register
OPTKEY: u32, // bit offset: 0 desc: Option byte key
});
pub const SR = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 Status register
EOP: bool, // bit offset: 0 desc: End of operation
OPERR: bool, // bit offset: 1 desc: Operation error
reserved0: u2 = 0,
WRPERR: bool, // bit offset: 4 desc: Write protection error
PGAERR: bool, // bit offset: 5 desc: Programming alignment error
PGPERR: bool, // bit offset: 6 desc: Programming parallelism error
PGSERR: bool, // bit offset: 7 desc: Programming sequence error
reserved1: u8 = 0,
BSY: bool, // bit offset: 16 desc: Busy
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 Control register
PG: bool, // bit offset: 0 desc: Programming
SER: bool, // bit offset: 1 desc: Sector Erase
MER: bool, // bit offset: 2 desc: Mass Erase
SNB: u4, // bit offset: 3 desc: Sector number
reserved0: u1 = 0,
PSIZE: u2, // bit offset: 8 desc: Program size
reserved1: u6 = 0,
STRT: bool, // bit offset: 16 desc: Start
reserved2: u7 = 0,
EOPIE: bool, // bit offset: 24 desc: End of operation interrupt enable
ERRIE: bool, // bit offset: 25 desc: Error interrupt enable
reserved3: u5 = 0,
LOCK: bool, // bit offset: 31 desc: Lock
});
pub const OPTCR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 Flash option control register
OPTLOCK: bool, // bit offset: 0 desc: Option lock
OPTSTRT: bool, // bit offset: 1 desc: Option start
BOR_LEV: u2, // bit offset: 2 desc: BOR reset Level
reserved0: u1 = 0,
WDG_SW: bool, // bit offset: 5 desc: WDG_SW User option bytes
nRST_STOP: bool, // bit offset: 6 desc: nRST_STOP User option bytes
nRST_STDBY: bool, // bit offset: 7 desc: nRST_STDBY User option bytes
RDP: u8, // bit offset: 8 desc: Read protect
nWRP: u12, // bit offset: 16 desc: Not write protect
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const IWDG = extern struct {
pub const Address: u32 = 0x40003000;
pub const KR = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 Key register
KEY: u16, // bit offset: 0 desc: Key value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const PR = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 Prescaler register
PR: u3, // bit offset: 0 desc: Prescaler divider
padding29: u1 = 0,
padding28: u1 = 0,
padding27: u1 = 0,
padding26: u1 = 0,
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const RLR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 Reload register
RL: u12, // bit offset: 0 desc: Watchdog counter reload value
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SR = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 Status register
PVU: bool, // bit offset: 0 desc: Watchdog prescaler value update
RVU: bool, // bit offset: 1 desc: Watchdog counter reload value update
padding30: u1 = 0,
padding29: u1 = 0,
padding28: u1 = 0,
padding27: u1 = 0,
padding26: u1 = 0,
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const OTG_FS_DEVICE = extern struct {
pub const Address: u32 = 0x50000800;
pub const FS_DCFG = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 OTG_FS device configuration register (OTG_FS_DCFG)
DSPD: u2, // bit offset: 0 desc: Device speed
NZLSOHSK: bool, // bit offset: 2 desc: Non-zero-length status OUT handshake
reserved0: u1 = 0,
DAD: u7, // bit offset: 4 desc: Device address
PFIVL: u2, // bit offset: 11 desc: Periodic frame interval
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_DCTL = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 OTG_FS device control register (OTG_FS_DCTL)
RWUSIG: bool, // bit offset: 0 desc: Remote wakeup signaling
SDIS: bool, // bit offset: 1 desc: Soft disconnect
GINSTS: bool, // bit offset: 2 desc: Global IN NAK status
GONSTS: bool, // bit offset: 3 desc: Global OUT NAK status
TCTL: u3, // bit offset: 4 desc: Test control
SGINAK: bool, // bit offset: 7 desc: Set global IN NAK
CGINAK: bool, // bit offset: 8 desc: Clear global IN NAK
SGONAK: bool, // bit offset: 9 desc: Set global OUT NAK
CGONAK: bool, // bit offset: 10 desc: Clear global OUT NAK
POPRGDNE: bool, // bit offset: 11 desc: Power-on programming done
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_DSTS = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 OTG_FS device status register (OTG_FS_DSTS)
SUSPSTS: bool, // bit offset: 0 desc: Suspend status
ENUMSPD: u2, // bit offset: 1 desc: Enumerated speed
EERR: bool, // bit offset: 3 desc: Erratic error
reserved0: u4 = 0,
FNSOF: u14, // bit offset: 8 desc: Frame number of the received SOF
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_DIEPMSK = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 OTG_FS device IN endpoint common interrupt mask register (OTG_FS_DIEPMSK)
XFRCM: bool, // bit offset: 0 desc: Transfer completed interrupt mask
EPDM: bool, // bit offset: 1 desc: Endpoint disabled interrupt mask
reserved0: u1 = 0,
TOM: bool, // bit offset: 3 desc: Timeout condition mask (Non-isochronous endpoints)
ITTXFEMSK: bool, // bit offset: 4 desc: IN token received when TxFIFO empty mask
INEPNMM: bool, // bit offset: 5 desc: IN token received with EP mismatch mask
INEPNEM: bool, // bit offset: 6 desc: IN endpoint NAK effective mask
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_DOEPMSK = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 OTG_FS device OUT endpoint common interrupt mask register (OTG_FS_DOEPMSK)
XFRCM: bool, // bit offset: 0 desc: Transfer completed interrupt mask
EPDM: bool, // bit offset: 1 desc: Endpoint disabled interrupt mask
reserved0: u1 = 0,
STUPM: bool, // bit offset: 3 desc: SETUP phase done mask
OTEPDM: bool, // bit offset: 4 desc: OUT token received when endpoint disabled mask
padding27: u1 = 0,
padding26: u1 = 0,
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_DAINT = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 OTG_FS device all endpoints interrupt register (OTG_FS_DAINT)
IEPINT: u16, // bit offset: 0 desc: IN endpoint interrupt bits
OEPINT: u16, // bit offset: 16 desc: OUT endpoint interrupt bits
});
pub const FS_DAINTMSK = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 OTG_FS all endpoints interrupt mask register (OTG_FS_DAINTMSK)
IEPM: u16, // bit offset: 0 desc: IN EP interrupt mask bits
OEPINT: u16, // bit offset: 16 desc: OUT endpoint interrupt bits
});
pub const DVBUSDIS = MMIO(Address + 0x00000028, u32, packed struct { // byte offset: 40 OTG_FS device VBUS discharge time register
VBUSDT: u16, // bit offset: 0 desc: Device VBUS discharge time
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DVBUSPULSE = MMIO(Address + 0x0000002c, u32, packed struct { // byte offset: 44 OTG_FS device VBUS pulsing time register
DVBUSP: u12, // bit offset: 0 desc: Device VBUS pulsing time
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DIEPEMPMSK = MMIO(Address + 0x00000034, u32, packed struct { // byte offset: 52 OTG_FS device IN endpoint FIFO empty interrupt mask register
INEPTXFEM: u16, // bit offset: 0 desc: IN EP Tx FIFO empty interrupt mask bits
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_DIEPCTL0 = MMIO(Address + 0x00000100, u32, packed struct { // byte offset: 256 OTG_FS device control IN endpoint 0 control register (OTG_FS_DIEPCTL0)
MPSIZ: u2, // bit offset: 0 desc: Maximum packet size
reserved0: u13 = 0,
USBAEP: bool, // bit offset: 15 desc: USB active endpoint
reserved1: u1 = 0,
NAKSTS: bool, // bit offset: 17 desc: NAK status
EPTYP: u2, // bit offset: 18 desc: Endpoint type
reserved2: u1 = 0,
STALL: bool, // bit offset: 21 desc: STALL handshake
TXFNUM: u4, // bit offset: 22 desc: TxFIFO number
CNAK: bool, // bit offset: 26 desc: Clear NAK
SNAK: bool, // bit offset: 27 desc: Set NAK
reserved3: u2 = 0,
EPDIS: bool, // bit offset: 30 desc: Endpoint disable
EPENA: bool, // bit offset: 31 desc: Endpoint enable
});
pub const DIEPINT0 = MMIO(Address + 0x00000108, u32, packed struct { // byte offset: 264 device endpoint-x interrupt register
XFRC: bool, // bit offset: 0 desc: XFRC
EPDISD: bool, // bit offset: 1 desc: EPDISD
reserved0: u1 = 0,
TOC: bool, // bit offset: 3 desc: TOC
ITTXFE: bool, // bit offset: 4 desc: ITTXFE
reserved1: u1 = 0,
INEPNE: bool, // bit offset: 6 desc: INEPNE
TXFE: bool, // bit offset: 7 desc: TXFE
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DIEPTSIZ0 = MMIO(Address + 0x00000110, u32, packed struct { // byte offset: 272 device endpoint-0 transfer size register
XFRSIZ: u7, // bit offset: 0 desc: Transfer size
reserved0: u12 = 0,
PKTCNT: u2, // bit offset: 19 desc: Packet count
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DTXFSTS0 = MMIO(Address + 0x00000118, u32, packed struct { // byte offset: 280 OTG_FS device IN endpoint transmit FIFO status register
INEPTFSAV: u16, // bit offset: 0 desc: IN endpoint TxFIFO space available
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DIEPCTL1 = MMIO(Address + 0x00000120, u32, packed struct { // byte offset: 288 OTG device endpoint-1 control register
MPSIZ: u11, // bit offset: 0 desc: MPSIZ
reserved0: u4 = 0,
USBAEP: bool, // bit offset: 15 desc: USBAEP
EONUM_DPID: bool, // bit offset: 16 desc: EONUM/DPID
NAKSTS: bool, // bit offset: 17 desc: NAKSTS
EPTYP: u2, // bit offset: 18 desc: EPTYP
reserved1: u1 = 0,
Stall: bool, // bit offset: 21 desc: Stall
TXFNUM: u4, // bit offset: 22 desc: TXFNUM
CNAK: bool, // bit offset: 26 desc: CNAK
SNAK: bool, // bit offset: 27 desc: SNAK
SD0PID_SEVNFRM: bool, // bit offset: 28 desc: SD0PID/SEVNFRM
SODDFRM_SD1PID: bool, // bit offset: 29 desc: SODDFRM/SD1PID
EPDIS: bool, // bit offset: 30 desc: EPDIS
EPENA: bool, // bit offset: 31 desc: EPENA
});
pub const DIEPINT1 = MMIO(Address + 0x00000128, u32, packed struct { // byte offset: 296 device endpoint-1 interrupt register
XFRC: bool, // bit offset: 0 desc: XFRC
EPDISD: bool, // bit offset: 1 desc: EPDISD
reserved0: u1 = 0,
TOC: bool, // bit offset: 3 desc: TOC
ITTXFE: bool, // bit offset: 4 desc: ITTXFE
reserved1: u1 = 0,
INEPNE: bool, // bit offset: 6 desc: INEPNE
TXFE: bool, // bit offset: 7 desc: TXFE
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DIEPTSIZ1 = MMIO(Address + 0x00000130, u32, packed struct { // byte offset: 304 device endpoint-1 transfer size register
XFRSIZ: u19, // bit offset: 0 desc: Transfer size
PKTCNT: u10, // bit offset: 19 desc: Packet count
MCNT: u2, // bit offset: 29 desc: Multi count
padding1: u1 = 0,
});
pub const DTXFSTS1 = MMIO(Address + 0x00000138, u32, packed struct { // byte offset: 312 OTG_FS device IN endpoint transmit FIFO status register
INEPTFSAV: u16, // bit offset: 0 desc: IN endpoint TxFIFO space available
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DIEPCTL2 = MMIO(Address + 0x00000140, u32, packed struct { // byte offset: 320 OTG device endpoint-2 control register
MPSIZ: u11, // bit offset: 0 desc: MPSIZ
reserved0: u4 = 0,
USBAEP: bool, // bit offset: 15 desc: USBAEP
EONUM_DPID: bool, // bit offset: 16 desc: EONUM/DPID
NAKSTS: bool, // bit offset: 17 desc: NAKSTS
EPTYP: u2, // bit offset: 18 desc: EPTYP
reserved1: u1 = 0,
Stall: bool, // bit offset: 21 desc: Stall
TXFNUM: u4, // bit offset: 22 desc: TXFNUM
CNAK: bool, // bit offset: 26 desc: CNAK
SNAK: bool, // bit offset: 27 desc: SNAK
SD0PID_SEVNFRM: bool, // bit offset: 28 desc: SD0PID/SEVNFRM
SODDFRM: bool, // bit offset: 29 desc: SODDFRM
EPDIS: bool, // bit offset: 30 desc: EPDIS
EPENA: bool, // bit offset: 31 desc: EPENA
});
pub const DIEPINT2 = MMIO(Address + 0x00000148, u32, packed struct { // byte offset: 328 device endpoint-2 interrupt register
XFRC: bool, // bit offset: 0 desc: XFRC
EPDISD: bool, // bit offset: 1 desc: EPDISD
reserved0: u1 = 0,
TOC: bool, // bit offset: 3 desc: TOC
ITTXFE: bool, // bit offset: 4 desc: ITTXFE
reserved1: u1 = 0,
INEPNE: bool, // bit offset: 6 desc: INEPNE
TXFE: bool, // bit offset: 7 desc: TXFE
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DIEPTSIZ2 = MMIO(Address + 0x00000150, u32, packed struct { // byte offset: 336 device endpoint-2 transfer size register
XFRSIZ: u19, // bit offset: 0 desc: Transfer size
PKTCNT: u10, // bit offset: 19 desc: Packet count
MCNT: u2, // bit offset: 29 desc: Multi count
padding1: u1 = 0,
});
pub const DTXFSTS2 = MMIO(Address + 0x00000158, u32, packed struct { // byte offset: 344 OTG_FS device IN endpoint transmit FIFO status register
INEPTFSAV: u16, // bit offset: 0 desc: IN endpoint TxFIFO space available
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DIEPCTL3 = MMIO(Address + 0x00000160, u32, packed struct { // byte offset: 352 OTG device endpoint-3 control register
MPSIZ: u11, // bit offset: 0 desc: MPSIZ
reserved0: u4 = 0,
USBAEP: bool, // bit offset: 15 desc: USBAEP
EONUM_DPID: bool, // bit offset: 16 desc: EONUM/DPID
NAKSTS: bool, // bit offset: 17 desc: NAKSTS
EPTYP: u2, // bit offset: 18 desc: EPTYP
reserved1: u1 = 0,
Stall: bool, // bit offset: 21 desc: Stall
TXFNUM: u4, // bit offset: 22 desc: TXFNUM
CNAK: bool, // bit offset: 26 desc: CNAK
SNAK: bool, // bit offset: 27 desc: SNAK
SD0PID_SEVNFRM: bool, // bit offset: 28 desc: SD0PID/SEVNFRM
SODDFRM: bool, // bit offset: 29 desc: SODDFRM
EPDIS: bool, // bit offset: 30 desc: EPDIS
EPENA: bool, // bit offset: 31 desc: EPENA
});
pub const DIEPINT3 = MMIO(Address + 0x00000168, u32, packed struct { // byte offset: 360 device endpoint-3 interrupt register
XFRC: bool, // bit offset: 0 desc: XFRC
EPDISD: bool, // bit offset: 1 desc: EPDISD
reserved0: u1 = 0,
TOC: bool, // bit offset: 3 desc: TOC
ITTXFE: bool, // bit offset: 4 desc: ITTXFE
reserved1: u1 = 0,
INEPNE: bool, // bit offset: 6 desc: INEPNE
TXFE: bool, // bit offset: 7 desc: TXFE
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DIEPTSIZ3 = MMIO(Address + 0x00000170, u32, packed struct { // byte offset: 368 device endpoint-3 transfer size register
XFRSIZ: u19, // bit offset: 0 desc: Transfer size
PKTCNT: u10, // bit offset: 19 desc: Packet count
MCNT: u2, // bit offset: 29 desc: Multi count
padding1: u1 = 0,
});
pub const DTXFSTS3 = MMIO(Address + 0x00000178, u32, packed struct { // byte offset: 376 OTG_FS device IN endpoint transmit FIFO status register
INEPTFSAV: u16, // bit offset: 0 desc: IN endpoint TxFIFO space available
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DOEPCTL0 = MMIO(Address + 0x00000300, u32, packed struct { // byte offset: 768 device endpoint-0 control register
MPSIZ: u2, // bit offset: 0 desc: MPSIZ
reserved0: u13 = 0,
USBAEP: bool, // bit offset: 15 desc: USBAEP
reserved1: u1 = 0,
NAKSTS: bool, // bit offset: 17 desc: NAKSTS
EPTYP: u2, // bit offset: 18 desc: EPTYP
SNPM: bool, // bit offset: 20 desc: SNPM
Stall: bool, // bit offset: 21 desc: Stall
reserved2: u4 = 0,
CNAK: bool, // bit offset: 26 desc: CNAK
SNAK: bool, // bit offset: 27 desc: SNAK
reserved3: u2 = 0,
EPDIS: bool, // bit offset: 30 desc: EPDIS
EPENA: bool, // bit offset: 31 desc: EPENA
});
pub const DOEPINT0 = MMIO(Address + 0x00000308, u32, packed struct { // byte offset: 776 device endpoint-0 interrupt register
XFRC: bool, // bit offset: 0 desc: XFRC
EPDISD: bool, // bit offset: 1 desc: EPDISD
reserved0: u1 = 0,
STUP: bool, // bit offset: 3 desc: STUP
OTEPDIS: bool, // bit offset: 4 desc: OTEPDIS
reserved1: u1 = 0,
B2BSTUP: bool, // bit offset: 6 desc: B2BSTUP
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DOEPTSIZ0 = MMIO(Address + 0x00000310, u32, packed struct { // byte offset: 784 device OUT endpoint-0 transfer size register
XFRSIZ: u7, // bit offset: 0 desc: Transfer size
reserved0: u12 = 0,
PKTCNT: bool, // bit offset: 19 desc: Packet count
reserved1: u9 = 0,
STUPCNT: u2, // bit offset: 29 desc: SETUP packet count
padding1: u1 = 0,
});
pub const DOEPCTL1 = MMIO(Address + 0x00000320, u32, packed struct { // byte offset: 800 device endpoint-1 control register
MPSIZ: u11, // bit offset: 0 desc: MPSIZ
reserved0: u4 = 0,
USBAEP: bool, // bit offset: 15 desc: USBAEP
EONUM_DPID: bool, // bit offset: 16 desc: EONUM/DPID
NAKSTS: bool, // bit offset: 17 desc: NAKSTS
EPTYP: u2, // bit offset: 18 desc: EPTYP
SNPM: bool, // bit offset: 20 desc: SNPM
Stall: bool, // bit offset: 21 desc: Stall
reserved1: u4 = 0,
CNAK: bool, // bit offset: 26 desc: CNAK
SNAK: bool, // bit offset: 27 desc: SNAK
SD0PID_SEVNFRM: bool, // bit offset: 28 desc: SD0PID/SEVNFRM
SODDFRM: bool, // bit offset: 29 desc: SODDFRM
EPDIS: bool, // bit offset: 30 desc: EPDIS
EPENA: bool, // bit offset: 31 desc: EPENA
});
pub const DOEPINT1 = MMIO(Address + 0x00000328, u32, packed struct { // byte offset: 808 device endpoint-1 interrupt register
XFRC: bool, // bit offset: 0 desc: XFRC
EPDISD: bool, // bit offset: 1 desc: EPDISD
reserved0: u1 = 0,
STUP: bool, // bit offset: 3 desc: STUP
OTEPDIS: bool, // bit offset: 4 desc: OTEPDIS
reserved1: u1 = 0,
B2BSTUP: bool, // bit offset: 6 desc: B2BSTUP
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DOEPTSIZ1 = MMIO(Address + 0x00000330, u32, packed struct { // byte offset: 816 device OUT endpoint-1 transfer size register
XFRSIZ: u19, // bit offset: 0 desc: Transfer size
PKTCNT: u10, // bit offset: 19 desc: Packet count
RXDPID_STUPCNT: u2, // bit offset: 29 desc: Received data PID/SETUP packet count
padding1: u1 = 0,
});
pub const DOEPCTL2 = MMIO(Address + 0x00000340, u32, packed struct { // byte offset: 832 device endpoint-2 control register
MPSIZ: u11, // bit offset: 0 desc: MPSIZ
reserved0: u4 = 0,
USBAEP: bool, // bit offset: 15 desc: USBAEP
EONUM_DPID: bool, // bit offset: 16 desc: EONUM/DPID
NAKSTS: bool, // bit offset: 17 desc: NAKSTS
EPTYP: u2, // bit offset: 18 desc: EPTYP
SNPM: bool, // bit offset: 20 desc: SNPM
Stall: bool, // bit offset: 21 desc: Stall
reserved1: u4 = 0,
CNAK: bool, // bit offset: 26 desc: CNAK
SNAK: bool, // bit offset: 27 desc: SNAK
SD0PID_SEVNFRM: bool, // bit offset: 28 desc: SD0PID/SEVNFRM
SODDFRM: bool, // bit offset: 29 desc: SODDFRM
EPDIS: bool, // bit offset: 30 desc: EPDIS
EPENA: bool, // bit offset: 31 desc: EPENA
});
pub const DOEPINT2 = MMIO(Address + 0x00000348, u32, packed struct { // byte offset: 840 device endpoint-2 interrupt register
XFRC: bool, // bit offset: 0 desc: XFRC
EPDISD: bool, // bit offset: 1 desc: EPDISD
reserved0: u1 = 0,
STUP: bool, // bit offset: 3 desc: STUP
OTEPDIS: bool, // bit offset: 4 desc: OTEPDIS
reserved1: u1 = 0,
B2BSTUP: bool, // bit offset: 6 desc: B2BSTUP
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DOEPTSIZ2 = MMIO(Address + 0x00000350, u32, packed struct { // byte offset: 848 device OUT endpoint-2 transfer size register
XFRSIZ: u19, // bit offset: 0 desc: Transfer size
PKTCNT: u10, // bit offset: 19 desc: Packet count
RXDPID_STUPCNT: u2, // bit offset: 29 desc: Received data PID/SETUP packet count
padding1: u1 = 0,
});
pub const DOEPCTL3 = MMIO(Address + 0x00000360, u32, packed struct { // byte offset: 864 device endpoint-3 control register
MPSIZ: u11, // bit offset: 0 desc: MPSIZ
reserved0: u4 = 0,
USBAEP: bool, // bit offset: 15 desc: USBAEP
EONUM_DPID: bool, // bit offset: 16 desc: EONUM/DPID
NAKSTS: bool, // bit offset: 17 desc: NAKSTS
EPTYP: u2, // bit offset: 18 desc: EPTYP
SNPM: bool, // bit offset: 20 desc: SNPM
Stall: bool, // bit offset: 21 desc: Stall
reserved1: u4 = 0,
CNAK: bool, // bit offset: 26 desc: CNAK
SNAK: bool, // bit offset: 27 desc: SNAK
SD0PID_SEVNFRM: bool, // bit offset: 28 desc: SD0PID/SEVNFRM
SODDFRM: bool, // bit offset: 29 desc: SODDFRM
EPDIS: bool, // bit offset: 30 desc: EPDIS
EPENA: bool, // bit offset: 31 desc: EPENA
});
pub const DOEPINT3 = MMIO(Address + 0x00000368, u32, packed struct { // byte offset: 872 device endpoint-3 interrupt register
XFRC: bool, // bit offset: 0 desc: XFRC
EPDISD: bool, // bit offset: 1 desc: EPDISD
reserved0: u1 = 0,
STUP: bool, // bit offset: 3 desc: STUP
OTEPDIS: bool, // bit offset: 4 desc: OTEPDIS
reserved1: u1 = 0,
B2BSTUP: bool, // bit offset: 6 desc: B2BSTUP
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DOEPTSIZ3 = MMIO(Address + 0x00000370, u32, packed struct { // byte offset: 880 device OUT endpoint-3 transfer size register
XFRSIZ: u19, // bit offset: 0 desc: Transfer size
PKTCNT: u10, // bit offset: 19 desc: Packet count
RXDPID_STUPCNT: u2, // bit offset: 29 desc: Received data PID/SETUP packet count
padding1: u1 = 0,
});
};
pub const OTG_FS_GLOBAL = extern struct {
pub const Address: u32 = 0x50000000;
pub const FS_GOTGCTL = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 OTG_FS control and status register (OTG_FS_GOTGCTL)
SRQSCS: bool, // bit offset: 0 desc: Session request success
SRQ: bool, // bit offset: 1 desc: Session request
reserved0: u6 = 0,
HNGSCS: bool, // bit offset: 8 desc: Host negotiation success
HNPRQ: bool, // bit offset: 9 desc: HNP request
HSHNPEN: bool, // bit offset: 10 desc: Host set HNP enable
DHNPEN: bool, // bit offset: 11 desc: Device HNP enabled
reserved1: u4 = 0,
CIDSTS: bool, // bit offset: 16 desc: Connector ID status
DBCT: bool, // bit offset: 17 desc: Long/short debounce time
ASVLD: bool, // bit offset: 18 desc: A-session valid
BSVLD: bool, // bit offset: 19 desc: B-session valid
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_GOTGINT = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 OTG_FS interrupt register (OTG_FS_GOTGINT)
reserved0: u2 = 0,
SEDET: bool, // bit offset: 2 desc: Session end detected
reserved1: u5 = 0,
SRSSCHG: bool, // bit offset: 8 desc: Session request success status change
HNSSCHG: bool, // bit offset: 9 desc: Host negotiation success status change
reserved2: u7 = 0,
HNGDET: bool, // bit offset: 17 desc: Host negotiation detected
ADTOCHG: bool, // bit offset: 18 desc: A-device timeout change
DBCDNE: bool, // bit offset: 19 desc: Debounce done
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_GAHBCFG = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 OTG_FS AHB configuration register (OTG_FS_GAHBCFG)
GINT: bool, // bit offset: 0 desc: Global interrupt mask
reserved0: u6 = 0,
TXFELVL: bool, // bit offset: 7 desc: TxFIFO empty level
PTXFELVL: bool, // bit offset: 8 desc: Periodic TxFIFO empty level
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_GUSBCFG = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 OTG_FS USB configuration register (OTG_FS_GUSBCFG)
TOCAL: u3, // bit offset: 0 desc: FS timeout calibration
reserved0: u3 = 0,
PHYSEL: bool, // bit offset: 6 desc: Full Speed serial transceiver select
reserved1: u1 = 0,
SRPCAP: bool, // bit offset: 8 desc: SRP-capable
HNPCAP: bool, // bit offset: 9 desc: HNP-capable
TRDT: u4, // bit offset: 10 desc: USB turnaround time
reserved2: u15 = 0,
FHMOD: bool, // bit offset: 29 desc: Force host mode
FDMOD: bool, // bit offset: 30 desc: Force device mode
CTXPKT: bool, // bit offset: 31 desc: Corrupt Tx packet
});
pub const FS_GRSTCTL = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 OTG_FS reset register (OTG_FS_GRSTCTL)
CSRST: bool, // bit offset: 0 desc: Core soft reset
HSRST: bool, // bit offset: 1 desc: HCLK soft reset
FCRST: bool, // bit offset: 2 desc: Host frame counter reset
reserved0: u1 = 0,
RXFFLSH: bool, // bit offset: 4 desc: RxFIFO flush
TXFFLSH: bool, // bit offset: 5 desc: TxFIFO flush
TXFNUM: u5, // bit offset: 6 desc: TxFIFO number
reserved1: u20 = 0,
AHBIDL: bool, // bit offset: 31 desc: AHB master idle
});
pub const FS_GINTSTS = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 OTG_FS core interrupt register (OTG_FS_GINTSTS)
CMOD: bool, // bit offset: 0 desc: Current mode of operation
MMIS: bool, // bit offset: 1 desc: Mode mismatch interrupt
OTGINT: bool, // bit offset: 2 desc: OTG interrupt
SOF: bool, // bit offset: 3 desc: Start of frame
RXFLVL: bool, // bit offset: 4 desc: RxFIFO non-empty
NPTXFE: bool, // bit offset: 5 desc: Non-periodic TxFIFO empty
GINAKEFF: bool, // bit offset: 6 desc: Global IN non-periodic NAK effective
GOUTNAKEFF: bool, // bit offset: 7 desc: Global OUT NAK effective
reserved0: u2 = 0,
ESUSP: bool, // bit offset: 10 desc: Early suspend
USBSUSP: bool, // bit offset: 11 desc: USB suspend
USBRST: bool, // bit offset: 12 desc: USB reset
ENUMDNE: bool, // bit offset: 13 desc: Enumeration done
ISOODRP: bool, // bit offset: 14 desc: Isochronous OUT packet dropped interrupt
EOPF: bool, // bit offset: 15 desc: End of periodic frame interrupt
reserved1: u2 = 0,
IEPINT: bool, // bit offset: 18 desc: IN endpoint interrupt
OEPINT: bool, // bit offset: 19 desc: OUT endpoint interrupt
IISOIXFR: bool, // bit offset: 20 desc: Incomplete isochronous IN transfer
IPXFR_INCOMPISOOUT: bool, // bit offset: 21 desc: Incomplete periodic transfer(Host mode)/Incomplete isochronous OUT transfer(Device mode)
reserved2: u2 = 0,
HPRTINT: bool, // bit offset: 24 desc: Host port interrupt
HCINT: bool, // bit offset: 25 desc: Host channels interrupt
PTXFE: bool, // bit offset: 26 desc: Periodic TxFIFO empty
reserved3: u1 = 0,
CIDSCHG: bool, // bit offset: 28 desc: Connector ID status change
DISCINT: bool, // bit offset: 29 desc: Disconnect detected interrupt
SRQINT: bool, // bit offset: 30 desc: Session request/new session detected interrupt
WKUPINT: bool, // bit offset: 31 desc: Resume/remote wakeup detected interrupt
});
pub const FS_GINTMSK = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 OTG_FS interrupt mask register (OTG_FS_GINTMSK)
reserved0: u1 = 0,
MMISM: bool, // bit offset: 1 desc: Mode mismatch interrupt mask
OTGINT: bool, // bit offset: 2 desc: OTG interrupt mask
SOFM: bool, // bit offset: 3 desc: Start of frame mask
RXFLVLM: bool, // bit offset: 4 desc: Receive FIFO non-empty mask
NPTXFEM: bool, // bit offset: 5 desc: Non-periodic TxFIFO empty mask
GINAKEFFM: bool, // bit offset: 6 desc: Global non-periodic IN NAK effective mask
GONAKEFFM: bool, // bit offset: 7 desc: Global OUT NAK effective mask
reserved1: u2 = 0,
ESUSPM: bool, // bit offset: 10 desc: Early suspend mask
USBSUSPM: bool, // bit offset: 11 desc: USB suspend mask
USBRST: bool, // bit offset: 12 desc: USB reset mask
ENUMDNEM: bool, // bit offset: 13 desc: Enumeration done mask
ISOODRPM: bool, // bit offset: 14 desc: Isochronous OUT packet dropped interrupt mask
EOPFM: bool, // bit offset: 15 desc: End of periodic frame interrupt mask
reserved2: u1 = 0,
EPMISM: bool, // bit offset: 17 desc: Endpoint mismatch interrupt mask
IEPINT: bool, // bit offset: 18 desc: IN endpoints interrupt mask
OEPINT: bool, // bit offset: 19 desc: OUT endpoints interrupt mask
IISOIXFRM: bool, // bit offset: 20 desc: Incomplete isochronous IN transfer mask
IPXFRM_IISOOXFRM: bool, // bit offset: 21 desc: Incomplete periodic transfer mask(Host mode)/Incomplete isochronous OUT transfer mask(Device mode)
reserved3: u2 = 0,
PRTIM: bool, // bit offset: 24 desc: Host port interrupt mask
HCIM: bool, // bit offset: 25 desc: Host channels interrupt mask
PTXFEM: bool, // bit offset: 26 desc: Periodic TxFIFO empty mask
reserved4: u1 = 0,
CIDSCHGM: bool, // bit offset: 28 desc: Connector ID status change mask
DISCINT: bool, // bit offset: 29 desc: Disconnect detected interrupt mask
SRQIM: bool, // bit offset: 30 desc: Session request/new session detected interrupt mask
WUIM: bool, // bit offset: 31 desc: Resume/remote wakeup detected interrupt mask
});
pub const FS_GRXSTSR_Device = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 OTG_FS Receive status debug read(Device mode)
EPNUM: u4, // bit offset: 0 desc: Endpoint number
BCNT: u11, // bit offset: 4 desc: Byte count
DPID: u2, // bit offset: 15 desc: Data PID
PKTSTS: u4, // bit offset: 17 desc: Packet status
FRMNUM: u4, // bit offset: 21 desc: Frame number
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_GRXSTSR_Host = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 OTG_FS Receive status debug read(Host mode)
EPNUM: u4, // bit offset: 0 desc: Endpoint number
BCNT: u11, // bit offset: 4 desc: Byte count
DPID: u2, // bit offset: 15 desc: Data PID
PKTSTS: u4, // bit offset: 17 desc: Packet status
FRMNUM: u4, // bit offset: 21 desc: Frame number
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_GRXFSIZ = MMIO(Address + 0x00000024, u32, packed struct { // byte offset: 36 OTG_FS Receive FIFO size register (OTG_FS_GRXFSIZ)
RXFD: u16, // bit offset: 0 desc: RxFIFO depth
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_GNPTXFSIZ_Device = MMIO(Address + 0x00000028, u32, packed struct { // byte offset: 40 OTG_FS non-periodic transmit FIFO size register (Device mode)
TX0FSA: u16, // bit offset: 0 desc: Endpoint 0 transmit RAM start address
TX0FD: u16, // bit offset: 16 desc: Endpoint 0 TxFIFO depth
});
pub const FS_GNPTXFSIZ_Host = MMIO(Address + 0x00000028, u32, packed struct { // byte offset: 40 OTG_FS non-periodic transmit FIFO size register (Host mode)
NPTXFSA: u16, // bit offset: 0 desc: Non-periodic transmit RAM start address
NPTXFD: u16, // bit offset: 16 desc: Non-periodic TxFIFO depth
});
pub const FS_GNPTXSTS = MMIO(Address + 0x0000002c, u32, packed struct { // byte offset: 44 OTG_FS non-periodic transmit FIFO/queue status register (OTG_FS_GNPTXSTS)
NPTXFSAV: u16, // bit offset: 0 desc: Non-periodic TxFIFO space available
NPTQXSAV: u8, // bit offset: 16 desc: Non-periodic transmit request queue space available
NPTXQTOP: u7, // bit offset: 24 desc: Top of the non-periodic transmit request queue
padding1: u1 = 0,
});
pub const FS_GCCFG = MMIO(Address + 0x00000038, u32, packed struct { // byte offset: 56 OTG_FS general core configuration register (OTG_FS_GCCFG)
reserved0: u16 = 0,
PWRDWN: bool, // bit offset: 16 desc: Power down
reserved1: u1 = 0,
VBUSASEN: bool, // bit offset: 18 desc: Enable the VBUS sensing device
VBUSBSEN: bool, // bit offset: 19 desc: Enable the VBUS sensing device
SOFOUTEN: bool, // bit offset: 20 desc: SOF output enable
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_CID = MMIO(Address + 0x0000003c, u32, packed struct { // byte offset: 60 core ID register
PRODUCT_ID: u32, // bit offset: 0 desc: Product ID field
});
pub const FS_HPTXFSIZ = MMIO(Address + 0x00000100, u32, packed struct { // byte offset: 256 OTG_FS Host periodic transmit FIFO size register (OTG_FS_HPTXFSIZ)
PTXSA: u16, // bit offset: 0 desc: Host periodic TxFIFO start address
PTXFSIZ: u16, // bit offset: 16 desc: Host periodic TxFIFO depth
});
pub const FS_DIEPTXF1 = MMIO(Address + 0x00000104, u32, packed struct { // byte offset: 260 OTG_FS device IN endpoint transmit FIFO size register (OTG_FS_DIEPTXF2)
INEPTXSA: u16, // bit offset: 0 desc: IN endpoint FIFO2 transmit RAM start address
INEPTXFD: u16, // bit offset: 16 desc: IN endpoint TxFIFO depth
});
pub const FS_DIEPTXF2 = MMIO(Address + 0x00000108, u32, packed struct { // byte offset: 264 OTG_FS device IN endpoint transmit FIFO size register (OTG_FS_DIEPTXF3)
INEPTXSA: u16, // bit offset: 0 desc: IN endpoint FIFO3 transmit RAM start address
INEPTXFD: u16, // bit offset: 16 desc: IN endpoint TxFIFO depth
});
pub const FS_DIEPTXF3 = MMIO(Address + 0x0000010c, u32, packed struct { // byte offset: 268 OTG_FS device IN endpoint transmit FIFO size register (OTG_FS_DIEPTXF4)
INEPTXSA: u16, // bit offset: 0 desc: IN endpoint FIFO4 transmit RAM start address
INEPTXFD: u16, // bit offset: 16 desc: IN endpoint TxFIFO depth
});
};
pub const OTG_FS_HOST = extern struct {
pub const Address: u32 = 0x50000400;
pub const FS_HCFG = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 OTG_FS host configuration register (OTG_FS_HCFG)
FSLSPCS: u2, // bit offset: 0 desc: FS/LS PHY clock select
FSLSS: bool, // bit offset: 2 desc: FS- and LS-only support
padding29: u1 = 0,
padding28: u1 = 0,
padding27: u1 = 0,
padding26: u1 = 0,
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const HFIR = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 OTG_FS Host frame interval register
FRIVL: u16, // bit offset: 0 desc: Frame interval
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_HFNUM = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 OTG_FS host frame number/frame time remaining register (OTG_FS_HFNUM)
FRNUM: u16, // bit offset: 0 desc: Frame number
FTREM: u16, // bit offset: 16 desc: Frame time remaining
});
pub const FS_HPTXSTS = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 OTG_FS_Host periodic transmit FIFO/queue status register (OTG_FS_HPTXSTS)
PTXFSAVL: u16, // bit offset: 0 desc: Periodic transmit data FIFO space available
PTXQSAV: u8, // bit offset: 16 desc: Periodic transmit request queue space available
PTXQTOP: u8, // bit offset: 24 desc: Top of the periodic transmit request queue
});
pub const HAINT = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 OTG_FS Host all channels interrupt register
HAINT: u16, // bit offset: 0 desc: Channel interrupts
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const HAINTMSK = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 OTG_FS host all channels interrupt mask register
HAINTM: u16, // bit offset: 0 desc: Channel interrupt mask
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_HPRT = MMIO(Address + 0x00000040, u32, packed struct { // byte offset: 64 OTG_FS host port control and status register (OTG_FS_HPRT)
PCSTS: bool, // bit offset: 0 desc: Port connect status
PCDET: bool, // bit offset: 1 desc: Port connect detected
PENA: bool, // bit offset: 2 desc: Port enable
PENCHNG: bool, // bit offset: 3 desc: Port enable/disable change
POCA: bool, // bit offset: 4 desc: Port overcurrent active
POCCHNG: bool, // bit offset: 5 desc: Port overcurrent change
PRES: bool, // bit offset: 6 desc: Port resume
PSUSP: bool, // bit offset: 7 desc: Port suspend
PRST: bool, // bit offset: 8 desc: Port reset
reserved0: u1 = 0,
PLSTS: u2, // bit offset: 10 desc: Port line status
PPWR: bool, // bit offset: 12 desc: Port power
PTCTL: u4, // bit offset: 13 desc: Port test control
PSPD: u2, // bit offset: 17 desc: Port speed
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_HCCHAR0 = MMIO(Address + 0x00000100, u32, packed struct { // byte offset: 256 OTG_FS host channel-0 characteristics register (OTG_FS_HCCHAR0)
MPSIZ: u11, // bit offset: 0 desc: Maximum packet size
EPNUM: u4, // bit offset: 11 desc: Endpoint number
EPDIR: bool, // bit offset: 15 desc: Endpoint direction
reserved0: u1 = 0,
LSDEV: bool, // bit offset: 17 desc: Low-speed device
EPTYP: u2, // bit offset: 18 desc: Endpoint type
MCNT: u2, // bit offset: 20 desc: Multicount
DAD: u7, // bit offset: 22 desc: Device address
ODDFRM: bool, // bit offset: 29 desc: Odd frame
CHDIS: bool, // bit offset: 30 desc: Channel disable
CHENA: bool, // bit offset: 31 desc: Channel enable
});
pub const FS_HCINT0 = MMIO(Address + 0x00000108, u32, packed struct { // byte offset: 264 OTG_FS host channel-0 interrupt register (OTG_FS_HCINT0)
XFRC: bool, // bit offset: 0 desc: Transfer completed
CHH: bool, // bit offset: 1 desc: Channel halted
reserved0: u1 = 0,
STALL: bool, // bit offset: 3 desc: STALL response received interrupt
NAK: bool, // bit offset: 4 desc: NAK response received interrupt
ACK: bool, // bit offset: 5 desc: ACK response received/transmitted interrupt
reserved1: u1 = 0,
TXERR: bool, // bit offset: 7 desc: Transaction error
BBERR: bool, // bit offset: 8 desc: Babble error
FRMOR: bool, // bit offset: 9 desc: Frame overrun
DTERR: bool, // bit offset: 10 desc: Data toggle error
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_HCINTMSK0 = MMIO(Address + 0x0000010c, u32, packed struct { // byte offset: 268 OTG_FS host channel-0 mask register (OTG_FS_HCINTMSK0)
XFRCM: bool, // bit offset: 0 desc: Transfer completed mask
CHHM: bool, // bit offset: 1 desc: Channel halted mask
reserved0: u1 = 0,
STALLM: bool, // bit offset: 3 desc: STALL response received interrupt mask
NAKM: bool, // bit offset: 4 desc: NAK response received interrupt mask
ACKM: bool, // bit offset: 5 desc: ACK response received/transmitted interrupt mask
NYET: bool, // bit offset: 6 desc: response received interrupt mask
TXERRM: bool, // bit offset: 7 desc: Transaction error mask
BBERRM: bool, // bit offset: 8 desc: Babble error mask
FRMORM: bool, // bit offset: 9 desc: Frame overrun mask
DTERRM: bool, // bit offset: 10 desc: Data toggle error mask
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_HCTSIZ0 = MMIO(Address + 0x00000110, u32, packed struct { // byte offset: 272 OTG_FS host channel-0 transfer size register
XFRSIZ: u19, // bit offset: 0 desc: Transfer size
PKTCNT: u10, // bit offset: 19 desc: Packet count
DPID: u2, // bit offset: 29 desc: Data PID
padding1: u1 = 0,
});
pub const FS_HCCHAR1 = MMIO(Address + 0x00000120, u32, packed struct { // byte offset: 288 OTG_FS host channel-1 characteristics register (OTG_FS_HCCHAR1)
MPSIZ: u11, // bit offset: 0 desc: Maximum packet size
EPNUM: u4, // bit offset: 11 desc: Endpoint number
EPDIR: bool, // bit offset: 15 desc: Endpoint direction
reserved0: u1 = 0,
LSDEV: bool, // bit offset: 17 desc: Low-speed device
EPTYP: u2, // bit offset: 18 desc: Endpoint type
MCNT: u2, // bit offset: 20 desc: Multicount
DAD: u7, // bit offset: 22 desc: Device address
ODDFRM: bool, // bit offset: 29 desc: Odd frame
CHDIS: bool, // bit offset: 30 desc: Channel disable
CHENA: bool, // bit offset: 31 desc: Channel enable
});
pub const FS_HCINT1 = MMIO(Address + 0x00000128, u32, packed struct { // byte offset: 296 OTG_FS host channel-1 interrupt register (OTG_FS_HCINT1)
XFRC: bool, // bit offset: 0 desc: Transfer completed
CHH: bool, // bit offset: 1 desc: Channel halted
reserved0: u1 = 0,
STALL: bool, // bit offset: 3 desc: STALL response received interrupt
NAK: bool, // bit offset: 4 desc: NAK response received interrupt
ACK: bool, // bit offset: 5 desc: ACK response received/transmitted interrupt
reserved1: u1 = 0,
TXERR: bool, // bit offset: 7 desc: Transaction error
BBERR: bool, // bit offset: 8 desc: Babble error
FRMOR: bool, // bit offset: 9 desc: Frame overrun
DTERR: bool, // bit offset: 10 desc: Data toggle error
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_HCINTMSK1 = MMIO(Address + 0x0000012c, u32, packed struct { // byte offset: 300 OTG_FS host channel-1 mask register (OTG_FS_HCINTMSK1)
XFRCM: bool, // bit offset: 0 desc: Transfer completed mask
CHHM: bool, // bit offset: 1 desc: Channel halted mask
reserved0: u1 = 0,
STALLM: bool, // bit offset: 3 desc: STALL response received interrupt mask
NAKM: bool, // bit offset: 4 desc: NAK response received interrupt mask
ACKM: bool, // bit offset: 5 desc: ACK response received/transmitted interrupt mask
NYET: bool, // bit offset: 6 desc: response received interrupt mask
TXERRM: bool, // bit offset: 7 desc: Transaction error mask
BBERRM: bool, // bit offset: 8 desc: Babble error mask
FRMORM: bool, // bit offset: 9 desc: Frame overrun mask
DTERRM: bool, // bit offset: 10 desc: Data toggle error mask
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_HCTSIZ1 = MMIO(Address + 0x00000130, u32, packed struct { // byte offset: 304 OTG_FS host channel-1 transfer size register
XFRSIZ: u19, // bit offset: 0 desc: Transfer size
PKTCNT: u10, // bit offset: 19 desc: Packet count
DPID: u2, // bit offset: 29 desc: Data PID
padding1: u1 = 0,
});
pub const FS_HCCHAR2 = MMIO(Address + 0x00000140, u32, packed struct { // byte offset: 320 OTG_FS host channel-2 characteristics register (OTG_FS_HCCHAR2)
MPSIZ: u11, // bit offset: 0 desc: Maximum packet size
EPNUM: u4, // bit offset: 11 desc: Endpoint number
EPDIR: bool, // bit offset: 15 desc: Endpoint direction
reserved0: u1 = 0,
LSDEV: bool, // bit offset: 17 desc: Low-speed device
EPTYP: u2, // bit offset: 18 desc: Endpoint type
MCNT: u2, // bit offset: 20 desc: Multicount
DAD: u7, // bit offset: 22 desc: Device address
ODDFRM: bool, // bit offset: 29 desc: Odd frame
CHDIS: bool, // bit offset: 30 desc: Channel disable
CHENA: bool, // bit offset: 31 desc: Channel enable
});
pub const FS_HCINT2 = MMIO(Address + 0x00000148, u32, packed struct { // byte offset: 328 OTG_FS host channel-2 interrupt register (OTG_FS_HCINT2)
XFRC: bool, // bit offset: 0 desc: Transfer completed
CHH: bool, // bit offset: 1 desc: Channel halted
reserved0: u1 = 0,
STALL: bool, // bit offset: 3 desc: STALL response received interrupt
NAK: bool, // bit offset: 4 desc: NAK response received interrupt
ACK: bool, // bit offset: 5 desc: ACK response received/transmitted interrupt
reserved1: u1 = 0,
TXERR: bool, // bit offset: 7 desc: Transaction error
BBERR: bool, // bit offset: 8 desc: Babble error
FRMOR: bool, // bit offset: 9 desc: Frame overrun
DTERR: bool, // bit offset: 10 desc: Data toggle error
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_HCINTMSK2 = MMIO(Address + 0x0000014c, u32, packed struct { // byte offset: 332 OTG_FS host channel-2 mask register (OTG_FS_HCINTMSK2)
XFRCM: bool, // bit offset: 0 desc: Transfer completed mask
CHHM: bool, // bit offset: 1 desc: Channel halted mask
reserved0: u1 = 0,
STALLM: bool, // bit offset: 3 desc: STALL response received interrupt mask
NAKM: bool, // bit offset: 4 desc: NAK response received interrupt mask
ACKM: bool, // bit offset: 5 desc: ACK response received/transmitted interrupt mask
NYET: bool, // bit offset: 6 desc: response received interrupt mask
TXERRM: bool, // bit offset: 7 desc: Transaction error mask
BBERRM: bool, // bit offset: 8 desc: Babble error mask
FRMORM: bool, // bit offset: 9 desc: Frame overrun mask
DTERRM: bool, // bit offset: 10 desc: Data toggle error mask
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_HCTSIZ2 = MMIO(Address + 0x00000150, u32, packed struct { // byte offset: 336 OTG_FS host channel-2 transfer size register
XFRSIZ: u19, // bit offset: 0 desc: Transfer size
PKTCNT: u10, // bit offset: 19 desc: Packet count
DPID: u2, // bit offset: 29 desc: Data PID
padding1: u1 = 0,
});
pub const FS_HCCHAR3 = MMIO(Address + 0x00000160, u32, packed struct { // byte offset: 352 OTG_FS host channel-3 characteristics register (OTG_FS_HCCHAR3)
MPSIZ: u11, // bit offset: 0 desc: Maximum packet size
EPNUM: u4, // bit offset: 11 desc: Endpoint number
EPDIR: bool, // bit offset: 15 desc: Endpoint direction
reserved0: u1 = 0,
LSDEV: bool, // bit offset: 17 desc: Low-speed device
EPTYP: u2, // bit offset: 18 desc: Endpoint type
MCNT: u2, // bit offset: 20 desc: Multicount
DAD: u7, // bit offset: 22 desc: Device address
ODDFRM: bool, // bit offset: 29 desc: Odd frame
CHDIS: bool, // bit offset: 30 desc: Channel disable
CHENA: bool, // bit offset: 31 desc: Channel enable
});
pub const FS_HCINT3 = MMIO(Address + 0x00000168, u32, packed struct { // byte offset: 360 OTG_FS host channel-3 interrupt register (OTG_FS_HCINT3)
XFRC: bool, // bit offset: 0 desc: Transfer completed
CHH: bool, // bit offset: 1 desc: Channel halted
reserved0: u1 = 0,
STALL: bool, // bit offset: 3 desc: STALL response received interrupt
NAK: bool, // bit offset: 4 desc: NAK response received interrupt
ACK: bool, // bit offset: 5 desc: ACK response received/transmitted interrupt
reserved1: u1 = 0,
TXERR: bool, // bit offset: 7 desc: Transaction error
BBERR: bool, // bit offset: 8 desc: Babble error
FRMOR: bool, // bit offset: 9 desc: Frame overrun
DTERR: bool, // bit offset: 10 desc: Data toggle error
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_HCINTMSK3 = MMIO(Address + 0x0000016c, u32, packed struct { // byte offset: 364 OTG_FS host channel-3 mask register (OTG_FS_HCINTMSK3)
XFRCM: bool, // bit offset: 0 desc: Transfer completed mask
CHHM: bool, // bit offset: 1 desc: Channel halted mask
reserved0: u1 = 0,
STALLM: bool, // bit offset: 3 desc: STALL response received interrupt mask
NAKM: bool, // bit offset: 4 desc: NAK response received interrupt mask
ACKM: bool, // bit offset: 5 desc: ACK response received/transmitted interrupt mask
NYET: bool, // bit offset: 6 desc: response received interrupt mask
TXERRM: bool, // bit offset: 7 desc: Transaction error mask
BBERRM: bool, // bit offset: 8 desc: Babble error mask
FRMORM: bool, // bit offset: 9 desc: Frame overrun mask
DTERRM: bool, // bit offset: 10 desc: Data toggle error mask
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_HCTSIZ3 = MMIO(Address + 0x00000170, u32, packed struct { // byte offset: 368 OTG_FS host channel-3 transfer size register
XFRSIZ: u19, // bit offset: 0 desc: Transfer size
PKTCNT: u10, // bit offset: 19 desc: Packet count
DPID: u2, // bit offset: 29 desc: Data PID
padding1: u1 = 0,
});
pub const FS_HCCHAR4 = MMIO(Address + 0x00000180, u32, packed struct { // byte offset: 384 OTG_FS host channel-4 characteristics register (OTG_FS_HCCHAR4)
MPSIZ: u11, // bit offset: 0 desc: Maximum packet size
EPNUM: u4, // bit offset: 11 desc: Endpoint number
EPDIR: bool, // bit offset: 15 desc: Endpoint direction
reserved0: u1 = 0,
LSDEV: bool, // bit offset: 17 desc: Low-speed device
EPTYP: u2, // bit offset: 18 desc: Endpoint type
MCNT: u2, // bit offset: 20 desc: Multicount
DAD: u7, // bit offset: 22 desc: Device address
ODDFRM: bool, // bit offset: 29 desc: Odd frame
CHDIS: bool, // bit offset: 30 desc: Channel disable
CHENA: bool, // bit offset: 31 desc: Channel enable
});
pub const FS_HCINT4 = MMIO(Address + 0x00000188, u32, packed struct { // byte offset: 392 OTG_FS host channel-4 interrupt register (OTG_FS_HCINT4)
XFRC: bool, // bit offset: 0 desc: Transfer completed
CHH: bool, // bit offset: 1 desc: Channel halted
reserved0: u1 = 0,
STALL: bool, // bit offset: 3 desc: STALL response received interrupt
NAK: bool, // bit offset: 4 desc: NAK response received interrupt
ACK: bool, // bit offset: 5 desc: ACK response received/transmitted interrupt
reserved1: u1 = 0,
TXERR: bool, // bit offset: 7 desc: Transaction error
BBERR: bool, // bit offset: 8 desc: Babble error
FRMOR: bool, // bit offset: 9 desc: Frame overrun
DTERR: bool, // bit offset: 10 desc: Data toggle error
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_HCINTMSK4 = MMIO(Address + 0x0000018c, u32, packed struct { // byte offset: 396 OTG_FS host channel-4 mask register (OTG_FS_HCINTMSK4)
XFRCM: bool, // bit offset: 0 desc: Transfer completed mask
CHHM: bool, // bit offset: 1 desc: Channel halted mask
reserved0: u1 = 0,
STALLM: bool, // bit offset: 3 desc: STALL response received interrupt mask
NAKM: bool, // bit offset: 4 desc: NAK response received interrupt mask
ACKM: bool, // bit offset: 5 desc: ACK response received/transmitted interrupt mask
NYET: bool, // bit offset: 6 desc: response received interrupt mask
TXERRM: bool, // bit offset: 7 desc: Transaction error mask
BBERRM: bool, // bit offset: 8 desc: Babble error mask
FRMORM: bool, // bit offset: 9 desc: Frame overrun mask
DTERRM: bool, // bit offset: 10 desc: Data toggle error mask
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_HCTSIZ4 = MMIO(Address + 0x00000190, u32, packed struct { // byte offset: 400 OTG_FS host channel-x transfer size register
XFRSIZ: u19, // bit offset: 0 desc: Transfer size
PKTCNT: u10, // bit offset: 19 desc: Packet count
DPID: u2, // bit offset: 29 desc: Data PID
padding1: u1 = 0,
});
pub const FS_HCCHAR5 = MMIO(Address + 0x000001a0, u32, packed struct { // byte offset: 416 OTG_FS host channel-5 characteristics register (OTG_FS_HCCHAR5)
MPSIZ: u11, // bit offset: 0 desc: Maximum packet size
EPNUM: u4, // bit offset: 11 desc: Endpoint number
EPDIR: bool, // bit offset: 15 desc: Endpoint direction
reserved0: u1 = 0,
LSDEV: bool, // bit offset: 17 desc: Low-speed device
EPTYP: u2, // bit offset: 18 desc: Endpoint type
MCNT: u2, // bit offset: 20 desc: Multicount
DAD: u7, // bit offset: 22 desc: Device address
ODDFRM: bool, // bit offset: 29 desc: Odd frame
CHDIS: bool, // bit offset: 30 desc: Channel disable
CHENA: bool, // bit offset: 31 desc: Channel enable
});
pub const FS_HCINT5 = MMIO(Address + 0x000001a8, u32, packed struct { // byte offset: 424 OTG_FS host channel-5 interrupt register (OTG_FS_HCINT5)
XFRC: bool, // bit offset: 0 desc: Transfer completed
CHH: bool, // bit offset: 1 desc: Channel halted
reserved0: u1 = 0,
STALL: bool, // bit offset: 3 desc: STALL response received interrupt
NAK: bool, // bit offset: 4 desc: NAK response received interrupt
ACK: bool, // bit offset: 5 desc: ACK response received/transmitted interrupt
reserved1: u1 = 0,
TXERR: bool, // bit offset: 7 desc: Transaction error
BBERR: bool, // bit offset: 8 desc: Babble error
FRMOR: bool, // bit offset: 9 desc: Frame overrun
DTERR: bool, // bit offset: 10 desc: Data toggle error
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_HCINTMSK5 = MMIO(Address + 0x000001ac, u32, packed struct { // byte offset: 428 OTG_FS host channel-5 mask register (OTG_FS_HCINTMSK5)
XFRCM: bool, // bit offset: 0 desc: Transfer completed mask
CHHM: bool, // bit offset: 1 desc: Channel halted mask
reserved0: u1 = 0,
STALLM: bool, // bit offset: 3 desc: STALL response received interrupt mask
NAKM: bool, // bit offset: 4 desc: NAK response received interrupt mask
ACKM: bool, // bit offset: 5 desc: ACK response received/transmitted interrupt mask
NYET: bool, // bit offset: 6 desc: response received interrupt mask
TXERRM: bool, // bit offset: 7 desc: Transaction error mask
BBERRM: bool, // bit offset: 8 desc: Babble error mask
FRMORM: bool, // bit offset: 9 desc: Frame overrun mask
DTERRM: bool, // bit offset: 10 desc: Data toggle error mask
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_HCTSIZ5 = MMIO(Address + 0x000001b0, u32, packed struct { // byte offset: 432 OTG_FS host channel-5 transfer size register
XFRSIZ: u19, // bit offset: 0 desc: Transfer size
PKTCNT: u10, // bit offset: 19 desc: Packet count
DPID: u2, // bit offset: 29 desc: Data PID
padding1: u1 = 0,
});
pub const FS_HCCHAR6 = MMIO(Address + 0x000001c0, u32, packed struct { // byte offset: 448 OTG_FS host channel-6 characteristics register (OTG_FS_HCCHAR6)
MPSIZ: u11, // bit offset: 0 desc: Maximum packet size
EPNUM: u4, // bit offset: 11 desc: Endpoint number
EPDIR: bool, // bit offset: 15 desc: Endpoint direction
reserved0: u1 = 0,
LSDEV: bool, // bit offset: 17 desc: Low-speed device
EPTYP: u2, // bit offset: 18 desc: Endpoint type
MCNT: u2, // bit offset: 20 desc: Multicount
DAD: u7, // bit offset: 22 desc: Device address
ODDFRM: bool, // bit offset: 29 desc: Odd frame
CHDIS: bool, // bit offset: 30 desc: Channel disable
CHENA: bool, // bit offset: 31 desc: Channel enable
});
pub const FS_HCINT6 = MMIO(Address + 0x000001c8, u32, packed struct { // byte offset: 456 OTG_FS host channel-6 interrupt register (OTG_FS_HCINT6)
XFRC: bool, // bit offset: 0 desc: Transfer completed
CHH: bool, // bit offset: 1 desc: Channel halted
reserved0: u1 = 0,
STALL: bool, // bit offset: 3 desc: STALL response received interrupt
NAK: bool, // bit offset: 4 desc: NAK response received interrupt
ACK: bool, // bit offset: 5 desc: ACK response received/transmitted interrupt
reserved1: u1 = 0,
TXERR: bool, // bit offset: 7 desc: Transaction error
BBERR: bool, // bit offset: 8 desc: Babble error
FRMOR: bool, // bit offset: 9 desc: Frame overrun
DTERR: bool, // bit offset: 10 desc: Data toggle error
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_HCINTMSK6 = MMIO(Address + 0x000001cc, u32, packed struct { // byte offset: 460 OTG_FS host channel-6 mask register (OTG_FS_HCINTMSK6)
XFRCM: bool, // bit offset: 0 desc: Transfer completed mask
CHHM: bool, // bit offset: 1 desc: Channel halted mask
reserved0: u1 = 0,
STALLM: bool, // bit offset: 3 desc: STALL response received interrupt mask
NAKM: bool, // bit offset: 4 desc: NAK response received interrupt mask
ACKM: bool, // bit offset: 5 desc: ACK response received/transmitted interrupt mask
NYET: bool, // bit offset: 6 desc: response received interrupt mask
TXERRM: bool, // bit offset: 7 desc: Transaction error mask
BBERRM: bool, // bit offset: 8 desc: Babble error mask
FRMORM: bool, // bit offset: 9 desc: Frame overrun mask
DTERRM: bool, // bit offset: 10 desc: Data toggle error mask
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_HCTSIZ6 = MMIO(Address + 0x000001d0, u32, packed struct { // byte offset: 464 OTG_FS host channel-6 transfer size register
XFRSIZ: u19, // bit offset: 0 desc: Transfer size
PKTCNT: u10, // bit offset: 19 desc: Packet count
DPID: u2, // bit offset: 29 desc: Data PID
padding1: u1 = 0,
});
pub const FS_HCCHAR7 = MMIO(Address + 0x000001e0, u32, packed struct { // byte offset: 480 OTG_FS host channel-7 characteristics register (OTG_FS_HCCHAR7)
MPSIZ: u11, // bit offset: 0 desc: Maximum packet size
EPNUM: u4, // bit offset: 11 desc: Endpoint number
EPDIR: bool, // bit offset: 15 desc: Endpoint direction
reserved0: u1 = 0,
LSDEV: bool, // bit offset: 17 desc: Low-speed device
EPTYP: u2, // bit offset: 18 desc: Endpoint type
MCNT: u2, // bit offset: 20 desc: Multicount
DAD: u7, // bit offset: 22 desc: Device address
ODDFRM: bool, // bit offset: 29 desc: Odd frame
CHDIS: bool, // bit offset: 30 desc: Channel disable
CHENA: bool, // bit offset: 31 desc: Channel enable
});
pub const FS_HCINT7 = MMIO(Address + 0x000001e8, u32, packed struct { // byte offset: 488 OTG_FS host channel-7 interrupt register (OTG_FS_HCINT7)
XFRC: bool, // bit offset: 0 desc: Transfer completed
CHH: bool, // bit offset: 1 desc: Channel halted
reserved0: u1 = 0,
STALL: bool, // bit offset: 3 desc: STALL response received interrupt
NAK: bool, // bit offset: 4 desc: NAK response received interrupt
ACK: bool, // bit offset: 5 desc: ACK response received/transmitted interrupt
reserved1: u1 = 0,
TXERR: bool, // bit offset: 7 desc: Transaction error
BBERR: bool, // bit offset: 8 desc: Babble error
FRMOR: bool, // bit offset: 9 desc: Frame overrun
DTERR: bool, // bit offset: 10 desc: Data toggle error
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_HCINTMSK7 = MMIO(Address + 0x000001ec, u32, packed struct { // byte offset: 492 OTG_FS host channel-7 mask register (OTG_FS_HCINTMSK7)
XFRCM: bool, // bit offset: 0 desc: Transfer completed mask
CHHM: bool, // bit offset: 1 desc: Channel halted mask
reserved0: u1 = 0,
STALLM: bool, // bit offset: 3 desc: STALL response received interrupt mask
NAKM: bool, // bit offset: 4 desc: NAK response received interrupt mask
ACKM: bool, // bit offset: 5 desc: ACK response received/transmitted interrupt mask
NYET: bool, // bit offset: 6 desc: response received interrupt mask
TXERRM: bool, // bit offset: 7 desc: Transaction error mask
BBERRM: bool, // bit offset: 8 desc: Babble error mask
FRMORM: bool, // bit offset: 9 desc: Frame overrun mask
DTERRM: bool, // bit offset: 10 desc: Data toggle error mask
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FS_HCTSIZ7 = MMIO(Address + 0x000001f0, u32, packed struct { // byte offset: 496 OTG_FS host channel-7 transfer size register
XFRSIZ: u19, // bit offset: 0 desc: Transfer size
PKTCNT: u10, // bit offset: 19 desc: Packet count
DPID: u2, // bit offset: 29 desc: Data PID
padding1: u1 = 0,
});
};
pub const OTG_FS_PWRCLK = extern struct {
pub const Address: u32 = 0x50000e00;
pub const FS_PCGCCTL = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 OTG_FS power and clock gating control register
STPPCLK: bool, // bit offset: 0 desc: Stop PHY clock
GATEHCLK: bool, // bit offset: 1 desc: Gate HCLK
reserved0: u2 = 0,
PHYSUSP: bool, // bit offset: 4 desc: PHY Suspended
padding27: u1 = 0,
padding26: u1 = 0,
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const PWR = extern struct {
pub const Address: u32 = 0x40007000;
pub const CR = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 power control register
LPDS: bool, // bit offset: 0 desc: Low-power deep sleep
PDDS: bool, // bit offset: 1 desc: Power down deepsleep
CWUF: bool, // bit offset: 2 desc: Clear wakeup flag
CSBF: bool, // bit offset: 3 desc: Clear standby flag
PVDE: bool, // bit offset: 4 desc: Power voltage detector enable
PLS: u3, // bit offset: 5 desc: PVD level selection
DBP: bool, // bit offset: 8 desc: Disable backup domain write protection
FPDS: bool, // bit offset: 9 desc: Flash power down in Stop mode
reserved0: u3 = 0,
ADCDC1: bool, // bit offset: 13 desc: ADCDC1
VOS: u2, // bit offset: 14 desc: Regulator voltage scaling output selection
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CSR = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 power control/status register
WUF: bool, // bit offset: 0 desc: Wakeup flag
SBF: bool, // bit offset: 1 desc: Standby flag
PVDO: bool, // bit offset: 2 desc: PVD output
BRR: bool, // bit offset: 3 desc: Backup regulator ready
reserved0: u4 = 0,
EWUP: bool, // bit offset: 8 desc: Enable WKUP pin
BRE: bool, // bit offset: 9 desc: Backup regulator enable
reserved1: u4 = 0,
VOSRDY: bool, // bit offset: 14 desc: Regulator voltage scaling output selection ready bit
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const RCC = extern struct {
pub const Address: u32 = 0x40023800;
pub const CR = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 clock control register
HSION: bool, // bit offset: 0 desc: Internal high-speed clock enable
HSIRDY: bool, // bit offset: 1 desc: Internal high-speed clock ready flag
reserved0: u1 = 0,
HSITRIM: u5, // bit offset: 3 desc: Internal high-speed clock trimming
HSICAL: u8, // bit offset: 8 desc: Internal high-speed clock calibration
HSEON: bool, // bit offset: 16 desc: HSE clock enable
HSERDY: bool, // bit offset: 17 desc: HSE clock ready flag
HSEBYP: bool, // bit offset: 18 desc: HSE clock bypass
CSSON: bool, // bit offset: 19 desc: Clock security system enable
reserved1: u4 = 0,
PLLON: bool, // bit offset: 24 desc: Main PLL (PLL) enable
PLLRDY: bool, // bit offset: 25 desc: Main PLL (PLL) clock ready flag
PLLI2SON: bool, // bit offset: 26 desc: PLLI2S enable
PLLI2SRDY: bool, // bit offset: 27 desc: PLLI2S clock ready flag
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const PLLCFGR = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 PLL configuration register
PLLM0: bool, // bit offset: 0 desc: Division factor for the main PLL (PLL) and audio PLL (PLLI2S) input clock
PLLM1: bool, // bit offset: 1 desc: Division factor for the main PLL (PLL) and audio PLL (PLLI2S) input clock
PLLM2: bool, // bit offset: 2 desc: Division factor for the main PLL (PLL) and audio PLL (PLLI2S) input clock
PLLM3: bool, // bit offset: 3 desc: Division factor for the main PLL (PLL) and audio PLL (PLLI2S) input clock
PLLM4: bool, // bit offset: 4 desc: Division factor for the main PLL (PLL) and audio PLL (PLLI2S) input clock
PLLM5: bool, // bit offset: 5 desc: Division factor for the main PLL (PLL) and audio PLL (PLLI2S) input clock
PLLN0: bool, // bit offset: 6 desc: Main PLL (PLL) multiplication factor for VCO
PLLN1: bool, // bit offset: 7 desc: Main PLL (PLL) multiplication factor for VCO
PLLN2: bool, // bit offset: 8 desc: Main PLL (PLL) multiplication factor for VCO
PLLN3: bool, // bit offset: 9 desc: Main PLL (PLL) multiplication factor for VCO
PLLN4: bool, // bit offset: 10 desc: Main PLL (PLL) multiplication factor for VCO
PLLN5: bool, // bit offset: 11 desc: Main PLL (PLL) multiplication factor for VCO
PLLN6: bool, // bit offset: 12 desc: Main PLL (PLL) multiplication factor for VCO
PLLN7: bool, // bit offset: 13 desc: Main PLL (PLL) multiplication factor for VCO
PLLN8: bool, // bit offset: 14 desc: Main PLL (PLL) multiplication factor for VCO
reserved0: u1 = 0,
PLLP0: bool, // bit offset: 16 desc: Main PLL (PLL) division factor for main system clock
PLLP1: bool, // bit offset: 17 desc: Main PLL (PLL) division factor for main system clock
reserved1: u4 = 0,
PLLSRC: bool, // bit offset: 22 desc: Main PLL(PLL) and audio PLL (PLLI2S) entry clock source
reserved2: u1 = 0,
PLLQ0: bool, // bit offset: 24 desc: Main PLL (PLL) division factor for USB OTG FS, SDIO and random number generator clocks
PLLQ1: bool, // bit offset: 25 desc: Main PLL (PLL) division factor for USB OTG FS, SDIO and random number generator clocks
PLLQ2: bool, // bit offset: 26 desc: Main PLL (PLL) division factor for USB OTG FS, SDIO and random number generator clocks
PLLQ3: bool, // bit offset: 27 desc: Main PLL (PLL) division factor for USB OTG FS, SDIO and random number generator clocks
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CFGR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 clock configuration register
SW0: bool, // bit offset: 0 desc: System clock switch
SW1: bool, // bit offset: 1 desc: System clock switch
SWS0: bool, // bit offset: 2 desc: System clock switch status
SWS1: bool, // bit offset: 3 desc: System clock switch status
HPRE: u4, // bit offset: 4 desc: AHB prescaler
reserved0: u2 = 0,
PPRE1: u3, // bit offset: 10 desc: APB Low speed prescaler (APB1)
PPRE2: u3, // bit offset: 13 desc: APB high-speed prescaler (APB2)
RTCPRE: u5, // bit offset: 16 desc: HSE division factor for RTC clock
MCO1: u2, // bit offset: 21 desc: Microcontroller clock output 1
I2SSRC: bool, // bit offset: 23 desc: I2S clock selection
MCO1PRE: u3, // bit offset: 24 desc: MCO1 prescaler
MCO2PRE: u3, // bit offset: 27 desc: MCO2 prescaler
MCO2: u2, // bit offset: 30 desc: Microcontroller clock output 2
});
pub const CIR = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 clock interrupt register
LSIRDYF: bool, // bit offset: 0 desc: LSI ready interrupt flag
LSERDYF: bool, // bit offset: 1 desc: LSE ready interrupt flag
HSIRDYF: bool, // bit offset: 2 desc: HSI ready interrupt flag
HSERDYF: bool, // bit offset: 3 desc: HSE ready interrupt flag
PLLRDYF: bool, // bit offset: 4 desc: Main PLL (PLL) ready interrupt flag
PLLI2SRDYF: bool, // bit offset: 5 desc: PLLI2S ready interrupt flag
reserved0: u1 = 0,
CSSF: bool, // bit offset: 7 desc: Clock security system interrupt flag
LSIRDYIE: bool, // bit offset: 8 desc: LSI ready interrupt enable
LSERDYIE: bool, // bit offset: 9 desc: LSE ready interrupt enable
HSIRDYIE: bool, // bit offset: 10 desc: HSI ready interrupt enable
HSERDYIE: bool, // bit offset: 11 desc: HSE ready interrupt enable
PLLRDYIE: bool, // bit offset: 12 desc: Main PLL (PLL) ready interrupt enable
PLLI2SRDYIE: bool, // bit offset: 13 desc: PLLI2S ready interrupt enable
reserved1: u2 = 0,
LSIRDYC: bool, // bit offset: 16 desc: LSI ready interrupt clear
LSERDYC: bool, // bit offset: 17 desc: LSE ready interrupt clear
HSIRDYC: bool, // bit offset: 18 desc: HSI ready interrupt clear
HSERDYC: bool, // bit offset: 19 desc: HSE ready interrupt clear
PLLRDYC: bool, // bit offset: 20 desc: Main PLL(PLL) ready interrupt clear
PLLI2SRDYC: bool, // bit offset: 21 desc: PLLI2S ready interrupt clear
reserved2: u1 = 0,
CSSC: bool, // bit offset: 23 desc: Clock security system interrupt clear
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const AHB1RSTR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 AHB1 peripheral reset register
GPIOARST: bool, // bit offset: 0 desc: IO port A reset
GPIOBRST: bool, // bit offset: 1 desc: IO port B reset
GPIOCRST: bool, // bit offset: 2 desc: IO port C reset
GPIODRST: bool, // bit offset: 3 desc: IO port D reset
GPIOERST: bool, // bit offset: 4 desc: IO port E reset
reserved0: u2 = 0,
GPIOHRST: bool, // bit offset: 7 desc: IO port H reset
reserved1: u4 = 0,
CRCRST: bool, // bit offset: 12 desc: CRC reset
reserved2: u8 = 0,
DMA1RST: bool, // bit offset: 21 desc: DMA2 reset
DMA2RST: bool, // bit offset: 22 desc: DMA2 reset
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const AHB2RSTR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 AHB2 peripheral reset register
reserved0: u7 = 0,
OTGFSRST: bool, // bit offset: 7 desc: USB OTG FS module reset
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const APB1RSTR = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 APB1 peripheral reset register
TIM2RST: bool, // bit offset: 0 desc: TIM2 reset
TIM3RST: bool, // bit offset: 1 desc: TIM3 reset
TIM4RST: bool, // bit offset: 2 desc: TIM4 reset
TIM5RST: bool, // bit offset: 3 desc: TIM5 reset
reserved0: u7 = 0,
WWDGRST: bool, // bit offset: 11 desc: Window watchdog reset
reserved1: u2 = 0,
SPI2RST: bool, // bit offset: 14 desc: SPI 2 reset
SPI3RST: bool, // bit offset: 15 desc: SPI 3 reset
reserved2: u1 = 0,
UART2RST: bool, // bit offset: 17 desc: USART 2 reset
reserved3: u3 = 0,
I2C1RST: bool, // bit offset: 21 desc: I2C 1 reset
I2C2RST: bool, // bit offset: 22 desc: I2C 2 reset
I2C3RST: bool, // bit offset: 23 desc: I2C3 reset
reserved4: u4 = 0,
PWRRST: bool, // bit offset: 28 desc: Power interface reset
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const APB2RSTR = MMIO(Address + 0x00000024, u32, packed struct { // byte offset: 36 APB2 peripheral reset register
TIM1RST: bool, // bit offset: 0 desc: TIM1 reset
reserved0: u3 = 0,
USART1RST: bool, // bit offset: 4 desc: USART1 reset
USART6RST: bool, // bit offset: 5 desc: USART6 reset
reserved1: u2 = 0,
ADCRST: bool, // bit offset: 8 desc: ADC interface reset (common to all ADCs)
reserved2: u2 = 0,
SDIORST: bool, // bit offset: 11 desc: SDIO reset
SPI1RST: bool, // bit offset: 12 desc: SPI 1 reset
reserved3: u1 = 0,
SYSCFGRST: bool, // bit offset: 14 desc: System configuration controller reset
reserved4: u1 = 0,
TIM9RST: bool, // bit offset: 16 desc: TIM9 reset
TIM10RST: bool, // bit offset: 17 desc: TIM10 reset
TIM11RST: bool, // bit offset: 18 desc: TIM11 reset
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const AHB1ENR = MMIO(Address + 0x00000030, u32, packed struct { // byte offset: 48 AHB1 peripheral clock register
GPIOAEN: bool, // bit offset: 0 desc: IO port A clock enable
GPIOBEN: bool, // bit offset: 1 desc: IO port B clock enable
GPIOCEN: bool, // bit offset: 2 desc: IO port C clock enable
GPIODEN: bool, // bit offset: 3 desc: IO port D clock enable
GPIOEEN: bool, // bit offset: 4 desc: IO port E clock enable
reserved0: u2 = 0,
GPIOHEN: bool, // bit offset: 7 desc: IO port H clock enable
reserved1: u4 = 0,
CRCEN: bool, // bit offset: 12 desc: CRC clock enable
reserved2: u8 = 0,
DMA1EN: bool, // bit offset: 21 desc: DMA1 clock enable
DMA2EN: bool, // bit offset: 22 desc: DMA2 clock enable
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const AHB2ENR = MMIO(Address + 0x00000034, u32, packed struct { // byte offset: 52 AHB2 peripheral clock enable register
reserved0: u7 = 0,
OTGFSEN: bool, // bit offset: 7 desc: USB OTG FS clock enable
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const APB1ENR = MMIO(Address + 0x00000040, u32, packed struct { // byte offset: 64 APB1 peripheral clock enable register
TIM2EN: bool, // bit offset: 0 desc: TIM2 clock enable
TIM3EN: bool, // bit offset: 1 desc: TIM3 clock enable
TIM4EN: bool, // bit offset: 2 desc: TIM4 clock enable
TIM5EN: bool, // bit offset: 3 desc: TIM5 clock enable
reserved0: u7 = 0,
WWDGEN: bool, // bit offset: 11 desc: Window watchdog clock enable
reserved1: u2 = 0,
SPI2EN: bool, // bit offset: 14 desc: SPI2 clock enable
SPI3EN: bool, // bit offset: 15 desc: SPI3 clock enable
reserved2: u1 = 0,
USART2EN: bool, // bit offset: 17 desc: USART 2 clock enable
reserved3: u3 = 0,
I2C1EN: bool, // bit offset: 21 desc: I2C1 clock enable
I2C2EN: bool, // bit offset: 22 desc: I2C2 clock enable
I2C3EN: bool, // bit offset: 23 desc: I2C3 clock enable
reserved4: u4 = 0,
PWREN: bool, // bit offset: 28 desc: Power interface clock enable
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const APB2ENR = MMIO(Address + 0x00000044, u32, packed struct { // byte offset: 68 APB2 peripheral clock enable register
TIM1EN: bool, // bit offset: 0 desc: TIM1 clock enable
reserved0: u3 = 0,
USART1EN: bool, // bit offset: 4 desc: USART1 clock enable
USART6EN: bool, // bit offset: 5 desc: USART6 clock enable
reserved1: u2 = 0,
ADC1EN: bool, // bit offset: 8 desc: ADC1 clock enable
reserved2: u2 = 0,
SDIOEN: bool, // bit offset: 11 desc: SDIO clock enable
SPI1EN: bool, // bit offset: 12 desc: SPI1 clock enable
SPI4EN: bool, // bit offset: 13 desc: SPI4 clock enable
SYSCFGEN: bool, // bit offset: 14 desc: System configuration controller clock enable
reserved3: u1 = 0,
TIM9EN: bool, // bit offset: 16 desc: TIM9 clock enable
TIM10EN: bool, // bit offset: 17 desc: TIM10 clock enable
TIM11EN: bool, // bit offset: 18 desc: TIM11 clock enable
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const AHB1LPENR = MMIO(Address + 0x00000050, u32, packed struct { // byte offset: 80 AHB1 peripheral clock enable in low power mode register
GPIOALPEN: bool, // bit offset: 0 desc: IO port A clock enable during sleep mode
GPIOBLPEN: bool, // bit offset: 1 desc: IO port B clock enable during Sleep mode
GPIOCLPEN: bool, // bit offset: 2 desc: IO port C clock enable during Sleep mode
GPIODLPEN: bool, // bit offset: 3 desc: IO port D clock enable during Sleep mode
GPIOELPEN: bool, // bit offset: 4 desc: IO port E clock enable during Sleep mode
reserved0: u2 = 0,
GPIOHLPEN: bool, // bit offset: 7 desc: IO port H clock enable during Sleep mode
reserved1: u4 = 0,
CRCLPEN: bool, // bit offset: 12 desc: CRC clock enable during Sleep mode
reserved2: u2 = 0,
FLITFLPEN: bool, // bit offset: 15 desc: Flash interface clock enable during Sleep mode
SRAM1LPEN: bool, // bit offset: 16 desc: SRAM 1interface clock enable during Sleep mode
reserved3: u4 = 0,
DMA1LPEN: bool, // bit offset: 21 desc: DMA1 clock enable during Sleep mode
DMA2LPEN: bool, // bit offset: 22 desc: DMA2 clock enable during Sleep mode
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const AHB2LPENR = MMIO(Address + 0x00000054, u32, packed struct { // byte offset: 84 AHB2 peripheral clock enable in low power mode register
reserved0: u7 = 0,
OTGFSLPEN: bool, // bit offset: 7 desc: USB OTG FS clock enable during Sleep mode
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const APB1LPENR = MMIO(Address + 0x00000060, u32, packed struct { // byte offset: 96 APB1 peripheral clock enable in low power mode register
TIM2LPEN: bool, // bit offset: 0 desc: TIM2 clock enable during Sleep mode
TIM3LPEN: bool, // bit offset: 1 desc: TIM3 clock enable during Sleep mode
TIM4LPEN: bool, // bit offset: 2 desc: TIM4 clock enable during Sleep mode
TIM5LPEN: bool, // bit offset: 3 desc: TIM5 clock enable during Sleep mode
reserved0: u7 = 0,
WWDGLPEN: bool, // bit offset: 11 desc: Window watchdog clock enable during Sleep mode
reserved1: u2 = 0,
SPI2LPEN: bool, // bit offset: 14 desc: SPI2 clock enable during Sleep mode
SPI3LPEN: bool, // bit offset: 15 desc: SPI3 clock enable during Sleep mode
reserved2: u1 = 0,
USART2LPEN: bool, // bit offset: 17 desc: USART2 clock enable during Sleep mode
reserved3: u3 = 0,
I2C1LPEN: bool, // bit offset: 21 desc: I2C1 clock enable during Sleep mode
I2C2LPEN: bool, // bit offset: 22 desc: I2C2 clock enable during Sleep mode
I2C3LPEN: bool, // bit offset: 23 desc: I2C3 clock enable during Sleep mode
reserved4: u4 = 0,
PWRLPEN: bool, // bit offset: 28 desc: Power interface clock enable during Sleep mode
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const APB2LPENR = MMIO(Address + 0x00000064, u32, packed struct { // byte offset: 100 APB2 peripheral clock enabled in low power mode register
TIM1LPEN: bool, // bit offset: 0 desc: TIM1 clock enable during Sleep mode
reserved0: u3 = 0,
USART1LPEN: bool, // bit offset: 4 desc: USART1 clock enable during Sleep mode
USART6LPEN: bool, // bit offset: 5 desc: USART6 clock enable during Sleep mode
reserved1: u2 = 0,
ADC1LPEN: bool, // bit offset: 8 desc: ADC1 clock enable during Sleep mode
reserved2: u2 = 0,
SDIOLPEN: bool, // bit offset: 11 desc: SDIO clock enable during Sleep mode
SPI1LPEN: bool, // bit offset: 12 desc: SPI 1 clock enable during Sleep mode
SPI4LPEN: bool, // bit offset: 13 desc: SPI4 clock enable during Sleep mode
SYSCFGLPEN: bool, // bit offset: 14 desc: System configuration controller clock enable during Sleep mode
reserved3: u1 = 0,
TIM9LPEN: bool, // bit offset: 16 desc: TIM9 clock enable during sleep mode
TIM10LPEN: bool, // bit offset: 17 desc: TIM10 clock enable during Sleep mode
TIM11LPEN: bool, // bit offset: 18 desc: TIM11 clock enable during Sleep mode
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const BDCR = MMIO(Address + 0x00000070, u32, packed struct { // byte offset: 112 Backup domain control register
LSEON: bool, // bit offset: 0 desc: External low-speed oscillator enable
LSERDY: bool, // bit offset: 1 desc: External low-speed oscillator ready
LSEBYP: bool, // bit offset: 2 desc: External low-speed oscillator bypass
reserved0: u5 = 0,
RTCSEL0: bool, // bit offset: 8 desc: RTC clock source selection
RTCSEL1: bool, // bit offset: 9 desc: RTC clock source selection
reserved1: u5 = 0,
RTCEN: bool, // bit offset: 15 desc: RTC clock enable
BDRST: bool, // bit offset: 16 desc: Backup domain software reset
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CSR = MMIO(Address + 0x00000074, u32, packed struct { // byte offset: 116 clock control & status register
LSION: bool, // bit offset: 0 desc: Internal low-speed oscillator enable
LSIRDY: bool, // bit offset: 1 desc: Internal low-speed oscillator ready
reserved0: u22 = 0,
RMVF: bool, // bit offset: 24 desc: Remove reset flag
BORRSTF: bool, // bit offset: 25 desc: BOR reset flag
PADRSTF: bool, // bit offset: 26 desc: PIN reset flag
PORRSTF: bool, // bit offset: 27 desc: POR/PDR reset flag
SFTRSTF: bool, // bit offset: 28 desc: Software reset flag
WDGRSTF: bool, // bit offset: 29 desc: Independent watchdog reset flag
WWDGRSTF: bool, // bit offset: 30 desc: Window watchdog reset flag
LPWRRSTF: bool, // bit offset: 31 desc: Low-power reset flag
});
pub const SSCGR = MMIO(Address + 0x00000080, u32, packed struct { // byte offset: 128 spread spectrum clock generation register
MODPER: u13, // bit offset: 0 desc: Modulation period
INCSTEP: u15, // bit offset: 13 desc: Incrementation step
reserved0: u2 = 0,
SPREADSEL: bool, // bit offset: 30 desc: Spread Select
SSCGEN: bool, // bit offset: 31 desc: Spread spectrum modulation enable
});
pub const PLLI2SCFGR = MMIO(Address + 0x00000084, u32, packed struct { // byte offset: 132 PLLI2S configuration register
reserved0: u6 = 0,
PLLI2SNx: u9, // bit offset: 6 desc: PLLI2S multiplication factor for VCO
reserved1: u13 = 0,
PLLI2SRx: u3, // bit offset: 28 desc: PLLI2S division factor for I2S clocks
padding1: u1 = 0,
});
};
pub const RTC = extern struct {
pub const Address: u32 = 0x40002800;
pub const TR = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 time register
SU: u4, // bit offset: 0 desc: Second units in BCD format
ST: u3, // bit offset: 4 desc: Second tens in BCD format
reserved0: u1 = 0,
MNU: u4, // bit offset: 8 desc: Minute units in BCD format
MNT: u3, // bit offset: 12 desc: Minute tens in BCD format
reserved1: u1 = 0,
HU: u4, // bit offset: 16 desc: Hour units in BCD format
HT: u2, // bit offset: 20 desc: Hour tens in BCD format
PM: bool, // bit offset: 22 desc: AM/PM notation
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DR = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 date register
DU: u4, // bit offset: 0 desc: Date units in BCD format
DT: u2, // bit offset: 4 desc: Date tens in BCD format
reserved0: u2 = 0,
MU: u4, // bit offset: 8 desc: Month units in BCD format
MT: bool, // bit offset: 12 desc: Month tens in BCD format
WDU: u3, // bit offset: 13 desc: Week day units
YU: u4, // bit offset: 16 desc: Year units in BCD format
YT: u4, // bit offset: 20 desc: Year tens in BCD format
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 control register
WCKSEL: u3, // bit offset: 0 desc: Wakeup clock selection
TSEDGE: bool, // bit offset: 3 desc: Time-stamp event active edge
REFCKON: bool, // bit offset: 4 desc: Reference clock detection enable (50 or 60 Hz)
BYPSHAD: bool, // bit offset: 5 desc: Bypass the shadow registers
FMT: bool, // bit offset: 6 desc: Hour format
DCE: bool, // bit offset: 7 desc: Coarse digital calibration enable
ALRAE: bool, // bit offset: 8 desc: Alarm A enable
ALRBE: bool, // bit offset: 9 desc: Alarm B enable
WUTE: bool, // bit offset: 10 desc: Wakeup timer enable
TSE: bool, // bit offset: 11 desc: Time stamp enable
ALRAIE: bool, // bit offset: 12 desc: Alarm A interrupt enable
ALRBIE: bool, // bit offset: 13 desc: Alarm B interrupt enable
WUTIE: bool, // bit offset: 14 desc: Wakeup timer interrupt enable
TSIE: bool, // bit offset: 15 desc: Time-stamp interrupt enable
ADD1H: bool, // bit offset: 16 desc: Add 1 hour (summer time change)
SUB1H: bool, // bit offset: 17 desc: Subtract 1 hour (winter time change)
BKP: bool, // bit offset: 18 desc: Backup
COSEL: bool, // bit offset: 19 desc: Calibration Output selection
POL: bool, // bit offset: 20 desc: Output polarity
OSEL: u2, // bit offset: 21 desc: Output selection
COE: bool, // bit offset: 23 desc: Calibration output enable
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const ISR = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 initialization and status register
ALRAWF: bool, // bit offset: 0 desc: Alarm A write flag
ALRBWF: bool, // bit offset: 1 desc: Alarm B write flag
WUTWF: bool, // bit offset: 2 desc: Wakeup timer write flag
SHPF: bool, // bit offset: 3 desc: Shift operation pending
INITS: bool, // bit offset: 4 desc: Initialization status flag
RSF: bool, // bit offset: 5 desc: Registers synchronization flag
INITF: bool, // bit offset: 6 desc: Initialization flag
INIT: bool, // bit offset: 7 desc: Initialization mode
ALRAF: bool, // bit offset: 8 desc: Alarm A flag
ALRBF: bool, // bit offset: 9 desc: Alarm B flag
WUTF: bool, // bit offset: 10 desc: Wakeup timer flag
TSF: bool, // bit offset: 11 desc: Time-stamp flag
TSOVF: bool, // bit offset: 12 desc: Time-stamp overflow flag
TAMP1F: bool, // bit offset: 13 desc: Tamper detection flag
TAMP2F: bool, // bit offset: 14 desc: TAMPER2 detection flag
reserved0: u1 = 0,
RECALPF: bool, // bit offset: 16 desc: Recalibration pending Flag
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const PRER = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 prescaler register
PREDIV_S: u15, // bit offset: 0 desc: Synchronous prescaler factor
reserved0: u1 = 0,
PREDIV_A: u7, // bit offset: 16 desc: Asynchronous prescaler factor
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const WUTR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 wakeup timer register
WUT: u16, // bit offset: 0 desc: Wakeup auto-reload value bits
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CALIBR = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 calibration register
DC: u5, // bit offset: 0 desc: Digital calibration
reserved0: u2 = 0,
DCS: bool, // bit offset: 7 desc: Digital calibration sign
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const ALRMAR = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 alarm A register
SU: u4, // bit offset: 0 desc: Second units in BCD format
ST: u3, // bit offset: 4 desc: Second tens in BCD format
MSK1: bool, // bit offset: 7 desc: Alarm A seconds mask
MNU: u4, // bit offset: 8 desc: Minute units in BCD format
MNT: u3, // bit offset: 12 desc: Minute tens in BCD format
MSK2: bool, // bit offset: 15 desc: Alarm A minutes mask
HU: u4, // bit offset: 16 desc: Hour units in BCD format
HT: u2, // bit offset: 20 desc: Hour tens in BCD format
PM: bool, // bit offset: 22 desc: AM/PM notation
MSK3: bool, // bit offset: 23 desc: Alarm A hours mask
DU: u4, // bit offset: 24 desc: Date units or day in BCD format
DT: u2, // bit offset: 28 desc: Date tens in BCD format
WDSEL: bool, // bit offset: 30 desc: Week day selection
MSK4: bool, // bit offset: 31 desc: Alarm A date mask
});
pub const ALRMBR = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 alarm B register
SU: u4, // bit offset: 0 desc: Second units in BCD format
ST: u3, // bit offset: 4 desc: Second tens in BCD format
MSK1: bool, // bit offset: 7 desc: Alarm B seconds mask
MNU: u4, // bit offset: 8 desc: Minute units in BCD format
MNT: u3, // bit offset: 12 desc: Minute tens in BCD format
MSK2: bool, // bit offset: 15 desc: Alarm B minutes mask
HU: u4, // bit offset: 16 desc: Hour units in BCD format
HT: u2, // bit offset: 20 desc: Hour tens in BCD format
PM: bool, // bit offset: 22 desc: AM/PM notation
MSK3: bool, // bit offset: 23 desc: Alarm B hours mask
DU: u4, // bit offset: 24 desc: Date units or day in BCD format
DT: u2, // bit offset: 28 desc: Date tens in BCD format
WDSEL: bool, // bit offset: 30 desc: Week day selection
MSK4: bool, // bit offset: 31 desc: Alarm B date mask
});
pub const WPR = MMIO(Address + 0x00000024, u32, packed struct { // byte offset: 36 write protection register
KEY: u8, // bit offset: 0 desc: Write protection key
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SSR = MMIO(Address + 0x00000028, u32, packed struct { // byte offset: 40 sub second register
SS: u16, // bit offset: 0 desc: Sub second value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SHIFTR = MMIO(Address + 0x0000002c, u32, packed struct { // byte offset: 44 shift control register
SUBFS: u15, // bit offset: 0 desc: Subtract a fraction of a second
reserved0: u16 = 0,
ADD1S: bool, // bit offset: 31 desc: Add one second
});
pub const TSTR = MMIO(Address + 0x00000030, u32, packed struct { // byte offset: 48 time stamp time register
SU: u4, // bit offset: 0 desc: Second units in BCD format
ST: u3, // bit offset: 4 desc: Second tens in BCD format
reserved0: u1 = 0,
MNU: u4, // bit offset: 8 desc: Minute units in BCD format
MNT: u3, // bit offset: 12 desc: Minute tens in BCD format
reserved1: u1 = 0,
HU: u4, // bit offset: 16 desc: Hour units in BCD format
HT: u2, // bit offset: 20 desc: Hour tens in BCD format
PM: bool, // bit offset: 22 desc: AM/PM notation
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const TSDR = MMIO(Address + 0x00000034, u32, packed struct { // byte offset: 52 time stamp date register
DU: u4, // bit offset: 0 desc: Date units in BCD format
DT: u2, // bit offset: 4 desc: Date tens in BCD format
reserved0: u2 = 0,
MU: u4, // bit offset: 8 desc: Month units in BCD format
MT: bool, // bit offset: 12 desc: Month tens in BCD format
WDU: u3, // bit offset: 13 desc: Week day units
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const TSSSR = MMIO(Address + 0x00000038, u32, packed struct { // byte offset: 56 timestamp sub second register
SS: u16, // bit offset: 0 desc: Sub second value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CALR = MMIO(Address + 0x0000003c, u32, packed struct { // byte offset: 60 calibration register
CALM: u9, // bit offset: 0 desc: Calibration minus
reserved0: u4 = 0,
CALW16: bool, // bit offset: 13 desc: Use a 16-second calibration cycle period
CALW8: bool, // bit offset: 14 desc: Use an 8-second calibration cycle period
CALP: bool, // bit offset: 15 desc: Increase frequency of RTC by 488.5 ppm
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const TAFCR = MMIO(Address + 0x00000040, u32, packed struct { // byte offset: 64 tamper and alternate function configuration register
TAMP1E: bool, // bit offset: 0 desc: Tamper 1 detection enable
TAMP1TRG: bool, // bit offset: 1 desc: Active level for tamper 1
TAMPIE: bool, // bit offset: 2 desc: Tamper interrupt enable
TAMP2E: bool, // bit offset: 3 desc: Tamper 2 detection enable
TAMP2TRG: bool, // bit offset: 4 desc: Active level for tamper 2
reserved0: u2 = 0,
TAMPTS: bool, // bit offset: 7 desc: Activate timestamp on tamper detection event
TAMPFREQ: u3, // bit offset: 8 desc: Tamper sampling frequency
TAMPFLT: u2, // bit offset: 11 desc: Tamper filter count
TAMPPRCH: u2, // bit offset: 13 desc: Tamper precharge duration
TAMPPUDIS: bool, // bit offset: 15 desc: TAMPER pull-up disable
TAMP1INSEL: bool, // bit offset: 16 desc: TAMPER1 mapping
TSINSEL: bool, // bit offset: 17 desc: TIMESTAMP mapping
ALARMOUTTYPE: bool, // bit offset: 18 desc: AFO_ALARM output type
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const ALRMASSR = MMIO(Address + 0x00000044, u32, packed struct { // byte offset: 68 alarm A sub second register
SS: u15, // bit offset: 0 desc: Sub seconds value
reserved0: u9 = 0,
MASKSS: u4, // bit offset: 24 desc: Mask the most-significant bits starting at this bit
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const ALRMBSSR = MMIO(Address + 0x00000048, u32, packed struct { // byte offset: 72 alarm B sub second register
SS: u15, // bit offset: 0 desc: Sub seconds value
reserved0: u9 = 0,
MASKSS: u4, // bit offset: 24 desc: Mask the most-significant bits starting at this bit
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const BKP0R = MMIO(Address + 0x00000050, u32, packed struct { // byte offset: 80 backup register
BKP: u32, // bit offset: 0 desc: BKP
});
pub const BKP1R = MMIO(Address + 0x00000054, u32, packed struct { // byte offset: 84 backup register
BKP: u32, // bit offset: 0 desc: BKP
});
pub const BKP2R = MMIO(Address + 0x00000058, u32, packed struct { // byte offset: 88 backup register
BKP: u32, // bit offset: 0 desc: BKP
});
pub const BKP3R = MMIO(Address + 0x0000005c, u32, packed struct { // byte offset: 92 backup register
BKP: u32, // bit offset: 0 desc: BKP
});
pub const BKP4R = MMIO(Address + 0x00000060, u32, packed struct { // byte offset: 96 backup register
BKP: u32, // bit offset: 0 desc: BKP
});
pub const BKP5R = MMIO(Address + 0x00000064, u32, packed struct { // byte offset: 100 backup register
BKP: u32, // bit offset: 0 desc: BKP
});
pub const BKP6R = MMIO(Address + 0x00000068, u32, packed struct { // byte offset: 104 backup register
BKP: u32, // bit offset: 0 desc: BKP
});
pub const BKP7R = MMIO(Address + 0x0000006c, u32, packed struct { // byte offset: 108 backup register
BKP: u32, // bit offset: 0 desc: BKP
});
pub const BKP8R = MMIO(Address + 0x00000070, u32, packed struct { // byte offset: 112 backup register
BKP: u32, // bit offset: 0 desc: BKP
});
pub const BKP9R = MMIO(Address + 0x00000074, u32, packed struct { // byte offset: 116 backup register
BKP: u32, // bit offset: 0 desc: BKP
});
pub const BKP10R = MMIO(Address + 0x00000078, u32, packed struct { // byte offset: 120 backup register
BKP: u32, // bit offset: 0 desc: BKP
});
pub const BKP11R = MMIO(Address + 0x0000007c, u32, packed struct { // byte offset: 124 backup register
BKP: u32, // bit offset: 0 desc: BKP
});
pub const BKP12R = MMIO(Address + 0x00000080, u32, packed struct { // byte offset: 128 backup register
BKP: u32, // bit offset: 0 desc: BKP
});
pub const BKP13R = MMIO(Address + 0x00000084, u32, packed struct { // byte offset: 132 backup register
BKP: u32, // bit offset: 0 desc: BKP
});
pub const BKP14R = MMIO(Address + 0x00000088, u32, packed struct { // byte offset: 136 backup register
BKP: u32, // bit offset: 0 desc: BKP
});
pub const BKP15R = MMIO(Address + 0x0000008c, u32, packed struct { // byte offset: 140 backup register
BKP: u32, // bit offset: 0 desc: BKP
});
pub const BKP16R = MMIO(Address + 0x00000090, u32, packed struct { // byte offset: 144 backup register
BKP: u32, // bit offset: 0 desc: BKP
});
pub const BKP17R = MMIO(Address + 0x00000094, u32, packed struct { // byte offset: 148 backup register
BKP: u32, // bit offset: 0 desc: BKP
});
pub const BKP18R = MMIO(Address + 0x00000098, u32, packed struct { // byte offset: 152 backup register
BKP: u32, // bit offset: 0 desc: BKP
});
pub const BKP19R = MMIO(Address + 0x0000009c, u32, packed struct { // byte offset: 156 backup register
BKP: u32, // bit offset: 0 desc: BKP
});
};
pub const SDIO = extern struct {
pub const Address: u32 = 0x40012c00;
pub const POWER = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 power control register
PWRCTRL: u2, // bit offset: 0 desc: PWRCTRL
padding30: u1 = 0,
padding29: u1 = 0,
padding28: u1 = 0,
padding27: u1 = 0,
padding26: u1 = 0,
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CLKCR = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 SDI clock control register
CLKDIV: u8, // bit offset: 0 desc: Clock divide factor
CLKEN: bool, // bit offset: 8 desc: Clock enable bit
PWRSAV: bool, // bit offset: 9 desc: Power saving configuration bit
BYPASS: bool, // bit offset: 10 desc: Clock divider bypass enable bit
WIDBUS: u2, // bit offset: 11 desc: Wide bus mode enable bit
NEGEDGE: bool, // bit offset: 13 desc: SDIO_CK dephasing selection bit
HWFC_EN: bool, // bit offset: 14 desc: HW Flow Control enable
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const ARG = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 argument register
CMDARG: u32, // bit offset: 0 desc: Command argument
});
pub const CMD = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 command register
CMDINDEX: u6, // bit offset: 0 desc: Command index
WAITRESP: u2, // bit offset: 6 desc: Wait for response bits
WAITINT: bool, // bit offset: 8 desc: CPSM waits for interrupt request
WAITPEND: bool, // bit offset: 9 desc: CPSM Waits for ends of data transfer (CmdPend internal signal).
CPSMEN: bool, // bit offset: 10 desc: Command path state machine (CPSM) Enable bit
SDIOSuspend: bool, // bit offset: 11 desc: SD I/O suspend command
ENCMDcompl: bool, // bit offset: 12 desc: Enable CMD completion
nIEN: bool, // bit offset: 13 desc: not Interrupt Enable
CE_ATACMD: bool, // bit offset: 14 desc: CE-ATA command
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const RESPCMD = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 command response register
RESPCMD: u6, // bit offset: 0 desc: Response command index
padding26: u1 = 0,
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const RESP1 = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 response 1..4 register
CARDSTATUS1: u32, // bit offset: 0 desc: Card Status
});
pub const RESP2 = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 response 1..4 register
CARDSTATUS2: u32, // bit offset: 0 desc: Card Status
});
pub const RESP3 = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 response 1..4 register
CARDSTATUS3: u32, // bit offset: 0 desc: Card Status
});
pub const RESP4 = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 response 1..4 register
CARDSTATUS4: u32, // bit offset: 0 desc: Card Status
});
pub const DTIMER = MMIO(Address + 0x00000024, u32, packed struct { // byte offset: 36 data timer register
DATATIME: u32, // bit offset: 0 desc: Data timeout period
});
pub const DLEN = MMIO(Address + 0x00000028, u32, packed struct { // byte offset: 40 data length register
DATALENGTH: u25, // bit offset: 0 desc: Data length value
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DCTRL = MMIO(Address + 0x0000002c, u32, packed struct { // byte offset: 44 data control register
DTEN: bool, // bit offset: 0 desc: DTEN
DTDIR: bool, // bit offset: 1 desc: Data transfer direction selection
DTMODE: bool, // bit offset: 2 desc: Data transfer mode selection 1: Stream or SDIO multibyte data transfer.
DMAEN: bool, // bit offset: 3 desc: DMA enable bit
DBLOCKSIZE: u4, // bit offset: 4 desc: Data block size
RWSTART: bool, // bit offset: 8 desc: Read wait start
RWSTOP: bool, // bit offset: 9 desc: Read wait stop
RWMOD: bool, // bit offset: 10 desc: Read wait mode
SDIOEN: bool, // bit offset: 11 desc: SD I/O enable functions
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DCOUNT = MMIO(Address + 0x00000030, u32, packed struct { // byte offset: 48 data counter register
DATACOUNT: u25, // bit offset: 0 desc: Data count value
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const STA = MMIO(Address + 0x00000034, u32, packed struct { // byte offset: 52 status register
CCRCFAIL: bool, // bit offset: 0 desc: Command response received (CRC check failed)
DCRCFAIL: bool, // bit offset: 1 desc: Data block sent/received (CRC check failed)
CTIMEOUT: bool, // bit offset: 2 desc: Command response timeout
DTIMEOUT: bool, // bit offset: 3 desc: Data timeout
TXUNDERR: bool, // bit offset: 4 desc: Transmit FIFO underrun error
RXOVERR: bool, // bit offset: 5 desc: Received FIFO overrun error
CMDREND: bool, // bit offset: 6 desc: Command response received (CRC check passed)
CMDSENT: bool, // bit offset: 7 desc: Command sent (no response required)
DATAEND: bool, // bit offset: 8 desc: Data end (data counter, SDIDCOUNT, is zero)
STBITERR: bool, // bit offset: 9 desc: Start bit not detected on all data signals in wide bus mode
DBCKEND: bool, // bit offset: 10 desc: Data block sent/received (CRC check passed)
CMDACT: bool, // bit offset: 11 desc: Command transfer in progress
TXACT: bool, // bit offset: 12 desc: Data transmit in progress
RXACT: bool, // bit offset: 13 desc: Data receive in progress
TXFIFOHE: bool, // bit offset: 14 desc: Transmit FIFO half empty: at least 8 words can be written into the FIFO
RXFIFOHF: bool, // bit offset: 15 desc: Receive FIFO half full: there are at least 8 words in the FIFO
TXFIFOF: bool, // bit offset: 16 desc: Transmit FIFO full
RXFIFOF: bool, // bit offset: 17 desc: Receive FIFO full
TXFIFOE: bool, // bit offset: 18 desc: Transmit FIFO empty
RXFIFOE: bool, // bit offset: 19 desc: Receive FIFO empty
TXDAVL: bool, // bit offset: 20 desc: Data available in transmit FIFO
RXDAVL: bool, // bit offset: 21 desc: Data available in receive FIFO
SDIOIT: bool, // bit offset: 22 desc: SDIO interrupt received
CEATAEND: bool, // bit offset: 23 desc: CE-ATA command completion signal received for CMD61
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const ICR = MMIO(Address + 0x00000038, u32, packed struct { // byte offset: 56 interrupt clear register
CCRCFAILC: bool, // bit offset: 0 desc: CCRCFAIL flag clear bit
DCRCFAILC: bool, // bit offset: 1 desc: DCRCFAIL flag clear bit
CTIMEOUTC: bool, // bit offset: 2 desc: CTIMEOUT flag clear bit
DTIMEOUTC: bool, // bit offset: 3 desc: DTIMEOUT flag clear bit
TXUNDERRC: bool, // bit offset: 4 desc: TXUNDERR flag clear bit
RXOVERRC: bool, // bit offset: 5 desc: RXOVERR flag clear bit
CMDRENDC: bool, // bit offset: 6 desc: CMDREND flag clear bit
CMDSENTC: bool, // bit offset: 7 desc: CMDSENT flag clear bit
DATAENDC: bool, // bit offset: 8 desc: DATAEND flag clear bit
STBITERRC: bool, // bit offset: 9 desc: STBITERR flag clear bit
DBCKENDC: bool, // bit offset: 10 desc: DBCKEND flag clear bit
reserved0: u11 = 0,
SDIOITC: bool, // bit offset: 22 desc: SDIOIT flag clear bit
CEATAENDC: bool, // bit offset: 23 desc: CEATAEND flag clear bit
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const MASK = MMIO(Address + 0x0000003c, u32, packed struct { // byte offset: 60 mask register
CCRCFAILIE: bool, // bit offset: 0 desc: Command CRC fail interrupt enable
DCRCFAILIE: bool, // bit offset: 1 desc: Data CRC fail interrupt enable
CTIMEOUTIE: bool, // bit offset: 2 desc: Command timeout interrupt enable
DTIMEOUTIE: bool, // bit offset: 3 desc: Data timeout interrupt enable
TXUNDERRIE: bool, // bit offset: 4 desc: Tx FIFO underrun error interrupt enable
RXOVERRIE: bool, // bit offset: 5 desc: Rx FIFO overrun error interrupt enable
CMDRENDIE: bool, // bit offset: 6 desc: Command response received interrupt enable
CMDSENTIE: bool, // bit offset: 7 desc: Command sent interrupt enable
DATAENDIE: bool, // bit offset: 8 desc: Data end interrupt enable
STBITERRIE: bool, // bit offset: 9 desc: Start bit error interrupt enable
DBCKENDIE: bool, // bit offset: 10 desc: Data block end interrupt enable
CMDACTIE: bool, // bit offset: 11 desc: Command acting interrupt enable
TXACTIE: bool, // bit offset: 12 desc: Data transmit acting interrupt enable
RXACTIE: bool, // bit offset: 13 desc: Data receive acting interrupt enable
TXFIFOHEIE: bool, // bit offset: 14 desc: Tx FIFO half empty interrupt enable
RXFIFOHFIE: bool, // bit offset: 15 desc: Rx FIFO half full interrupt enable
TXFIFOFIE: bool, // bit offset: 16 desc: Tx FIFO full interrupt enable
RXFIFOFIE: bool, // bit offset: 17 desc: Rx FIFO full interrupt enable
TXFIFOEIE: bool, // bit offset: 18 desc: Tx FIFO empty interrupt enable
RXFIFOEIE: bool, // bit offset: 19 desc: Rx FIFO empty interrupt enable
TXDAVLIE: bool, // bit offset: 20 desc: Data available in Tx FIFO interrupt enable
RXDAVLIE: bool, // bit offset: 21 desc: Data available in Rx FIFO interrupt enable
SDIOITIE: bool, // bit offset: 22 desc: SDIO mode interrupt received interrupt enable
CEATAENDIE: bool, // bit offset: 23 desc: CE-ATA command completion signal received interrupt enable
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FIFOCNT = MMIO(Address + 0x00000048, u32, packed struct { // byte offset: 72 FIFO counter register
FIFOCOUNT: u24, // bit offset: 0 desc: Remaining number of words to be written to or read from the FIFO.
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const FIFO = MMIO(Address + 0x00000080, u32, packed struct { // byte offset: 128 data FIFO register
FIFOData: u32, // bit offset: 0 desc: Receive and transmit FIFO data
});
};
pub const SYSCFG = extern struct {
pub const Address: u32 = 0x40013800;
pub const MEMRM = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 memory remap register
MEM_MODE: u2, // bit offset: 0 desc: MEM_MODE
padding30: u1 = 0,
padding29: u1 = 0,
padding28: u1 = 0,
padding27: u1 = 0,
padding26: u1 = 0,
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const PMC = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 peripheral mode configuration register
reserved0: u16 = 0,
ADC1DC2: bool, // bit offset: 16 desc: ADC1DC2
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const EXTICR1 = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 external interrupt configuration register 1
EXTI0: u4, // bit offset: 0 desc: EXTI x configuration (x = 0 to 3)
EXTI1: u4, // bit offset: 4 desc: EXTI x configuration (x = 0 to 3)
EXTI2: u4, // bit offset: 8 desc: EXTI x configuration (x = 0 to 3)
EXTI3: u4, // bit offset: 12 desc: EXTI x configuration (x = 0 to 3)
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const EXTICR2 = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 external interrupt configuration register 2
EXTI4: u4, // bit offset: 0 desc: EXTI x configuration (x = 4 to 7)
EXTI5: u4, // bit offset: 4 desc: EXTI x configuration (x = 4 to 7)
EXTI6: u4, // bit offset: 8 desc: EXTI x configuration (x = 4 to 7)
EXTI7: u4, // bit offset: 12 desc: EXTI x configuration (x = 4 to 7)
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const EXTICR3 = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 external interrupt configuration register 3
EXTI8: u4, // bit offset: 0 desc: EXTI x configuration (x = 8 to 11)
EXTI9: u4, // bit offset: 4 desc: EXTI x configuration (x = 8 to 11)
EXTI10: u4, // bit offset: 8 desc: EXTI10
EXTI11: u4, // bit offset: 12 desc: EXTI x configuration (x = 8 to 11)
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const EXTICR4 = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 external interrupt configuration register 4
EXTI12: u4, // bit offset: 0 desc: EXTI x configuration (x = 12 to 15)
EXTI13: u4, // bit offset: 4 desc: EXTI x configuration (x = 12 to 15)
EXTI14: u4, // bit offset: 8 desc: EXTI x configuration (x = 12 to 15)
EXTI15: u4, // bit offset: 12 desc: EXTI x configuration (x = 12 to 15)
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CMPCR = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 Compensation cell control register
CMP_PD: bool, // bit offset: 0 desc: Compensation cell power-down
reserved0: u7 = 0,
READY: bool, // bit offset: 8 desc: READY
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const TIM1 = extern struct {
pub const Address: u32 = 0x40010000;
pub const CR1 = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 control register 1
CEN: bool, // bit offset: 0 desc: Counter enable
UDIS: bool, // bit offset: 1 desc: Update disable
URS: bool, // bit offset: 2 desc: Update request source
OPM: bool, // bit offset: 3 desc: One-pulse mode
DIR: bool, // bit offset: 4 desc: Direction
CMS: u2, // bit offset: 5 desc: Center-aligned mode selection
ARPE: bool, // bit offset: 7 desc: Auto-reload preload enable
CKD: u2, // bit offset: 8 desc: Clock division
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR2 = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 control register 2
CCPC: bool, // bit offset: 0 desc: Capture/compare preloaded control
reserved0: u1 = 0,
CCUS: bool, // bit offset: 2 desc: Capture/compare control update selection
CCDS: bool, // bit offset: 3 desc: Capture/compare DMA selection
MMS: u3, // bit offset: 4 desc: Master mode selection
TI1S: bool, // bit offset: 7 desc: TI1 selection
OIS1: bool, // bit offset: 8 desc: Output Idle state 1
OIS1N: bool, // bit offset: 9 desc: Output Idle state 1
OIS2: bool, // bit offset: 10 desc: Output Idle state 2
OIS2N: bool, // bit offset: 11 desc: Output Idle state 2
OIS3: bool, // bit offset: 12 desc: Output Idle state 3
OIS3N: bool, // bit offset: 13 desc: Output Idle state 3
OIS4: bool, // bit offset: 14 desc: Output Idle state 4
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SMCR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 slave mode control register
SMS: u3, // bit offset: 0 desc: Slave mode selection
reserved0: u1 = 0,
TS: u3, // bit offset: 4 desc: Trigger selection
MSM: bool, // bit offset: 7 desc: Master/Slave mode
ETF: u4, // bit offset: 8 desc: External trigger filter
ETPS: u2, // bit offset: 12 desc: External trigger prescaler
ECE: bool, // bit offset: 14 desc: External clock enable
ETP: bool, // bit offset: 15 desc: External trigger polarity
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DIER = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 DMA/Interrupt enable register
UIE: bool, // bit offset: 0 desc: Update interrupt enable
CC1IE: bool, // bit offset: 1 desc: Capture/Compare 1 interrupt enable
CC2IE: bool, // bit offset: 2 desc: Capture/Compare 2 interrupt enable
CC3IE: bool, // bit offset: 3 desc: Capture/Compare 3 interrupt enable
CC4IE: bool, // bit offset: 4 desc: Capture/Compare 4 interrupt enable
COMIE: bool, // bit offset: 5 desc: COM interrupt enable
TIE: bool, // bit offset: 6 desc: Trigger interrupt enable
BIE: bool, // bit offset: 7 desc: Break interrupt enable
UDE: bool, // bit offset: 8 desc: Update DMA request enable
CC1DE: bool, // bit offset: 9 desc: Capture/Compare 1 DMA request enable
CC2DE: bool, // bit offset: 10 desc: Capture/Compare 2 DMA request enable
CC3DE: bool, // bit offset: 11 desc: Capture/Compare 3 DMA request enable
CC4DE: bool, // bit offset: 12 desc: Capture/Compare 4 DMA request enable
COMDE: bool, // bit offset: 13 desc: COM DMA request enable
TDE: bool, // bit offset: 14 desc: Trigger DMA request enable
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 status register
UIF: bool, // bit offset: 0 desc: Update interrupt flag
CC1IF: bool, // bit offset: 1 desc: Capture/compare 1 interrupt flag
CC2IF: bool, // bit offset: 2 desc: Capture/Compare 2 interrupt flag
CC3IF: bool, // bit offset: 3 desc: Capture/Compare 3 interrupt flag
CC4IF: bool, // bit offset: 4 desc: Capture/Compare 4 interrupt flag
COMIF: bool, // bit offset: 5 desc: COM interrupt flag
TIF: bool, // bit offset: 6 desc: Trigger interrupt flag
BIF: bool, // bit offset: 7 desc: Break interrupt flag
reserved0: u1 = 0,
CC1OF: bool, // bit offset: 9 desc: Capture/Compare 1 overcapture flag
CC2OF: bool, // bit offset: 10 desc: Capture/compare 2 overcapture flag
CC3OF: bool, // bit offset: 11 desc: Capture/Compare 3 overcapture flag
CC4OF: bool, // bit offset: 12 desc: Capture/Compare 4 overcapture flag
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const EGR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 event generation register
UG: bool, // bit offset: 0 desc: Update generation
CC1G: bool, // bit offset: 1 desc: Capture/compare 1 generation
CC2G: bool, // bit offset: 2 desc: Capture/compare 2 generation
CC3G: bool, // bit offset: 3 desc: Capture/compare 3 generation
CC4G: bool, // bit offset: 4 desc: Capture/compare 4 generation
COMG: bool, // bit offset: 5 desc: Capture/Compare control update generation
TG: bool, // bit offset: 6 desc: Trigger generation
BG: bool, // bit offset: 7 desc: Break generation
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR1_Output = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 capture/compare mode register 1 (output mode)
CC1S: u2, // bit offset: 0 desc: Capture/Compare 1 selection
OC1FE: bool, // bit offset: 2 desc: Output Compare 1 fast enable
OC1PE: bool, // bit offset: 3 desc: Output Compare 1 preload enable
OC1M: u3, // bit offset: 4 desc: Output Compare 1 mode
OC1CE: bool, // bit offset: 7 desc: Output Compare 1 clear enable
CC2S: u2, // bit offset: 8 desc: Capture/Compare 2 selection
OC2FE: bool, // bit offset: 10 desc: Output Compare 2 fast enable
OC2PE: bool, // bit offset: 11 desc: Output Compare 2 preload enable
OC2M: u3, // bit offset: 12 desc: Output Compare 2 mode
OC2CE: bool, // bit offset: 15 desc: Output Compare 2 clear enable
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR1_Input = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 capture/compare mode register 1 (input mode)
CC1S: u2, // bit offset: 0 desc: Capture/Compare 1 selection
ICPCS: u2, // bit offset: 2 desc: Input capture 1 prescaler
IC1F: u4, // bit offset: 4 desc: Input capture 1 filter
CC2S: u2, // bit offset: 8 desc: Capture/Compare 2 selection
IC2PCS: u2, // bit offset: 10 desc: Input capture 2 prescaler
IC2F: u4, // bit offset: 12 desc: Input capture 2 filter
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR2_Output = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 capture/compare mode register 2 (output mode)
CC3S: u2, // bit offset: 0 desc: Capture/Compare 3 selection
OC3FE: bool, // bit offset: 2 desc: Output compare 3 fast enable
OC3PE: bool, // bit offset: 3 desc: Output compare 3 preload enable
OC3M: u3, // bit offset: 4 desc: Output compare 3 mode
OC3CE: bool, // bit offset: 7 desc: Output compare 3 clear enable
CC4S: u2, // bit offset: 8 desc: Capture/Compare 4 selection
OC4FE: bool, // bit offset: 10 desc: Output compare 4 fast enable
OC4PE: bool, // bit offset: 11 desc: Output compare 4 preload enable
OC4M: u3, // bit offset: 12 desc: Output compare 4 mode
OC4CE: bool, // bit offset: 15 desc: Output compare 4 clear enable
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR2_Input = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 capture/compare mode register 2 (input mode)
CC3S: u2, // bit offset: 0 desc: Capture/compare 3 selection
IC3PSC: u2, // bit offset: 2 desc: Input capture 3 prescaler
IC3F: u4, // bit offset: 4 desc: Input capture 3 filter
CC4S: u2, // bit offset: 8 desc: Capture/Compare 4 selection
IC4PSC: u2, // bit offset: 10 desc: Input capture 4 prescaler
IC4F: u4, // bit offset: 12 desc: Input capture 4 filter
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCER = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 capture/compare enable register
CC1E: bool, // bit offset: 0 desc: Capture/Compare 1 output enable
CC1P: bool, // bit offset: 1 desc: Capture/Compare 1 output Polarity
CC1NE: bool, // bit offset: 2 desc: Capture/Compare 1 complementary output enable
CC1NP: bool, // bit offset: 3 desc: Capture/Compare 1 output Polarity
CC2E: bool, // bit offset: 4 desc: Capture/Compare 2 output enable
CC2P: bool, // bit offset: 5 desc: Capture/Compare 2 output Polarity
CC2NE: bool, // bit offset: 6 desc: Capture/Compare 2 complementary output enable
CC2NP: bool, // bit offset: 7 desc: Capture/Compare 2 output Polarity
CC3E: bool, // bit offset: 8 desc: Capture/Compare 3 output enable
CC3P: bool, // bit offset: 9 desc: Capture/Compare 3 output Polarity
CC3NE: bool, // bit offset: 10 desc: Capture/Compare 3 complementary output enable
CC3NP: bool, // bit offset: 11 desc: Capture/Compare 3 output Polarity
CC4E: bool, // bit offset: 12 desc: Capture/Compare 4 output enable
CC4P: bool, // bit offset: 13 desc: Capture/Compare 3 output Polarity
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CNT = MMIO(Address + 0x00000024, u32, packed struct { // byte offset: 36 counter
CNT: u16, // bit offset: 0 desc: counter value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const PSC = MMIO(Address + 0x00000028, u32, packed struct { // byte offset: 40 prescaler
PSC: u16, // bit offset: 0 desc: Prescaler value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const ARR = MMIO(Address + 0x0000002c, u32, packed struct { // byte offset: 44 auto-reload register
ARR: u16, // bit offset: 0 desc: Auto-reload value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const RCR = MMIO(Address + 0x00000030, u32, packed struct { // byte offset: 48 repetition counter register
REP: u8, // bit offset: 0 desc: Repetition counter value
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCR1 = MMIO(Address + 0x00000034, u32, packed struct { // byte offset: 52 capture/compare register 1
CCR1: u16, // bit offset: 0 desc: Capture/Compare 1 value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCR2 = MMIO(Address + 0x00000038, u32, packed struct { // byte offset: 56 capture/compare register 2
CCR2: u16, // bit offset: 0 desc: Capture/Compare 2 value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCR3 = MMIO(Address + 0x0000003c, u32, packed struct { // byte offset: 60 capture/compare register 3
CCR3: u16, // bit offset: 0 desc: Capture/Compare value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCR4 = MMIO(Address + 0x00000040, u32, packed struct { // byte offset: 64 capture/compare register 4
CCR4: u16, // bit offset: 0 desc: Capture/Compare value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const BDTR = MMIO(Address + 0x00000044, u32, packed struct { // byte offset: 68 break and dead-time register
DTG: u8, // bit offset: 0 desc: Dead-time generator setup
LOCK: u2, // bit offset: 8 desc: Lock configuration
OSSI: bool, // bit offset: 10 desc: Off-state selection for Idle mode
OSSR: bool, // bit offset: 11 desc: Off-state selection for Run mode
BKE: bool, // bit offset: 12 desc: Break enable
BKP: bool, // bit offset: 13 desc: Break polarity
AOE: bool, // bit offset: 14 desc: Automatic output enable
MOE: bool, // bit offset: 15 desc: Main output enable
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DCR = MMIO(Address + 0x00000048, u32, packed struct { // byte offset: 72 DMA control register
DBA: u5, // bit offset: 0 desc: DMA base address
reserved0: u3 = 0,
DBL: u5, // bit offset: 8 desc: DMA burst length
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DMAR = MMIO(Address + 0x0000004c, u32, packed struct { // byte offset: 76 DMA address for full transfer
DMAB: u16, // bit offset: 0 desc: DMA register for burst accesses
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const TIM8 = extern struct {
pub const Address: u32 = 0x40010400;
pub const CR1 = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 control register 1
CEN: bool, // bit offset: 0 desc: Counter enable
UDIS: bool, // bit offset: 1 desc: Update disable
URS: bool, // bit offset: 2 desc: Update request source
OPM: bool, // bit offset: 3 desc: One-pulse mode
DIR: bool, // bit offset: 4 desc: Direction
CMS: u2, // bit offset: 5 desc: Center-aligned mode selection
ARPE: bool, // bit offset: 7 desc: Auto-reload preload enable
CKD: u2, // bit offset: 8 desc: Clock division
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR2 = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 control register 2
CCPC: bool, // bit offset: 0 desc: Capture/compare preloaded control
reserved0: u1 = 0,
CCUS: bool, // bit offset: 2 desc: Capture/compare control update selection
CCDS: bool, // bit offset: 3 desc: Capture/compare DMA selection
MMS: u3, // bit offset: 4 desc: Master mode selection
TI1S: bool, // bit offset: 7 desc: TI1 selection
OIS1: bool, // bit offset: 8 desc: Output Idle state 1
OIS1N: bool, // bit offset: 9 desc: Output Idle state 1
OIS2: bool, // bit offset: 10 desc: Output Idle state 2
OIS2N: bool, // bit offset: 11 desc: Output Idle state 2
OIS3: bool, // bit offset: 12 desc: Output Idle state 3
OIS3N: bool, // bit offset: 13 desc: Output Idle state 3
OIS4: bool, // bit offset: 14 desc: Output Idle state 4
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SMCR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 slave mode control register
SMS: u3, // bit offset: 0 desc: Slave mode selection
reserved0: u1 = 0,
TS: u3, // bit offset: 4 desc: Trigger selection
MSM: bool, // bit offset: 7 desc: Master/Slave mode
ETF: u4, // bit offset: 8 desc: External trigger filter
ETPS: u2, // bit offset: 12 desc: External trigger prescaler
ECE: bool, // bit offset: 14 desc: External clock enable
ETP: bool, // bit offset: 15 desc: External trigger polarity
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DIER = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 DMA/Interrupt enable register
UIE: bool, // bit offset: 0 desc: Update interrupt enable
CC1IE: bool, // bit offset: 1 desc: Capture/Compare 1 interrupt enable
CC2IE: bool, // bit offset: 2 desc: Capture/Compare 2 interrupt enable
CC3IE: bool, // bit offset: 3 desc: Capture/Compare 3 interrupt enable
CC4IE: bool, // bit offset: 4 desc: Capture/Compare 4 interrupt enable
COMIE: bool, // bit offset: 5 desc: COM interrupt enable
TIE: bool, // bit offset: 6 desc: Trigger interrupt enable
BIE: bool, // bit offset: 7 desc: Break interrupt enable
UDE: bool, // bit offset: 8 desc: Update DMA request enable
CC1DE: bool, // bit offset: 9 desc: Capture/Compare 1 DMA request enable
CC2DE: bool, // bit offset: 10 desc: Capture/Compare 2 DMA request enable
CC3DE: bool, // bit offset: 11 desc: Capture/Compare 3 DMA request enable
CC4DE: bool, // bit offset: 12 desc: Capture/Compare 4 DMA request enable
COMDE: bool, // bit offset: 13 desc: COM DMA request enable
TDE: bool, // bit offset: 14 desc: Trigger DMA request enable
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 status register
UIF: bool, // bit offset: 0 desc: Update interrupt flag
CC1IF: bool, // bit offset: 1 desc: Capture/compare 1 interrupt flag
CC2IF: bool, // bit offset: 2 desc: Capture/Compare 2 interrupt flag
CC3IF: bool, // bit offset: 3 desc: Capture/Compare 3 interrupt flag
CC4IF: bool, // bit offset: 4 desc: Capture/Compare 4 interrupt flag
COMIF: bool, // bit offset: 5 desc: COM interrupt flag
TIF: bool, // bit offset: 6 desc: Trigger interrupt flag
BIF: bool, // bit offset: 7 desc: Break interrupt flag
reserved0: u1 = 0,
CC1OF: bool, // bit offset: 9 desc: Capture/Compare 1 overcapture flag
CC2OF: bool, // bit offset: 10 desc: Capture/compare 2 overcapture flag
CC3OF: bool, // bit offset: 11 desc: Capture/Compare 3 overcapture flag
CC4OF: bool, // bit offset: 12 desc: Capture/Compare 4 overcapture flag
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const EGR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 event generation register
UG: bool, // bit offset: 0 desc: Update generation
CC1G: bool, // bit offset: 1 desc: Capture/compare 1 generation
CC2G: bool, // bit offset: 2 desc: Capture/compare 2 generation
CC3G: bool, // bit offset: 3 desc: Capture/compare 3 generation
CC4G: bool, // bit offset: 4 desc: Capture/compare 4 generation
COMG: bool, // bit offset: 5 desc: Capture/Compare control update generation
TG: bool, // bit offset: 6 desc: Trigger generation
BG: bool, // bit offset: 7 desc: Break generation
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR1_Output = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 capture/compare mode register 1 (output mode)
CC1S: u2, // bit offset: 0 desc: Capture/Compare 1 selection
OC1FE: bool, // bit offset: 2 desc: Output Compare 1 fast enable
OC1PE: bool, // bit offset: 3 desc: Output Compare 1 preload enable
OC1M: u3, // bit offset: 4 desc: Output Compare 1 mode
OC1CE: bool, // bit offset: 7 desc: Output Compare 1 clear enable
CC2S: u2, // bit offset: 8 desc: Capture/Compare 2 selection
OC2FE: bool, // bit offset: 10 desc: Output Compare 2 fast enable
OC2PE: bool, // bit offset: 11 desc: Output Compare 2 preload enable
OC2M: u3, // bit offset: 12 desc: Output Compare 2 mode
OC2CE: bool, // bit offset: 15 desc: Output Compare 2 clear enable
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR1_Input = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 capture/compare mode register 1 (input mode)
CC1S: u2, // bit offset: 0 desc: Capture/Compare 1 selection
ICPCS: u2, // bit offset: 2 desc: Input capture 1 prescaler
IC1F: u4, // bit offset: 4 desc: Input capture 1 filter
CC2S: u2, // bit offset: 8 desc: Capture/Compare 2 selection
IC2PCS: u2, // bit offset: 10 desc: Input capture 2 prescaler
IC2F: u4, // bit offset: 12 desc: Input capture 2 filter
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR2_Output = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 capture/compare mode register 2 (output mode)
CC3S: u2, // bit offset: 0 desc: Capture/Compare 3 selection
OC3FE: bool, // bit offset: 2 desc: Output compare 3 fast enable
OC3PE: bool, // bit offset: 3 desc: Output compare 3 preload enable
OC3M: u3, // bit offset: 4 desc: Output compare 3 mode
OC3CE: bool, // bit offset: 7 desc: Output compare 3 clear enable
CC4S: u2, // bit offset: 8 desc: Capture/Compare 4 selection
OC4FE: bool, // bit offset: 10 desc: Output compare 4 fast enable
OC4PE: bool, // bit offset: 11 desc: Output compare 4 preload enable
OC4M: u3, // bit offset: 12 desc: Output compare 4 mode
OC4CE: bool, // bit offset: 15 desc: Output compare 4 clear enable
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR2_Input = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 capture/compare mode register 2 (input mode)
CC3S: u2, // bit offset: 0 desc: Capture/compare 3 selection
IC3PSC: u2, // bit offset: 2 desc: Input capture 3 prescaler
IC3F: u4, // bit offset: 4 desc: Input capture 3 filter
CC4S: u2, // bit offset: 8 desc: Capture/Compare 4 selection
IC4PSC: u2, // bit offset: 10 desc: Input capture 4 prescaler
IC4F: u4, // bit offset: 12 desc: Input capture 4 filter
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCER = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 capture/compare enable register
CC1E: bool, // bit offset: 0 desc: Capture/Compare 1 output enable
CC1P: bool, // bit offset: 1 desc: Capture/Compare 1 output Polarity
CC1NE: bool, // bit offset: 2 desc: Capture/Compare 1 complementary output enable
CC1NP: bool, // bit offset: 3 desc: Capture/Compare 1 output Polarity
CC2E: bool, // bit offset: 4 desc: Capture/Compare 2 output enable
CC2P: bool, // bit offset: 5 desc: Capture/Compare 2 output Polarity
CC2NE: bool, // bit offset: 6 desc: Capture/Compare 2 complementary output enable
CC2NP: bool, // bit offset: 7 desc: Capture/Compare 2 output Polarity
CC3E: bool, // bit offset: 8 desc: Capture/Compare 3 output enable
CC3P: bool, // bit offset: 9 desc: Capture/Compare 3 output Polarity
CC3NE: bool, // bit offset: 10 desc: Capture/Compare 3 complementary output enable
CC3NP: bool, // bit offset: 11 desc: Capture/Compare 3 output Polarity
CC4E: bool, // bit offset: 12 desc: Capture/Compare 4 output enable
CC4P: bool, // bit offset: 13 desc: Capture/Compare 3 output Polarity
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CNT = MMIO(Address + 0x00000024, u32, packed struct { // byte offset: 36 counter
CNT: u16, // bit offset: 0 desc: counter value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const PSC = MMIO(Address + 0x00000028, u32, packed struct { // byte offset: 40 prescaler
PSC: u16, // bit offset: 0 desc: Prescaler value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const ARR = MMIO(Address + 0x0000002c, u32, packed struct { // byte offset: 44 auto-reload register
ARR: u16, // bit offset: 0 desc: Auto-reload value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const RCR = MMIO(Address + 0x00000030, u32, packed struct { // byte offset: 48 repetition counter register
REP: u8, // bit offset: 0 desc: Repetition counter value
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCR1 = MMIO(Address + 0x00000034, u32, packed struct { // byte offset: 52 capture/compare register 1
CCR1: u16, // bit offset: 0 desc: Capture/Compare 1 value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCR2 = MMIO(Address + 0x00000038, u32, packed struct { // byte offset: 56 capture/compare register 2
CCR2: u16, // bit offset: 0 desc: Capture/Compare 2 value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCR3 = MMIO(Address + 0x0000003c, u32, packed struct { // byte offset: 60 capture/compare register 3
CCR3: u16, // bit offset: 0 desc: Capture/Compare value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCR4 = MMIO(Address + 0x00000040, u32, packed struct { // byte offset: 64 capture/compare register 4
CCR4: u16, // bit offset: 0 desc: Capture/Compare value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const BDTR = MMIO(Address + 0x00000044, u32, packed struct { // byte offset: 68 break and dead-time register
DTG: u8, // bit offset: 0 desc: Dead-time generator setup
LOCK: u2, // bit offset: 8 desc: Lock configuration
OSSI: bool, // bit offset: 10 desc: Off-state selection for Idle mode
OSSR: bool, // bit offset: 11 desc: Off-state selection for Run mode
BKE: bool, // bit offset: 12 desc: Break enable
BKP: bool, // bit offset: 13 desc: Break polarity
AOE: bool, // bit offset: 14 desc: Automatic output enable
MOE: bool, // bit offset: 15 desc: Main output enable
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DCR = MMIO(Address + 0x00000048, u32, packed struct { // byte offset: 72 DMA control register
DBA: u5, // bit offset: 0 desc: DMA base address
reserved0: u3 = 0,
DBL: u5, // bit offset: 8 desc: DMA burst length
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DMAR = MMIO(Address + 0x0000004c, u32, packed struct { // byte offset: 76 DMA address for full transfer
DMAB: u16, // bit offset: 0 desc: DMA register for burst accesses
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const TIM10 = extern struct {
pub const Address: u32 = 0x40014400;
pub const CR1 = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 control register 1
CEN: bool, // bit offset: 0 desc: Counter enable
UDIS: bool, // bit offset: 1 desc: Update disable
URS: bool, // bit offset: 2 desc: Update request source
reserved0: u4 = 0,
ARPE: bool, // bit offset: 7 desc: Auto-reload preload enable
CKD: u2, // bit offset: 8 desc: Clock division
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DIER = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 DMA/Interrupt enable register
UIE: bool, // bit offset: 0 desc: Update interrupt enable
CC1IE: bool, // bit offset: 1 desc: Capture/Compare 1 interrupt enable
padding30: u1 = 0,
padding29: u1 = 0,
padding28: u1 = 0,
padding27: u1 = 0,
padding26: u1 = 0,
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 status register
UIF: bool, // bit offset: 0 desc: Update interrupt flag
CC1IF: bool, // bit offset: 1 desc: Capture/compare 1 interrupt flag
reserved0: u7 = 0,
CC1OF: bool, // bit offset: 9 desc: Capture/Compare 1 overcapture flag
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const EGR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 event generation register
UG: bool, // bit offset: 0 desc: Update generation
CC1G: bool, // bit offset: 1 desc: Capture/compare 1 generation
padding30: u1 = 0,
padding29: u1 = 0,
padding28: u1 = 0,
padding27: u1 = 0,
padding26: u1 = 0,
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR1_Output = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 capture/compare mode register 1 (output mode)
CC1S: u2, // bit offset: 0 desc: Capture/Compare 1 selection
OC1FE: bool, // bit offset: 2 desc: Output Compare 1 fast enable
OC1PE: bool, // bit offset: 3 desc: Output Compare 1 preload enable
OC1M: u3, // bit offset: 4 desc: Output Compare 1 mode
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR1_Input = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 capture/compare mode register 1 (input mode)
CC1S: u2, // bit offset: 0 desc: Capture/Compare 1 selection
ICPCS: u2, // bit offset: 2 desc: Input capture 1 prescaler
IC1F: u4, // bit offset: 4 desc: Input capture 1 filter
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCER = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 capture/compare enable register
CC1E: bool, // bit offset: 0 desc: Capture/Compare 1 output enable
CC1P: bool, // bit offset: 1 desc: Capture/Compare 1 output Polarity
reserved0: u1 = 0,
CC1NP: bool, // bit offset: 3 desc: Capture/Compare 1 output Polarity
padding28: u1 = 0,
padding27: u1 = 0,
padding26: u1 = 0,
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CNT = MMIO(Address + 0x00000024, u32, packed struct { // byte offset: 36 counter
CNT: u16, // bit offset: 0 desc: counter value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const PSC = MMIO(Address + 0x00000028, u32, packed struct { // byte offset: 40 prescaler
PSC: u16, // bit offset: 0 desc: Prescaler value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const ARR = MMIO(Address + 0x0000002c, u32, packed struct { // byte offset: 44 auto-reload register
ARR: u16, // bit offset: 0 desc: Auto-reload value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCR1 = MMIO(Address + 0x00000034, u32, packed struct { // byte offset: 52 capture/compare register 1
CCR1: u16, // bit offset: 0 desc: Capture/Compare 1 value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const TIM11 = extern struct {
pub const Address: u32 = 0x40014800;
pub const CR1 = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 control register 1
CEN: bool, // bit offset: 0 desc: Counter enable
UDIS: bool, // bit offset: 1 desc: Update disable
URS: bool, // bit offset: 2 desc: Update request source
reserved0: u4 = 0,
ARPE: bool, // bit offset: 7 desc: Auto-reload preload enable
CKD: u2, // bit offset: 8 desc: Clock division
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DIER = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 DMA/Interrupt enable register
UIE: bool, // bit offset: 0 desc: Update interrupt enable
CC1IE: bool, // bit offset: 1 desc: Capture/Compare 1 interrupt enable
padding30: u1 = 0,
padding29: u1 = 0,
padding28: u1 = 0,
padding27: u1 = 0,
padding26: u1 = 0,
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 status register
UIF: bool, // bit offset: 0 desc: Update interrupt flag
CC1IF: bool, // bit offset: 1 desc: Capture/compare 1 interrupt flag
reserved0: u7 = 0,
CC1OF: bool, // bit offset: 9 desc: Capture/Compare 1 overcapture flag
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const EGR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 event generation register
UG: bool, // bit offset: 0 desc: Update generation
CC1G: bool, // bit offset: 1 desc: Capture/compare 1 generation
padding30: u1 = 0,
padding29: u1 = 0,
padding28: u1 = 0,
padding27: u1 = 0,
padding26: u1 = 0,
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR1_Output = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 capture/compare mode register 1 (output mode)
CC1S: u2, // bit offset: 0 desc: Capture/Compare 1 selection
OC1FE: bool, // bit offset: 2 desc: Output Compare 1 fast enable
OC1PE: bool, // bit offset: 3 desc: Output Compare 1 preload enable
OC1M: u3, // bit offset: 4 desc: Output Compare 1 mode
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR1_Input = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 capture/compare mode register 1 (input mode)
CC1S: u2, // bit offset: 0 desc: Capture/Compare 1 selection
ICPCS: u2, // bit offset: 2 desc: Input capture 1 prescaler
IC1F: u4, // bit offset: 4 desc: Input capture 1 filter
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCER = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 capture/compare enable register
CC1E: bool, // bit offset: 0 desc: Capture/Compare 1 output enable
CC1P: bool, // bit offset: 1 desc: Capture/Compare 1 output Polarity
reserved0: u1 = 0,
CC1NP: bool, // bit offset: 3 desc: Capture/Compare 1 output Polarity
padding28: u1 = 0,
padding27: u1 = 0,
padding26: u1 = 0,
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CNT = MMIO(Address + 0x00000024, u32, packed struct { // byte offset: 36 counter
CNT: u16, // bit offset: 0 desc: counter value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const PSC = MMIO(Address + 0x00000028, u32, packed struct { // byte offset: 40 prescaler
PSC: u16, // bit offset: 0 desc: Prescaler value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const ARR = MMIO(Address + 0x0000002c, u32, packed struct { // byte offset: 44 auto-reload register
ARR: u16, // bit offset: 0 desc: Auto-reload value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCR1 = MMIO(Address + 0x00000034, u32, packed struct { // byte offset: 52 capture/compare register 1
CCR1: u16, // bit offset: 0 desc: Capture/Compare 1 value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const OR = MMIO(Address + 0x00000050, u32, packed struct { // byte offset: 80 option register
RMP: u2, // bit offset: 0 desc: Input 1 remapping capability
padding30: u1 = 0,
padding29: u1 = 0,
padding28: u1 = 0,
padding27: u1 = 0,
padding26: u1 = 0,
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const TIM2 = extern struct {
pub const Address: u32 = 0x40000000;
pub const CR1 = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 control register 1
CEN: bool, // bit offset: 0 desc: Counter enable
UDIS: bool, // bit offset: 1 desc: Update disable
URS: bool, // bit offset: 2 desc: Update request source
OPM: bool, // bit offset: 3 desc: One-pulse mode
DIR: bool, // bit offset: 4 desc: Direction
CMS: u2, // bit offset: 5 desc: Center-aligned mode selection
ARPE: bool, // bit offset: 7 desc: Auto-reload preload enable
CKD: u2, // bit offset: 8 desc: Clock division
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR2 = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 control register 2
reserved0: u3 = 0,
CCDS: bool, // bit offset: 3 desc: Capture/compare DMA selection
MMS: u3, // bit offset: 4 desc: Master mode selection
TI1S: bool, // bit offset: 7 desc: TI1 selection
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SMCR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 slave mode control register
SMS: u3, // bit offset: 0 desc: Slave mode selection
reserved0: u1 = 0,
TS: u3, // bit offset: 4 desc: Trigger selection
MSM: bool, // bit offset: 7 desc: Master/Slave mode
ETF: u4, // bit offset: 8 desc: External trigger filter
ETPS: u2, // bit offset: 12 desc: External trigger prescaler
ECE: bool, // bit offset: 14 desc: External clock enable
ETP: bool, // bit offset: 15 desc: External trigger polarity
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DIER = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 DMA/Interrupt enable register
UIE: bool, // bit offset: 0 desc: Update interrupt enable
CC1IE: bool, // bit offset: 1 desc: Capture/Compare 1 interrupt enable
CC2IE: bool, // bit offset: 2 desc: Capture/Compare 2 interrupt enable
CC3IE: bool, // bit offset: 3 desc: Capture/Compare 3 interrupt enable
CC4IE: bool, // bit offset: 4 desc: Capture/Compare 4 interrupt enable
reserved0: u1 = 0,
TIE: bool, // bit offset: 6 desc: Trigger interrupt enable
reserved1: u1 = 0,
UDE: bool, // bit offset: 8 desc: Update DMA request enable
CC1DE: bool, // bit offset: 9 desc: Capture/Compare 1 DMA request enable
CC2DE: bool, // bit offset: 10 desc: Capture/Compare 2 DMA request enable
CC3DE: bool, // bit offset: 11 desc: Capture/Compare 3 DMA request enable
CC4DE: bool, // bit offset: 12 desc: Capture/Compare 4 DMA request enable
reserved2: u1 = 0,
TDE: bool, // bit offset: 14 desc: Trigger DMA request enable
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 status register
UIF: bool, // bit offset: 0 desc: Update interrupt flag
CC1IF: bool, // bit offset: 1 desc: Capture/compare 1 interrupt flag
CC2IF: bool, // bit offset: 2 desc: Capture/Compare 2 interrupt flag
CC3IF: bool, // bit offset: 3 desc: Capture/Compare 3 interrupt flag
CC4IF: bool, // bit offset: 4 desc: Capture/Compare 4 interrupt flag
reserved0: u1 = 0,
TIF: bool, // bit offset: 6 desc: Trigger interrupt flag
reserved1: u2 = 0,
CC1OF: bool, // bit offset: 9 desc: Capture/Compare 1 overcapture flag
CC2OF: bool, // bit offset: 10 desc: Capture/compare 2 overcapture flag
CC3OF: bool, // bit offset: 11 desc: Capture/Compare 3 overcapture flag
CC4OF: bool, // bit offset: 12 desc: Capture/Compare 4 overcapture flag
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const EGR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 event generation register
UG: bool, // bit offset: 0 desc: Update generation
CC1G: bool, // bit offset: 1 desc: Capture/compare 1 generation
CC2G: bool, // bit offset: 2 desc: Capture/compare 2 generation
CC3G: bool, // bit offset: 3 desc: Capture/compare 3 generation
CC4G: bool, // bit offset: 4 desc: Capture/compare 4 generation
reserved0: u1 = 0,
TG: bool, // bit offset: 6 desc: Trigger generation
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR1_Output = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 capture/compare mode register 1 (output mode)
CC1S: u2, // bit offset: 0 desc: CC1S
OC1FE: bool, // bit offset: 2 desc: OC1FE
OC1PE: bool, // bit offset: 3 desc: OC1PE
OC1M: u3, // bit offset: 4 desc: OC1M
OC1CE: bool, // bit offset: 7 desc: OC1CE
CC2S: u2, // bit offset: 8 desc: CC2S
OC2FE: bool, // bit offset: 10 desc: OC2FE
OC2PE: bool, // bit offset: 11 desc: OC2PE
OC2M: u3, // bit offset: 12 desc: OC2M
OC2CE: bool, // bit offset: 15 desc: OC2CE
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR1_Input = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 capture/compare mode register 1 (input mode)
CC1S: u2, // bit offset: 0 desc: Capture/Compare 1 selection
ICPCS: u2, // bit offset: 2 desc: Input capture 1 prescaler
IC1F: u4, // bit offset: 4 desc: Input capture 1 filter
CC2S: u2, // bit offset: 8 desc: Capture/Compare 2 selection
IC2PCS: u2, // bit offset: 10 desc: Input capture 2 prescaler
IC2F: u4, // bit offset: 12 desc: Input capture 2 filter
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR2_Output = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 capture/compare mode register 2 (output mode)
CC3S: u2, // bit offset: 0 desc: CC3S
OC3FE: bool, // bit offset: 2 desc: OC3FE
OC3PE: bool, // bit offset: 3 desc: OC3PE
OC3M: u3, // bit offset: 4 desc: OC3M
OC3CE: bool, // bit offset: 7 desc: OC3CE
CC4S: u2, // bit offset: 8 desc: CC4S
OC4FE: bool, // bit offset: 10 desc: OC4FE
OC4PE: bool, // bit offset: 11 desc: OC4PE
OC4M: u3, // bit offset: 12 desc: OC4M
O24CE: bool, // bit offset: 15 desc: O24CE
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR2_Input = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 capture/compare mode register 2 (input mode)
CC3S: u2, // bit offset: 0 desc: Capture/compare 3 selection
IC3PSC: u2, // bit offset: 2 desc: Input capture 3 prescaler
IC3F: u4, // bit offset: 4 desc: Input capture 3 filter
CC4S: u2, // bit offset: 8 desc: Capture/Compare 4 selection
IC4PSC: u2, // bit offset: 10 desc: Input capture 4 prescaler
IC4F: u4, // bit offset: 12 desc: Input capture 4 filter
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCER = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 capture/compare enable register
CC1E: bool, // bit offset: 0 desc: Capture/Compare 1 output enable
CC1P: bool, // bit offset: 1 desc: Capture/Compare 1 output Polarity
reserved0: u1 = 0,
CC1NP: bool, // bit offset: 3 desc: Capture/Compare 1 output Polarity
CC2E: bool, // bit offset: 4 desc: Capture/Compare 2 output enable
CC2P: bool, // bit offset: 5 desc: Capture/Compare 2 output Polarity
reserved1: u1 = 0,
CC2NP: bool, // bit offset: 7 desc: Capture/Compare 2 output Polarity
CC3E: bool, // bit offset: 8 desc: Capture/Compare 3 output enable
CC3P: bool, // bit offset: 9 desc: Capture/Compare 3 output Polarity
reserved2: u1 = 0,
CC3NP: bool, // bit offset: 11 desc: Capture/Compare 3 output Polarity
CC4E: bool, // bit offset: 12 desc: Capture/Compare 4 output enable
CC4P: bool, // bit offset: 13 desc: Capture/Compare 3 output Polarity
reserved3: u1 = 0,
CC4NP: bool, // bit offset: 15 desc: Capture/Compare 4 output Polarity
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CNT = MMIO(Address + 0x00000024, u32, packed struct { // byte offset: 36 counter
CNT_L: u16, // bit offset: 0 desc: Low counter value
CNT_H: u16, // bit offset: 16 desc: High counter value
});
pub const PSC = MMIO(Address + 0x00000028, u32, packed struct { // byte offset: 40 prescaler
PSC: u16, // bit offset: 0 desc: Prescaler value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const ARR = MMIO(Address + 0x0000002c, u32, packed struct { // byte offset: 44 auto-reload register
ARR_L: u16, // bit offset: 0 desc: Low Auto-reload value
ARR_H: u16, // bit offset: 16 desc: High Auto-reload value
});
pub const CCR1 = MMIO(Address + 0x00000034, u32, packed struct { // byte offset: 52 capture/compare register 1
CCR1_L: u16, // bit offset: 0 desc: Low Capture/Compare 1 value
CCR1_H: u16, // bit offset: 16 desc: High Capture/Compare 1 value
});
pub const CCR2 = MMIO(Address + 0x00000038, u32, packed struct { // byte offset: 56 capture/compare register 2
CCR2_L: u16, // bit offset: 0 desc: Low Capture/Compare 2 value
CCR2_H: u16, // bit offset: 16 desc: High Capture/Compare 2 value
});
pub const CCR3 = MMIO(Address + 0x0000003c, u32, packed struct { // byte offset: 60 capture/compare register 3
CCR3_L: u16, // bit offset: 0 desc: Low Capture/Compare value
CCR3_H: u16, // bit offset: 16 desc: High Capture/Compare value
});
pub const CCR4 = MMIO(Address + 0x00000040, u32, packed struct { // byte offset: 64 capture/compare register 4
CCR4_L: u16, // bit offset: 0 desc: Low Capture/Compare value
CCR4_H: u16, // bit offset: 16 desc: High Capture/Compare value
});
pub const DCR = MMIO(Address + 0x00000048, u32, packed struct { // byte offset: 72 DMA control register
DBA: u5, // bit offset: 0 desc: DMA base address
reserved0: u3 = 0,
DBL: u5, // bit offset: 8 desc: DMA burst length
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DMAR = MMIO(Address + 0x0000004c, u32, packed struct { // byte offset: 76 DMA address for full transfer
DMAB: u16, // bit offset: 0 desc: DMA register for burst accesses
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const OR = MMIO(Address + 0x00000050, u32, packed struct { // byte offset: 80 TIM5 option register
reserved0: u10 = 0,
ITR1_RMP: u2, // bit offset: 10 desc: Timer Input 4 remap
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const TIM3 = extern struct {
pub const Address: u32 = 0x40000400;
pub const CR1 = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 control register 1
CEN: bool, // bit offset: 0 desc: Counter enable
UDIS: bool, // bit offset: 1 desc: Update disable
URS: bool, // bit offset: 2 desc: Update request source
OPM: bool, // bit offset: 3 desc: One-pulse mode
DIR: bool, // bit offset: 4 desc: Direction
CMS: u2, // bit offset: 5 desc: Center-aligned mode selection
ARPE: bool, // bit offset: 7 desc: Auto-reload preload enable
CKD: u2, // bit offset: 8 desc: Clock division
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR2 = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 control register 2
reserved0: u3 = 0,
CCDS: bool, // bit offset: 3 desc: Capture/compare DMA selection
MMS: u3, // bit offset: 4 desc: Master mode selection
TI1S: bool, // bit offset: 7 desc: TI1 selection
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SMCR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 slave mode control register
SMS: u3, // bit offset: 0 desc: Slave mode selection
reserved0: u1 = 0,
TS: u3, // bit offset: 4 desc: Trigger selection
MSM: bool, // bit offset: 7 desc: Master/Slave mode
ETF: u4, // bit offset: 8 desc: External trigger filter
ETPS: u2, // bit offset: 12 desc: External trigger prescaler
ECE: bool, // bit offset: 14 desc: External clock enable
ETP: bool, // bit offset: 15 desc: External trigger polarity
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DIER = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 DMA/Interrupt enable register
UIE: bool, // bit offset: 0 desc: Update interrupt enable
CC1IE: bool, // bit offset: 1 desc: Capture/Compare 1 interrupt enable
CC2IE: bool, // bit offset: 2 desc: Capture/Compare 2 interrupt enable
CC3IE: bool, // bit offset: 3 desc: Capture/Compare 3 interrupt enable
CC4IE: bool, // bit offset: 4 desc: Capture/Compare 4 interrupt enable
reserved0: u1 = 0,
TIE: bool, // bit offset: 6 desc: Trigger interrupt enable
reserved1: u1 = 0,
UDE: bool, // bit offset: 8 desc: Update DMA request enable
CC1DE: bool, // bit offset: 9 desc: Capture/Compare 1 DMA request enable
CC2DE: bool, // bit offset: 10 desc: Capture/Compare 2 DMA request enable
CC3DE: bool, // bit offset: 11 desc: Capture/Compare 3 DMA request enable
CC4DE: bool, // bit offset: 12 desc: Capture/Compare 4 DMA request enable
reserved2: u1 = 0,
TDE: bool, // bit offset: 14 desc: Trigger DMA request enable
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 status register
UIF: bool, // bit offset: 0 desc: Update interrupt flag
CC1IF: bool, // bit offset: 1 desc: Capture/compare 1 interrupt flag
CC2IF: bool, // bit offset: 2 desc: Capture/Compare 2 interrupt flag
CC3IF: bool, // bit offset: 3 desc: Capture/Compare 3 interrupt flag
CC4IF: bool, // bit offset: 4 desc: Capture/Compare 4 interrupt flag
reserved0: u1 = 0,
TIF: bool, // bit offset: 6 desc: Trigger interrupt flag
reserved1: u2 = 0,
CC1OF: bool, // bit offset: 9 desc: Capture/Compare 1 overcapture flag
CC2OF: bool, // bit offset: 10 desc: Capture/compare 2 overcapture flag
CC3OF: bool, // bit offset: 11 desc: Capture/Compare 3 overcapture flag
CC4OF: bool, // bit offset: 12 desc: Capture/Compare 4 overcapture flag
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const EGR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 event generation register
UG: bool, // bit offset: 0 desc: Update generation
CC1G: bool, // bit offset: 1 desc: Capture/compare 1 generation
CC2G: bool, // bit offset: 2 desc: Capture/compare 2 generation
CC3G: bool, // bit offset: 3 desc: Capture/compare 3 generation
CC4G: bool, // bit offset: 4 desc: Capture/compare 4 generation
reserved0: u1 = 0,
TG: bool, // bit offset: 6 desc: Trigger generation
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR1_Output = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 capture/compare mode register 1 (output mode)
CC1S: u2, // bit offset: 0 desc: CC1S
OC1FE: bool, // bit offset: 2 desc: OC1FE
OC1PE: bool, // bit offset: 3 desc: OC1PE
OC1M: u3, // bit offset: 4 desc: OC1M
OC1CE: bool, // bit offset: 7 desc: OC1CE
CC2S: u2, // bit offset: 8 desc: CC2S
OC2FE: bool, // bit offset: 10 desc: OC2FE
OC2PE: bool, // bit offset: 11 desc: OC2PE
OC2M: u3, // bit offset: 12 desc: OC2M
OC2CE: bool, // bit offset: 15 desc: OC2CE
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR1_Input = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 capture/compare mode register 1 (input mode)
CC1S: u2, // bit offset: 0 desc: Capture/Compare 1 selection
ICPCS: u2, // bit offset: 2 desc: Input capture 1 prescaler
IC1F: u4, // bit offset: 4 desc: Input capture 1 filter
CC2S: u2, // bit offset: 8 desc: Capture/Compare 2 selection
IC2PCS: u2, // bit offset: 10 desc: Input capture 2 prescaler
IC2F: u4, // bit offset: 12 desc: Input capture 2 filter
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR2_Output = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 capture/compare mode register 2 (output mode)
CC3S: u2, // bit offset: 0 desc: CC3S
OC3FE: bool, // bit offset: 2 desc: OC3FE
OC3PE: bool, // bit offset: 3 desc: OC3PE
OC3M: u3, // bit offset: 4 desc: OC3M
OC3CE: bool, // bit offset: 7 desc: OC3CE
CC4S: u2, // bit offset: 8 desc: CC4S
OC4FE: bool, // bit offset: 10 desc: OC4FE
OC4PE: bool, // bit offset: 11 desc: OC4PE
OC4M: u3, // bit offset: 12 desc: OC4M
O24CE: bool, // bit offset: 15 desc: O24CE
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR2_Input = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 capture/compare mode register 2 (input mode)
CC3S: u2, // bit offset: 0 desc: Capture/compare 3 selection
IC3PSC: u2, // bit offset: 2 desc: Input capture 3 prescaler
IC3F: u4, // bit offset: 4 desc: Input capture 3 filter
CC4S: u2, // bit offset: 8 desc: Capture/Compare 4 selection
IC4PSC: u2, // bit offset: 10 desc: Input capture 4 prescaler
IC4F: u4, // bit offset: 12 desc: Input capture 4 filter
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCER = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 capture/compare enable register
CC1E: bool, // bit offset: 0 desc: Capture/Compare 1 output enable
CC1P: bool, // bit offset: 1 desc: Capture/Compare 1 output Polarity
reserved0: u1 = 0,
CC1NP: bool, // bit offset: 3 desc: Capture/Compare 1 output Polarity
CC2E: bool, // bit offset: 4 desc: Capture/Compare 2 output enable
CC2P: bool, // bit offset: 5 desc: Capture/Compare 2 output Polarity
reserved1: u1 = 0,
CC2NP: bool, // bit offset: 7 desc: Capture/Compare 2 output Polarity
CC3E: bool, // bit offset: 8 desc: Capture/Compare 3 output enable
CC3P: bool, // bit offset: 9 desc: Capture/Compare 3 output Polarity
reserved2: u1 = 0,
CC3NP: bool, // bit offset: 11 desc: Capture/Compare 3 output Polarity
CC4E: bool, // bit offset: 12 desc: Capture/Compare 4 output enable
CC4P: bool, // bit offset: 13 desc: Capture/Compare 3 output Polarity
reserved3: u1 = 0,
CC4NP: bool, // bit offset: 15 desc: Capture/Compare 4 output Polarity
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CNT = MMIO(Address + 0x00000024, u32, packed struct { // byte offset: 36 counter
CNT_L: u16, // bit offset: 0 desc: Low counter value
CNT_H: u16, // bit offset: 16 desc: High counter value
});
pub const PSC = MMIO(Address + 0x00000028, u32, packed struct { // byte offset: 40 prescaler
PSC: u16, // bit offset: 0 desc: Prescaler value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const ARR = MMIO(Address + 0x0000002c, u32, packed struct { // byte offset: 44 auto-reload register
ARR_L: u16, // bit offset: 0 desc: Low Auto-reload value
ARR_H: u16, // bit offset: 16 desc: High Auto-reload value
});
pub const CCR1 = MMIO(Address + 0x00000034, u32, packed struct { // byte offset: 52 capture/compare register 1
CCR1_L: u16, // bit offset: 0 desc: Low Capture/Compare 1 value
CCR1_H: u16, // bit offset: 16 desc: High Capture/Compare 1 value
});
pub const CCR2 = MMIO(Address + 0x00000038, u32, packed struct { // byte offset: 56 capture/compare register 2
CCR2_L: u16, // bit offset: 0 desc: Low Capture/Compare 2 value
CCR2_H: u16, // bit offset: 16 desc: High Capture/Compare 2 value
});
pub const CCR3 = MMIO(Address + 0x0000003c, u32, packed struct { // byte offset: 60 capture/compare register 3
CCR3_L: u16, // bit offset: 0 desc: Low Capture/Compare value
CCR3_H: u16, // bit offset: 16 desc: High Capture/Compare value
});
pub const CCR4 = MMIO(Address + 0x00000040, u32, packed struct { // byte offset: 64 capture/compare register 4
CCR4_L: u16, // bit offset: 0 desc: Low Capture/Compare value
CCR4_H: u16, // bit offset: 16 desc: High Capture/Compare value
});
pub const DCR = MMIO(Address + 0x00000048, u32, packed struct { // byte offset: 72 DMA control register
DBA: u5, // bit offset: 0 desc: DMA base address
reserved0: u3 = 0,
DBL: u5, // bit offset: 8 desc: DMA burst length
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DMAR = MMIO(Address + 0x0000004c, u32, packed struct { // byte offset: 76 DMA address for full transfer
DMAB: u16, // bit offset: 0 desc: DMA register for burst accesses
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const TIM4 = extern struct {
pub const Address: u32 = 0x40000800;
pub const CR1 = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 control register 1
CEN: bool, // bit offset: 0 desc: Counter enable
UDIS: bool, // bit offset: 1 desc: Update disable
URS: bool, // bit offset: 2 desc: Update request source
OPM: bool, // bit offset: 3 desc: One-pulse mode
DIR: bool, // bit offset: 4 desc: Direction
CMS: u2, // bit offset: 5 desc: Center-aligned mode selection
ARPE: bool, // bit offset: 7 desc: Auto-reload preload enable
CKD: u2, // bit offset: 8 desc: Clock division
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR2 = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 control register 2
reserved0: u3 = 0,
CCDS: bool, // bit offset: 3 desc: Capture/compare DMA selection
MMS: u3, // bit offset: 4 desc: Master mode selection
TI1S: bool, // bit offset: 7 desc: TI1 selection
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SMCR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 slave mode control register
SMS: u3, // bit offset: 0 desc: Slave mode selection
reserved0: u1 = 0,
TS: u3, // bit offset: 4 desc: Trigger selection
MSM: bool, // bit offset: 7 desc: Master/Slave mode
ETF: u4, // bit offset: 8 desc: External trigger filter
ETPS: u2, // bit offset: 12 desc: External trigger prescaler
ECE: bool, // bit offset: 14 desc: External clock enable
ETP: bool, // bit offset: 15 desc: External trigger polarity
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DIER = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 DMA/Interrupt enable register
UIE: bool, // bit offset: 0 desc: Update interrupt enable
CC1IE: bool, // bit offset: 1 desc: Capture/Compare 1 interrupt enable
CC2IE: bool, // bit offset: 2 desc: Capture/Compare 2 interrupt enable
CC3IE: bool, // bit offset: 3 desc: Capture/Compare 3 interrupt enable
CC4IE: bool, // bit offset: 4 desc: Capture/Compare 4 interrupt enable
reserved0: u1 = 0,
TIE: bool, // bit offset: 6 desc: Trigger interrupt enable
reserved1: u1 = 0,
UDE: bool, // bit offset: 8 desc: Update DMA request enable
CC1DE: bool, // bit offset: 9 desc: Capture/Compare 1 DMA request enable
CC2DE: bool, // bit offset: 10 desc: Capture/Compare 2 DMA request enable
CC3DE: bool, // bit offset: 11 desc: Capture/Compare 3 DMA request enable
CC4DE: bool, // bit offset: 12 desc: Capture/Compare 4 DMA request enable
reserved2: u1 = 0,
TDE: bool, // bit offset: 14 desc: Trigger DMA request enable
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 status register
UIF: bool, // bit offset: 0 desc: Update interrupt flag
CC1IF: bool, // bit offset: 1 desc: Capture/compare 1 interrupt flag
CC2IF: bool, // bit offset: 2 desc: Capture/Compare 2 interrupt flag
CC3IF: bool, // bit offset: 3 desc: Capture/Compare 3 interrupt flag
CC4IF: bool, // bit offset: 4 desc: Capture/Compare 4 interrupt flag
reserved0: u1 = 0,
TIF: bool, // bit offset: 6 desc: Trigger interrupt flag
reserved1: u2 = 0,
CC1OF: bool, // bit offset: 9 desc: Capture/Compare 1 overcapture flag
CC2OF: bool, // bit offset: 10 desc: Capture/compare 2 overcapture flag
CC3OF: bool, // bit offset: 11 desc: Capture/Compare 3 overcapture flag
CC4OF: bool, // bit offset: 12 desc: Capture/Compare 4 overcapture flag
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const EGR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 event generation register
UG: bool, // bit offset: 0 desc: Update generation
CC1G: bool, // bit offset: 1 desc: Capture/compare 1 generation
CC2G: bool, // bit offset: 2 desc: Capture/compare 2 generation
CC3G: bool, // bit offset: 3 desc: Capture/compare 3 generation
CC4G: bool, // bit offset: 4 desc: Capture/compare 4 generation
reserved0: u1 = 0,
TG: bool, // bit offset: 6 desc: Trigger generation
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR1_Output = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 capture/compare mode register 1 (output mode)
CC1S: u2, // bit offset: 0 desc: CC1S
OC1FE: bool, // bit offset: 2 desc: OC1FE
OC1PE: bool, // bit offset: 3 desc: OC1PE
OC1M: u3, // bit offset: 4 desc: OC1M
OC1CE: bool, // bit offset: 7 desc: OC1CE
CC2S: u2, // bit offset: 8 desc: CC2S
OC2FE: bool, // bit offset: 10 desc: OC2FE
OC2PE: bool, // bit offset: 11 desc: OC2PE
OC2M: u3, // bit offset: 12 desc: OC2M
OC2CE: bool, // bit offset: 15 desc: OC2CE
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR1_Input = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 capture/compare mode register 1 (input mode)
CC1S: u2, // bit offset: 0 desc: Capture/Compare 1 selection
ICPCS: u2, // bit offset: 2 desc: Input capture 1 prescaler
IC1F: u4, // bit offset: 4 desc: Input capture 1 filter
CC2S: u2, // bit offset: 8 desc: Capture/Compare 2 selection
IC2PCS: u2, // bit offset: 10 desc: Input capture 2 prescaler
IC2F: u4, // bit offset: 12 desc: Input capture 2 filter
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR2_Output = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 capture/compare mode register 2 (output mode)
CC3S: u2, // bit offset: 0 desc: CC3S
OC3FE: bool, // bit offset: 2 desc: OC3FE
OC3PE: bool, // bit offset: 3 desc: OC3PE
OC3M: u3, // bit offset: 4 desc: OC3M
OC3CE: bool, // bit offset: 7 desc: OC3CE
CC4S: u2, // bit offset: 8 desc: CC4S
OC4FE: bool, // bit offset: 10 desc: OC4FE
OC4PE: bool, // bit offset: 11 desc: OC4PE
OC4M: u3, // bit offset: 12 desc: OC4M
O24CE: bool, // bit offset: 15 desc: O24CE
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR2_Input = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 capture/compare mode register 2 (input mode)
CC3S: u2, // bit offset: 0 desc: Capture/compare 3 selection
IC3PSC: u2, // bit offset: 2 desc: Input capture 3 prescaler
IC3F: u4, // bit offset: 4 desc: Input capture 3 filter
CC4S: u2, // bit offset: 8 desc: Capture/Compare 4 selection
IC4PSC: u2, // bit offset: 10 desc: Input capture 4 prescaler
IC4F: u4, // bit offset: 12 desc: Input capture 4 filter
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCER = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 capture/compare enable register
CC1E: bool, // bit offset: 0 desc: Capture/Compare 1 output enable
CC1P: bool, // bit offset: 1 desc: Capture/Compare 1 output Polarity
reserved0: u1 = 0,
CC1NP: bool, // bit offset: 3 desc: Capture/Compare 1 output Polarity
CC2E: bool, // bit offset: 4 desc: Capture/Compare 2 output enable
CC2P: bool, // bit offset: 5 desc: Capture/Compare 2 output Polarity
reserved1: u1 = 0,
CC2NP: bool, // bit offset: 7 desc: Capture/Compare 2 output Polarity
CC3E: bool, // bit offset: 8 desc: Capture/Compare 3 output enable
CC3P: bool, // bit offset: 9 desc: Capture/Compare 3 output Polarity
reserved2: u1 = 0,
CC3NP: bool, // bit offset: 11 desc: Capture/Compare 3 output Polarity
CC4E: bool, // bit offset: 12 desc: Capture/Compare 4 output enable
CC4P: bool, // bit offset: 13 desc: Capture/Compare 3 output Polarity
reserved3: u1 = 0,
CC4NP: bool, // bit offset: 15 desc: Capture/Compare 4 output Polarity
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CNT = MMIO(Address + 0x00000024, u32, packed struct { // byte offset: 36 counter
CNT_L: u16, // bit offset: 0 desc: Low counter value
CNT_H: u16, // bit offset: 16 desc: High counter value
});
pub const PSC = MMIO(Address + 0x00000028, u32, packed struct { // byte offset: 40 prescaler
PSC: u16, // bit offset: 0 desc: Prescaler value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const ARR = MMIO(Address + 0x0000002c, u32, packed struct { // byte offset: 44 auto-reload register
ARR_L: u16, // bit offset: 0 desc: Low Auto-reload value
ARR_H: u16, // bit offset: 16 desc: High Auto-reload value
});
pub const CCR1 = MMIO(Address + 0x00000034, u32, packed struct { // byte offset: 52 capture/compare register 1
CCR1_L: u16, // bit offset: 0 desc: Low Capture/Compare 1 value
CCR1_H: u16, // bit offset: 16 desc: High Capture/Compare 1 value
});
pub const CCR2 = MMIO(Address + 0x00000038, u32, packed struct { // byte offset: 56 capture/compare register 2
CCR2_L: u16, // bit offset: 0 desc: Low Capture/Compare 2 value
CCR2_H: u16, // bit offset: 16 desc: High Capture/Compare 2 value
});
pub const CCR3 = MMIO(Address + 0x0000003c, u32, packed struct { // byte offset: 60 capture/compare register 3
CCR3_L: u16, // bit offset: 0 desc: Low Capture/Compare value
CCR3_H: u16, // bit offset: 16 desc: High Capture/Compare value
});
pub const CCR4 = MMIO(Address + 0x00000040, u32, packed struct { // byte offset: 64 capture/compare register 4
CCR4_L: u16, // bit offset: 0 desc: Low Capture/Compare value
CCR4_H: u16, // bit offset: 16 desc: High Capture/Compare value
});
pub const DCR = MMIO(Address + 0x00000048, u32, packed struct { // byte offset: 72 DMA control register
DBA: u5, // bit offset: 0 desc: DMA base address
reserved0: u3 = 0,
DBL: u5, // bit offset: 8 desc: DMA burst length
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DMAR = MMIO(Address + 0x0000004c, u32, packed struct { // byte offset: 76 DMA address for full transfer
DMAB: u16, // bit offset: 0 desc: DMA register for burst accesses
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const TIM5 = extern struct {
pub const Address: u32 = 0x40000c00;
pub const CR1 = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 control register 1
CEN: bool, // bit offset: 0 desc: Counter enable
UDIS: bool, // bit offset: 1 desc: Update disable
URS: bool, // bit offset: 2 desc: Update request source
OPM: bool, // bit offset: 3 desc: One-pulse mode
DIR: bool, // bit offset: 4 desc: Direction
CMS: u2, // bit offset: 5 desc: Center-aligned mode selection
ARPE: bool, // bit offset: 7 desc: Auto-reload preload enable
CKD: u2, // bit offset: 8 desc: Clock division
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR2 = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 control register 2
reserved0: u3 = 0,
CCDS: bool, // bit offset: 3 desc: Capture/compare DMA selection
MMS: u3, // bit offset: 4 desc: Master mode selection
TI1S: bool, // bit offset: 7 desc: TI1 selection
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SMCR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 slave mode control register
SMS: u3, // bit offset: 0 desc: Slave mode selection
reserved0: u1 = 0,
TS: u3, // bit offset: 4 desc: Trigger selection
MSM: bool, // bit offset: 7 desc: Master/Slave mode
ETF: u4, // bit offset: 8 desc: External trigger filter
ETPS: u2, // bit offset: 12 desc: External trigger prescaler
ECE: bool, // bit offset: 14 desc: External clock enable
ETP: bool, // bit offset: 15 desc: External trigger polarity
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DIER = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 DMA/Interrupt enable register
UIE: bool, // bit offset: 0 desc: Update interrupt enable
CC1IE: bool, // bit offset: 1 desc: Capture/Compare 1 interrupt enable
CC2IE: bool, // bit offset: 2 desc: Capture/Compare 2 interrupt enable
CC3IE: bool, // bit offset: 3 desc: Capture/Compare 3 interrupt enable
CC4IE: bool, // bit offset: 4 desc: Capture/Compare 4 interrupt enable
reserved0: u1 = 0,
TIE: bool, // bit offset: 6 desc: Trigger interrupt enable
reserved1: u1 = 0,
UDE: bool, // bit offset: 8 desc: Update DMA request enable
CC1DE: bool, // bit offset: 9 desc: Capture/Compare 1 DMA request enable
CC2DE: bool, // bit offset: 10 desc: Capture/Compare 2 DMA request enable
CC3DE: bool, // bit offset: 11 desc: Capture/Compare 3 DMA request enable
CC4DE: bool, // bit offset: 12 desc: Capture/Compare 4 DMA request enable
reserved2: u1 = 0,
TDE: bool, // bit offset: 14 desc: Trigger DMA request enable
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 status register
UIF: bool, // bit offset: 0 desc: Update interrupt flag
CC1IF: bool, // bit offset: 1 desc: Capture/compare 1 interrupt flag
CC2IF: bool, // bit offset: 2 desc: Capture/Compare 2 interrupt flag
CC3IF: bool, // bit offset: 3 desc: Capture/Compare 3 interrupt flag
CC4IF: bool, // bit offset: 4 desc: Capture/Compare 4 interrupt flag
reserved0: u1 = 0,
TIF: bool, // bit offset: 6 desc: Trigger interrupt flag
reserved1: u2 = 0,
CC1OF: bool, // bit offset: 9 desc: Capture/Compare 1 overcapture flag
CC2OF: bool, // bit offset: 10 desc: Capture/compare 2 overcapture flag
CC3OF: bool, // bit offset: 11 desc: Capture/Compare 3 overcapture flag
CC4OF: bool, // bit offset: 12 desc: Capture/Compare 4 overcapture flag
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const EGR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 event generation register
UG: bool, // bit offset: 0 desc: Update generation
CC1G: bool, // bit offset: 1 desc: Capture/compare 1 generation
CC2G: bool, // bit offset: 2 desc: Capture/compare 2 generation
CC3G: bool, // bit offset: 3 desc: Capture/compare 3 generation
CC4G: bool, // bit offset: 4 desc: Capture/compare 4 generation
reserved0: u1 = 0,
TG: bool, // bit offset: 6 desc: Trigger generation
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR1_Output = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 capture/compare mode register 1 (output mode)
CC1S: u2, // bit offset: 0 desc: CC1S
OC1FE: bool, // bit offset: 2 desc: OC1FE
OC1PE: bool, // bit offset: 3 desc: OC1PE
OC1M: u3, // bit offset: 4 desc: OC1M
OC1CE: bool, // bit offset: 7 desc: OC1CE
CC2S: u2, // bit offset: 8 desc: CC2S
OC2FE: bool, // bit offset: 10 desc: OC2FE
OC2PE: bool, // bit offset: 11 desc: OC2PE
OC2M: u3, // bit offset: 12 desc: OC2M
OC2CE: bool, // bit offset: 15 desc: OC2CE
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR1_Input = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 capture/compare mode register 1 (input mode)
CC1S: u2, // bit offset: 0 desc: Capture/Compare 1 selection
ICPCS: u2, // bit offset: 2 desc: Input capture 1 prescaler
IC1F: u4, // bit offset: 4 desc: Input capture 1 filter
CC2S: u2, // bit offset: 8 desc: Capture/Compare 2 selection
IC2PCS: u2, // bit offset: 10 desc: Input capture 2 prescaler
IC2F: u4, // bit offset: 12 desc: Input capture 2 filter
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR2_Output = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 capture/compare mode register 2 (output mode)
CC3S: u2, // bit offset: 0 desc: CC3S
OC3FE: bool, // bit offset: 2 desc: OC3FE
OC3PE: bool, // bit offset: 3 desc: OC3PE
OC3M: u3, // bit offset: 4 desc: OC3M
OC3CE: bool, // bit offset: 7 desc: OC3CE
CC4S: u2, // bit offset: 8 desc: CC4S
OC4FE: bool, // bit offset: 10 desc: OC4FE
OC4PE: bool, // bit offset: 11 desc: OC4PE
OC4M: u3, // bit offset: 12 desc: OC4M
O24CE: bool, // bit offset: 15 desc: O24CE
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR2_Input = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 capture/compare mode register 2 (input mode)
CC3S: u2, // bit offset: 0 desc: Capture/compare 3 selection
IC3PSC: u2, // bit offset: 2 desc: Input capture 3 prescaler
IC3F: u4, // bit offset: 4 desc: Input capture 3 filter
CC4S: u2, // bit offset: 8 desc: Capture/Compare 4 selection
IC4PSC: u2, // bit offset: 10 desc: Input capture 4 prescaler
IC4F: u4, // bit offset: 12 desc: Input capture 4 filter
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCER = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 capture/compare enable register
CC1E: bool, // bit offset: 0 desc: Capture/Compare 1 output enable
CC1P: bool, // bit offset: 1 desc: Capture/Compare 1 output Polarity
reserved0: u1 = 0,
CC1NP: bool, // bit offset: 3 desc: Capture/Compare 1 output Polarity
CC2E: bool, // bit offset: 4 desc: Capture/Compare 2 output enable
CC2P: bool, // bit offset: 5 desc: Capture/Compare 2 output Polarity
reserved1: u1 = 0,
CC2NP: bool, // bit offset: 7 desc: Capture/Compare 2 output Polarity
CC3E: bool, // bit offset: 8 desc: Capture/Compare 3 output enable
CC3P: bool, // bit offset: 9 desc: Capture/Compare 3 output Polarity
reserved2: u1 = 0,
CC3NP: bool, // bit offset: 11 desc: Capture/Compare 3 output Polarity
CC4E: bool, // bit offset: 12 desc: Capture/Compare 4 output enable
CC4P: bool, // bit offset: 13 desc: Capture/Compare 3 output Polarity
reserved3: u1 = 0,
CC4NP: bool, // bit offset: 15 desc: Capture/Compare 4 output Polarity
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CNT = MMIO(Address + 0x00000024, u32, packed struct { // byte offset: 36 counter
CNT_L: u16, // bit offset: 0 desc: Low counter value
CNT_H: u16, // bit offset: 16 desc: High counter value
});
pub const PSC = MMIO(Address + 0x00000028, u32, packed struct { // byte offset: 40 prescaler
PSC: u16, // bit offset: 0 desc: Prescaler value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const ARR = MMIO(Address + 0x0000002c, u32, packed struct { // byte offset: 44 auto-reload register
ARR_L: u16, // bit offset: 0 desc: Low Auto-reload value
ARR_H: u16, // bit offset: 16 desc: High Auto-reload value
});
pub const CCR1 = MMIO(Address + 0x00000034, u32, packed struct { // byte offset: 52 capture/compare register 1
CCR1_L: u16, // bit offset: 0 desc: Low Capture/Compare 1 value
CCR1_H: u16, // bit offset: 16 desc: High Capture/Compare 1 value
});
pub const CCR2 = MMIO(Address + 0x00000038, u32, packed struct { // byte offset: 56 capture/compare register 2
CCR2_L: u16, // bit offset: 0 desc: Low Capture/Compare 2 value
CCR2_H: u16, // bit offset: 16 desc: High Capture/Compare 2 value
});
pub const CCR3 = MMIO(Address + 0x0000003c, u32, packed struct { // byte offset: 60 capture/compare register 3
CCR3_L: u16, // bit offset: 0 desc: Low Capture/Compare value
CCR3_H: u16, // bit offset: 16 desc: High Capture/Compare value
});
pub const CCR4 = MMIO(Address + 0x00000040, u32, packed struct { // byte offset: 64 capture/compare register 4
CCR4_L: u16, // bit offset: 0 desc: Low Capture/Compare value
CCR4_H: u16, // bit offset: 16 desc: High Capture/Compare value
});
pub const DCR = MMIO(Address + 0x00000048, u32, packed struct { // byte offset: 72 DMA control register
DBA: u5, // bit offset: 0 desc: DMA base address
reserved0: u3 = 0,
DBL: u5, // bit offset: 8 desc: DMA burst length
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DMAR = MMIO(Address + 0x0000004c, u32, packed struct { // byte offset: 76 DMA address for full transfer
DMAB: u16, // bit offset: 0 desc: DMA register for burst accesses
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const OR = MMIO(Address + 0x00000050, u32, packed struct { // byte offset: 80 TIM5 option register
reserved0: u6 = 0,
IT4_RMP: u2, // bit offset: 6 desc: Timer Input 4 remap
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const TIM9 = extern struct {
pub const Address: u32 = 0x40014000;
pub const CR1 = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 control register 1
CEN: bool, // bit offset: 0 desc: Counter enable
UDIS: bool, // bit offset: 1 desc: Update disable
URS: bool, // bit offset: 2 desc: Update request source
OPM: bool, // bit offset: 3 desc: One-pulse mode
reserved0: u3 = 0,
ARPE: bool, // bit offset: 7 desc: Auto-reload preload enable
CKD: u2, // bit offset: 8 desc: Clock division
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR2 = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 control register 2
reserved0: u4 = 0,
MMS: u3, // bit offset: 4 desc: Master mode selection
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SMCR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 slave mode control register
SMS: u3, // bit offset: 0 desc: Slave mode selection
reserved0: u1 = 0,
TS: u3, // bit offset: 4 desc: Trigger selection
MSM: bool, // bit offset: 7 desc: Master/Slave mode
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DIER = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 DMA/Interrupt enable register
UIE: bool, // bit offset: 0 desc: Update interrupt enable
CC1IE: bool, // bit offset: 1 desc: Capture/Compare 1 interrupt enable
CC2IE: bool, // bit offset: 2 desc: Capture/Compare 2 interrupt enable
reserved0: u3 = 0,
TIE: bool, // bit offset: 6 desc: Trigger interrupt enable
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 status register
UIF: bool, // bit offset: 0 desc: Update interrupt flag
CC1IF: bool, // bit offset: 1 desc: Capture/compare 1 interrupt flag
CC2IF: bool, // bit offset: 2 desc: Capture/Compare 2 interrupt flag
reserved0: u3 = 0,
TIF: bool, // bit offset: 6 desc: Trigger interrupt flag
reserved1: u2 = 0,
CC1OF: bool, // bit offset: 9 desc: Capture/Compare 1 overcapture flag
CC2OF: bool, // bit offset: 10 desc: Capture/compare 2 overcapture flag
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const EGR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 event generation register
UG: bool, // bit offset: 0 desc: Update generation
CC1G: bool, // bit offset: 1 desc: Capture/compare 1 generation
CC2G: bool, // bit offset: 2 desc: Capture/compare 2 generation
reserved0: u3 = 0,
TG: bool, // bit offset: 6 desc: Trigger generation
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR1_Output = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 capture/compare mode register 1 (output mode)
CC1S: u2, // bit offset: 0 desc: Capture/Compare 1 selection
OC1FE: bool, // bit offset: 2 desc: Output Compare 1 fast enable
OC1PE: bool, // bit offset: 3 desc: Output Compare 1 preload enable
OC1M: u3, // bit offset: 4 desc: Output Compare 1 mode
reserved0: u1 = 0,
CC2S: u2, // bit offset: 8 desc: Capture/Compare 2 selection
OC2FE: bool, // bit offset: 10 desc: Output Compare 2 fast enable
OC2PE: bool, // bit offset: 11 desc: Output Compare 2 preload enable
OC2M: u3, // bit offset: 12 desc: Output Compare 2 mode
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCMR1_Input = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 capture/compare mode register 1 (input mode)
CC1S: u2, // bit offset: 0 desc: Capture/Compare 1 selection
ICPCS: u2, // bit offset: 2 desc: Input capture 1 prescaler
IC1F: u3, // bit offset: 4 desc: Input capture 1 filter
reserved0: u1 = 0,
CC2S: u2, // bit offset: 8 desc: Capture/Compare 2 selection
IC2PCS: u2, // bit offset: 10 desc: Input capture 2 prescaler
IC2F: u3, // bit offset: 12 desc: Input capture 2 filter
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCER = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 capture/compare enable register
CC1E: bool, // bit offset: 0 desc: Capture/Compare 1 output enable
CC1P: bool, // bit offset: 1 desc: Capture/Compare 1 output Polarity
reserved0: u1 = 0,
CC1NP: bool, // bit offset: 3 desc: Capture/Compare 1 output Polarity
CC2E: bool, // bit offset: 4 desc: Capture/Compare 2 output enable
CC2P: bool, // bit offset: 5 desc: Capture/Compare 2 output Polarity
reserved1: u1 = 0,
CC2NP: bool, // bit offset: 7 desc: Capture/Compare 2 output Polarity
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CNT = MMIO(Address + 0x00000024, u32, packed struct { // byte offset: 36 counter
CNT: u16, // bit offset: 0 desc: counter value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const PSC = MMIO(Address + 0x00000028, u32, packed struct { // byte offset: 40 prescaler
PSC: u16, // bit offset: 0 desc: Prescaler value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const ARR = MMIO(Address + 0x0000002c, u32, packed struct { // byte offset: 44 auto-reload register
ARR: u16, // bit offset: 0 desc: Auto-reload value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCR1 = MMIO(Address + 0x00000034, u32, packed struct { // byte offset: 52 capture/compare register 1
CCR1: u16, // bit offset: 0 desc: Capture/Compare 1 value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCR2 = MMIO(Address + 0x00000038, u32, packed struct { // byte offset: 56 capture/compare register 2
CCR2: u16, // bit offset: 0 desc: Capture/Compare 2 value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const USART1 = extern struct {
pub const Address: u32 = 0x40011000;
pub const SR = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 Status register
PE: bool, // bit offset: 0 desc: Parity error
FE: bool, // bit offset: 1 desc: Framing error
NF: bool, // bit offset: 2 desc: Noise detected flag
ORE: bool, // bit offset: 3 desc: Overrun error
IDLE: bool, // bit offset: 4 desc: IDLE line detected
RXNE: bool, // bit offset: 5 desc: Read data register not empty
TC: bool, // bit offset: 6 desc: Transmission complete
TXE: bool, // bit offset: 7 desc: Transmit data register empty
LBD: bool, // bit offset: 8 desc: LIN break detection flag
CTS: bool, // bit offset: 9 desc: CTS flag
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DR = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 Data register
DR: u9, // bit offset: 0 desc: Data value
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const BRR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 Baud rate register
DIV_Fraction: u4, // bit offset: 0 desc: fraction of USARTDIV
DIV_Mantissa: u12, // bit offset: 4 desc: mantissa of USARTDIV
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR1 = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 Control register 1
SBK: bool, // bit offset: 0 desc: Send break
RWU: bool, // bit offset: 1 desc: Receiver wakeup
RE: bool, // bit offset: 2 desc: Receiver enable
TE: bool, // bit offset: 3 desc: Transmitter enable
IDLEIE: bool, // bit offset: 4 desc: IDLE interrupt enable
RXNEIE: bool, // bit offset: 5 desc: RXNE interrupt enable
TCIE: bool, // bit offset: 6 desc: Transmission complete interrupt enable
TXEIE: bool, // bit offset: 7 desc: TXE interrupt enable
PEIE: bool, // bit offset: 8 desc: PE interrupt enable
PS: bool, // bit offset: 9 desc: Parity selection
PCE: bool, // bit offset: 10 desc: Parity control enable
WAKE: bool, // bit offset: 11 desc: Wakeup method
M: bool, // bit offset: 12 desc: Word length
UE: bool, // bit offset: 13 desc: USART enable
reserved0: u1 = 0,
OVER8: bool, // bit offset: 15 desc: Oversampling mode
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR2 = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 Control register 2
ADD: u4, // bit offset: 0 desc: Address of the USART node
reserved0: u1 = 0,
LBDL: bool, // bit offset: 5 desc: lin break detection length
LBDIE: bool, // bit offset: 6 desc: LIN break detection interrupt enable
reserved1: u1 = 0,
LBCL: bool, // bit offset: 8 desc: Last bit clock pulse
CPHA: bool, // bit offset: 9 desc: Clock phase
CPOL: bool, // bit offset: 10 desc: Clock polarity
CLKEN: bool, // bit offset: 11 desc: Clock enable
STOP: u2, // bit offset: 12 desc: STOP bits
LINEN: bool, // bit offset: 14 desc: LIN mode enable
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR3 = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 Control register 3
EIE: bool, // bit offset: 0 desc: Error interrupt enable
IREN: bool, // bit offset: 1 desc: IrDA mode enable
IRLP: bool, // bit offset: 2 desc: IrDA low-power
HDSEL: bool, // bit offset: 3 desc: Half-duplex selection
NACK: bool, // bit offset: 4 desc: Smartcard NACK enable
SCEN: bool, // bit offset: 5 desc: Smartcard mode enable
DMAR: bool, // bit offset: 6 desc: DMA enable receiver
DMAT: bool, // bit offset: 7 desc: DMA enable transmitter
RTSE: bool, // bit offset: 8 desc: RTS enable
CTSE: bool, // bit offset: 9 desc: CTS enable
CTSIE: bool, // bit offset: 10 desc: CTS interrupt enable
ONEBIT: bool, // bit offset: 11 desc: One sample bit method enable
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const GTPR = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 Guard time and prescaler register
PSC: u8, // bit offset: 0 desc: Prescaler value
GT: u8, // bit offset: 8 desc: Guard time value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const USART2 = extern struct {
pub const Address: u32 = 0x40004400;
pub const SR = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 Status register
PE: bool, // bit offset: 0 desc: Parity error
FE: bool, // bit offset: 1 desc: Framing error
NF: bool, // bit offset: 2 desc: Noise detected flag
ORE: bool, // bit offset: 3 desc: Overrun error
IDLE: bool, // bit offset: 4 desc: IDLE line detected
RXNE: bool, // bit offset: 5 desc: Read data register not empty
TC: bool, // bit offset: 6 desc: Transmission complete
TXE: bool, // bit offset: 7 desc: Transmit data register empty
LBD: bool, // bit offset: 8 desc: LIN break detection flag
CTS: bool, // bit offset: 9 desc: CTS flag
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DR = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 Data register
DR: u9, // bit offset: 0 desc: Data value
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const BRR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 Baud rate register
DIV_Fraction: u4, // bit offset: 0 desc: fraction of USARTDIV
DIV_Mantissa: u12, // bit offset: 4 desc: mantissa of USARTDIV
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR1 = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 Control register 1
SBK: bool, // bit offset: 0 desc: Send break
RWU: bool, // bit offset: 1 desc: Receiver wakeup
RE: bool, // bit offset: 2 desc: Receiver enable
TE: bool, // bit offset: 3 desc: Transmitter enable
IDLEIE: bool, // bit offset: 4 desc: IDLE interrupt enable
RXNEIE: bool, // bit offset: 5 desc: RXNE interrupt enable
TCIE: bool, // bit offset: 6 desc: Transmission complete interrupt enable
TXEIE: bool, // bit offset: 7 desc: TXE interrupt enable
PEIE: bool, // bit offset: 8 desc: PE interrupt enable
PS: bool, // bit offset: 9 desc: Parity selection
PCE: bool, // bit offset: 10 desc: Parity control enable
WAKE: bool, // bit offset: 11 desc: Wakeup method
M: bool, // bit offset: 12 desc: Word length
UE: bool, // bit offset: 13 desc: USART enable
reserved0: u1 = 0,
OVER8: bool, // bit offset: 15 desc: Oversampling mode
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR2 = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 Control register 2
ADD: u4, // bit offset: 0 desc: Address of the USART node
reserved0: u1 = 0,
LBDL: bool, // bit offset: 5 desc: lin break detection length
LBDIE: bool, // bit offset: 6 desc: LIN break detection interrupt enable
reserved1: u1 = 0,
LBCL: bool, // bit offset: 8 desc: Last bit clock pulse
CPHA: bool, // bit offset: 9 desc: Clock phase
CPOL: bool, // bit offset: 10 desc: Clock polarity
CLKEN: bool, // bit offset: 11 desc: Clock enable
STOP: u2, // bit offset: 12 desc: STOP bits
LINEN: bool, // bit offset: 14 desc: LIN mode enable
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR3 = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 Control register 3
EIE: bool, // bit offset: 0 desc: Error interrupt enable
IREN: bool, // bit offset: 1 desc: IrDA mode enable
IRLP: bool, // bit offset: 2 desc: IrDA low-power
HDSEL: bool, // bit offset: 3 desc: Half-duplex selection
NACK: bool, // bit offset: 4 desc: Smartcard NACK enable
SCEN: bool, // bit offset: 5 desc: Smartcard mode enable
DMAR: bool, // bit offset: 6 desc: DMA enable receiver
DMAT: bool, // bit offset: 7 desc: DMA enable transmitter
RTSE: bool, // bit offset: 8 desc: RTS enable
CTSE: bool, // bit offset: 9 desc: CTS enable
CTSIE: bool, // bit offset: 10 desc: CTS interrupt enable
ONEBIT: bool, // bit offset: 11 desc: One sample bit method enable
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const GTPR = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 Guard time and prescaler register
PSC: u8, // bit offset: 0 desc: Prescaler value
GT: u8, // bit offset: 8 desc: Guard time value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const USART6 = extern struct {
pub const Address: u32 = 0x40011400;
pub const SR = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 Status register
PE: bool, // bit offset: 0 desc: Parity error
FE: bool, // bit offset: 1 desc: Framing error
NF: bool, // bit offset: 2 desc: Noise detected flag
ORE: bool, // bit offset: 3 desc: Overrun error
IDLE: bool, // bit offset: 4 desc: IDLE line detected
RXNE: bool, // bit offset: 5 desc: Read data register not empty
TC: bool, // bit offset: 6 desc: Transmission complete
TXE: bool, // bit offset: 7 desc: Transmit data register empty
LBD: bool, // bit offset: 8 desc: LIN break detection flag
CTS: bool, // bit offset: 9 desc: CTS flag
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DR = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 Data register
DR: u9, // bit offset: 0 desc: Data value
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const BRR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 Baud rate register
DIV_Fraction: u4, // bit offset: 0 desc: fraction of USARTDIV
DIV_Mantissa: u12, // bit offset: 4 desc: mantissa of USARTDIV
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR1 = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 Control register 1
SBK: bool, // bit offset: 0 desc: Send break
RWU: bool, // bit offset: 1 desc: Receiver wakeup
RE: bool, // bit offset: 2 desc: Receiver enable
TE: bool, // bit offset: 3 desc: Transmitter enable
IDLEIE: bool, // bit offset: 4 desc: IDLE interrupt enable
RXNEIE: bool, // bit offset: 5 desc: RXNE interrupt enable
TCIE: bool, // bit offset: 6 desc: Transmission complete interrupt enable
TXEIE: bool, // bit offset: 7 desc: TXE interrupt enable
PEIE: bool, // bit offset: 8 desc: PE interrupt enable
PS: bool, // bit offset: 9 desc: Parity selection
PCE: bool, // bit offset: 10 desc: Parity control enable
WAKE: bool, // bit offset: 11 desc: Wakeup method
M: bool, // bit offset: 12 desc: Word length
UE: bool, // bit offset: 13 desc: USART enable
reserved0: u1 = 0,
OVER8: bool, // bit offset: 15 desc: Oversampling mode
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR2 = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 Control register 2
ADD: u4, // bit offset: 0 desc: Address of the USART node
reserved0: u1 = 0,
LBDL: bool, // bit offset: 5 desc: lin break detection length
LBDIE: bool, // bit offset: 6 desc: LIN break detection interrupt enable
reserved1: u1 = 0,
LBCL: bool, // bit offset: 8 desc: Last bit clock pulse
CPHA: bool, // bit offset: 9 desc: Clock phase
CPOL: bool, // bit offset: 10 desc: Clock polarity
CLKEN: bool, // bit offset: 11 desc: Clock enable
STOP: u2, // bit offset: 12 desc: STOP bits
LINEN: bool, // bit offset: 14 desc: LIN mode enable
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR3 = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 Control register 3
EIE: bool, // bit offset: 0 desc: Error interrupt enable
IREN: bool, // bit offset: 1 desc: IrDA mode enable
IRLP: bool, // bit offset: 2 desc: IrDA low-power
HDSEL: bool, // bit offset: 3 desc: Half-duplex selection
NACK: bool, // bit offset: 4 desc: Smartcard NACK enable
SCEN: bool, // bit offset: 5 desc: Smartcard mode enable
DMAR: bool, // bit offset: 6 desc: DMA enable receiver
DMAT: bool, // bit offset: 7 desc: DMA enable transmitter
RTSE: bool, // bit offset: 8 desc: RTS enable
CTSE: bool, // bit offset: 9 desc: CTS enable
CTSIE: bool, // bit offset: 10 desc: CTS interrupt enable
ONEBIT: bool, // bit offset: 11 desc: One sample bit method enable
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const GTPR = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 Guard time and prescaler register
PSC: u8, // bit offset: 0 desc: Prescaler value
GT: u8, // bit offset: 8 desc: Guard time value
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const WWDG = extern struct {
pub const Address: u32 = 0x40002c00;
pub const CR = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 Control register
T: u7, // bit offset: 0 desc: 7-bit counter (MSB to LSB)
WDGA: bool, // bit offset: 7 desc: Activation bit
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CFR = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 Configuration register
W: u7, // bit offset: 0 desc: 7-bit window value
WDGTB0: bool, // bit offset: 7 desc: Timer base
WDGTB1: bool, // bit offset: 8 desc: Timer base
EWI: bool, // bit offset: 9 desc: Early wakeup interrupt
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 Status register
EWIF: bool, // bit offset: 0 desc: Early wakeup interrupt flag
padding31: u1 = 0,
padding30: u1 = 0,
padding29: u1 = 0,
padding28: u1 = 0,
padding27: u1 = 0,
padding26: u1 = 0,
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const DMA2 = extern struct {
pub const Address: u32 = 0x40026400;
pub const LISR = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 low interrupt status register
FEIF0: bool, // bit offset: 0 desc: Stream x FIFO error interrupt flag (x=3..0)
reserved0: u1 = 0,
DMEIF0: bool, // bit offset: 2 desc: Stream x direct mode error interrupt flag (x=3..0)
TEIF0: bool, // bit offset: 3 desc: Stream x transfer error interrupt flag (x=3..0)
HTIF0: bool, // bit offset: 4 desc: Stream x half transfer interrupt flag (x=3..0)
TCIF0: bool, // bit offset: 5 desc: Stream x transfer complete interrupt flag (x = 3..0)
FEIF1: bool, // bit offset: 6 desc: Stream x FIFO error interrupt flag (x=3..0)
reserved1: u1 = 0,
DMEIF1: bool, // bit offset: 8 desc: Stream x direct mode error interrupt flag (x=3..0)
TEIF1: bool, // bit offset: 9 desc: Stream x transfer error interrupt flag (x=3..0)
HTIF1: bool, // bit offset: 10 desc: Stream x half transfer interrupt flag (x=3..0)
TCIF1: bool, // bit offset: 11 desc: Stream x transfer complete interrupt flag (x = 3..0)
reserved2: u4 = 0,
FEIF2: bool, // bit offset: 16 desc: Stream x FIFO error interrupt flag (x=3..0)
reserved3: u1 = 0,
DMEIF2: bool, // bit offset: 18 desc: Stream x direct mode error interrupt flag (x=3..0)
TEIF2: bool, // bit offset: 19 desc: Stream x transfer error interrupt flag (x=3..0)
HTIF2: bool, // bit offset: 20 desc: Stream x half transfer interrupt flag (x=3..0)
TCIF2: bool, // bit offset: 21 desc: Stream x transfer complete interrupt flag (x = 3..0)
FEIF3: bool, // bit offset: 22 desc: Stream x FIFO error interrupt flag (x=3..0)
reserved4: u1 = 0,
DMEIF3: bool, // bit offset: 24 desc: Stream x direct mode error interrupt flag (x=3..0)
TEIF3: bool, // bit offset: 25 desc: Stream x transfer error interrupt flag (x=3..0)
HTIF3: bool, // bit offset: 26 desc: Stream x half transfer interrupt flag (x=3..0)
TCIF3: bool, // bit offset: 27 desc: Stream x transfer complete interrupt flag (x = 3..0)
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const HISR = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 high interrupt status register
FEIF4: bool, // bit offset: 0 desc: Stream x FIFO error interrupt flag (x=7..4)
reserved0: u1 = 0,
DMEIF4: bool, // bit offset: 2 desc: Stream x direct mode error interrupt flag (x=7..4)
TEIF4: bool, // bit offset: 3 desc: Stream x transfer error interrupt flag (x=7..4)
HTIF4: bool, // bit offset: 4 desc: Stream x half transfer interrupt flag (x=7..4)
TCIF4: bool, // bit offset: 5 desc: Stream x transfer complete interrupt flag (x=7..4)
FEIF5: bool, // bit offset: 6 desc: Stream x FIFO error interrupt flag (x=7..4)
reserved1: u1 = 0,
DMEIF5: bool, // bit offset: 8 desc: Stream x direct mode error interrupt flag (x=7..4)
TEIF5: bool, // bit offset: 9 desc: Stream x transfer error interrupt flag (x=7..4)
HTIF5: bool, // bit offset: 10 desc: Stream x half transfer interrupt flag (x=7..4)
TCIF5: bool, // bit offset: 11 desc: Stream x transfer complete interrupt flag (x=7..4)
reserved2: u4 = 0,
FEIF6: bool, // bit offset: 16 desc: Stream x FIFO error interrupt flag (x=7..4)
reserved3: u1 = 0,
DMEIF6: bool, // bit offset: 18 desc: Stream x direct mode error interrupt flag (x=7..4)
TEIF6: bool, // bit offset: 19 desc: Stream x transfer error interrupt flag (x=7..4)
HTIF6: bool, // bit offset: 20 desc: Stream x half transfer interrupt flag (x=7..4)
TCIF6: bool, // bit offset: 21 desc: Stream x transfer complete interrupt flag (x=7..4)
FEIF7: bool, // bit offset: 22 desc: Stream x FIFO error interrupt flag (x=7..4)
reserved4: u1 = 0,
DMEIF7: bool, // bit offset: 24 desc: Stream x direct mode error interrupt flag (x=7..4)
TEIF7: bool, // bit offset: 25 desc: Stream x transfer error interrupt flag (x=7..4)
HTIF7: bool, // bit offset: 26 desc: Stream x half transfer interrupt flag (x=7..4)
TCIF7: bool, // bit offset: 27 desc: Stream x transfer complete interrupt flag (x=7..4)
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const LIFCR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 low interrupt flag clear register
CFEIF0: bool, // bit offset: 0 desc: Stream x clear FIFO error interrupt flag (x = 3..0)
reserved0: u1 = 0,
CDMEIF0: bool, // bit offset: 2 desc: Stream x clear direct mode error interrupt flag (x = 3..0)
CTEIF0: bool, // bit offset: 3 desc: Stream x clear transfer error interrupt flag (x = 3..0)
CHTIF0: bool, // bit offset: 4 desc: Stream x clear half transfer interrupt flag (x = 3..0)
CTCIF0: bool, // bit offset: 5 desc: Stream x clear transfer complete interrupt flag (x = 3..0)
CFEIF1: bool, // bit offset: 6 desc: Stream x clear FIFO error interrupt flag (x = 3..0)
reserved1: u1 = 0,
CDMEIF1: bool, // bit offset: 8 desc: Stream x clear direct mode error interrupt flag (x = 3..0)
CTEIF1: bool, // bit offset: 9 desc: Stream x clear transfer error interrupt flag (x = 3..0)
CHTIF1: bool, // bit offset: 10 desc: Stream x clear half transfer interrupt flag (x = 3..0)
CTCIF1: bool, // bit offset: 11 desc: Stream x clear transfer complete interrupt flag (x = 3..0)
reserved2: u4 = 0,
CFEIF2: bool, // bit offset: 16 desc: Stream x clear FIFO error interrupt flag (x = 3..0)
reserved3: u1 = 0,
CDMEIF2: bool, // bit offset: 18 desc: Stream x clear direct mode error interrupt flag (x = 3..0)
CTEIF2: bool, // bit offset: 19 desc: Stream x clear transfer error interrupt flag (x = 3..0)
CHTIF2: bool, // bit offset: 20 desc: Stream x clear half transfer interrupt flag (x = 3..0)
CTCIF2: bool, // bit offset: 21 desc: Stream x clear transfer complete interrupt flag (x = 3..0)
CFEIF3: bool, // bit offset: 22 desc: Stream x clear FIFO error interrupt flag (x = 3..0)
reserved4: u1 = 0,
CDMEIF3: bool, // bit offset: 24 desc: Stream x clear direct mode error interrupt flag (x = 3..0)
CTEIF3: bool, // bit offset: 25 desc: Stream x clear transfer error interrupt flag (x = 3..0)
CHTIF3: bool, // bit offset: 26 desc: Stream x clear half transfer interrupt flag (x = 3..0)
CTCIF3: bool, // bit offset: 27 desc: Stream x clear transfer complete interrupt flag (x = 3..0)
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const HIFCR = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 high interrupt flag clear register
CFEIF4: bool, // bit offset: 0 desc: Stream x clear FIFO error interrupt flag (x = 7..4)
reserved0: u1 = 0,
CDMEIF4: bool, // bit offset: 2 desc: Stream x clear direct mode error interrupt flag (x = 7..4)
CTEIF4: bool, // bit offset: 3 desc: Stream x clear transfer error interrupt flag (x = 7..4)
CHTIF4: bool, // bit offset: 4 desc: Stream x clear half transfer interrupt flag (x = 7..4)
CTCIF4: bool, // bit offset: 5 desc: Stream x clear transfer complete interrupt flag (x = 7..4)
CFEIF5: bool, // bit offset: 6 desc: Stream x clear FIFO error interrupt flag (x = 7..4)
reserved1: u1 = 0,
CDMEIF5: bool, // bit offset: 8 desc: Stream x clear direct mode error interrupt flag (x = 7..4)
CTEIF5: bool, // bit offset: 9 desc: Stream x clear transfer error interrupt flag (x = 7..4)
CHTIF5: bool, // bit offset: 10 desc: Stream x clear half transfer interrupt flag (x = 7..4)
CTCIF5: bool, // bit offset: 11 desc: Stream x clear transfer complete interrupt flag (x = 7..4)
reserved2: u4 = 0,
CFEIF6: bool, // bit offset: 16 desc: Stream x clear FIFO error interrupt flag (x = 7..4)
reserved3: u1 = 0,
CDMEIF6: bool, // bit offset: 18 desc: Stream x clear direct mode error interrupt flag (x = 7..4)
CTEIF6: bool, // bit offset: 19 desc: Stream x clear transfer error interrupt flag (x = 7..4)
CHTIF6: bool, // bit offset: 20 desc: Stream x clear half transfer interrupt flag (x = 7..4)
CTCIF6: bool, // bit offset: 21 desc: Stream x clear transfer complete interrupt flag (x = 7..4)
CFEIF7: bool, // bit offset: 22 desc: Stream x clear FIFO error interrupt flag (x = 7..4)
reserved4: u1 = 0,
CDMEIF7: bool, // bit offset: 24 desc: Stream x clear direct mode error interrupt flag (x = 7..4)
CTEIF7: bool, // bit offset: 25 desc: Stream x clear transfer error interrupt flag (x = 7..4)
CHTIF7: bool, // bit offset: 26 desc: Stream x clear half transfer interrupt flag (x = 7..4)
CTCIF7: bool, // bit offset: 27 desc: Stream x clear transfer complete interrupt flag (x = 7..4)
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S0CR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 stream x configuration register
EN: bool, // bit offset: 0 desc: Stream enable / flag stream ready when read low
DMEIE: bool, // bit offset: 1 desc: Direct mode error interrupt enable
TEIE: bool, // bit offset: 2 desc: Transfer error interrupt enable
HTIE: bool, // bit offset: 3 desc: Half transfer interrupt enable
TCIE: bool, // bit offset: 4 desc: Transfer complete interrupt enable
PFCTRL: bool, // bit offset: 5 desc: Peripheral flow controller
DIR: u2, // bit offset: 6 desc: Data transfer direction
CIRC: bool, // bit offset: 8 desc: Circular mode
PINC: bool, // bit offset: 9 desc: Peripheral increment mode
MINC: bool, // bit offset: 10 desc: Memory increment mode
PSIZE: u2, // bit offset: 11 desc: Peripheral data size
MSIZE: u2, // bit offset: 13 desc: Memory data size
PINCOS: bool, // bit offset: 15 desc: Peripheral increment offset size
PL: u2, // bit offset: 16 desc: Priority level
DBM: bool, // bit offset: 18 desc: Double buffer mode
CT: bool, // bit offset: 19 desc: Current target (only in double buffer mode)
reserved0: u1 = 0,
PBURST: u2, // bit offset: 21 desc: Peripheral burst transfer configuration
MBURST: u2, // bit offset: 23 desc: Memory burst transfer configuration
CHSEL: u3, // bit offset: 25 desc: Channel selection
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S0NDTR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 stream x number of data register
NDT: u16, // bit offset: 0 desc: Number of data items to transfer
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S0PAR = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 stream x peripheral address register
PA: u32, // bit offset: 0 desc: Peripheral address
});
pub const S0M0AR = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 stream x memory 0 address register
M0A: u32, // bit offset: 0 desc: Memory 0 address
});
pub const S0M1AR = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 stream x memory 1 address register
M1A: u32, // bit offset: 0 desc: Memory 1 address (used in case of Double buffer mode)
});
pub const S0FCR = MMIO(Address + 0x00000024, u32, packed struct { // byte offset: 36 stream x FIFO control register
FTH: u2, // bit offset: 0 desc: FIFO threshold selection
DMDIS: bool, // bit offset: 2 desc: Direct mode disable
FS: u3, // bit offset: 3 desc: FIFO status
reserved0: u1 = 0,
FEIE: bool, // bit offset: 7 desc: FIFO error interrupt enable
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S1CR = MMIO(Address + 0x00000028, u32, packed struct { // byte offset: 40 stream x configuration register
EN: bool, // bit offset: 0 desc: Stream enable / flag stream ready when read low
DMEIE: bool, // bit offset: 1 desc: Direct mode error interrupt enable
TEIE: bool, // bit offset: 2 desc: Transfer error interrupt enable
HTIE: bool, // bit offset: 3 desc: Half transfer interrupt enable
TCIE: bool, // bit offset: 4 desc: Transfer complete interrupt enable
PFCTRL: bool, // bit offset: 5 desc: Peripheral flow controller
DIR: u2, // bit offset: 6 desc: Data transfer direction
CIRC: bool, // bit offset: 8 desc: Circular mode
PINC: bool, // bit offset: 9 desc: Peripheral increment mode
MINC: bool, // bit offset: 10 desc: Memory increment mode
PSIZE: u2, // bit offset: 11 desc: Peripheral data size
MSIZE: u2, // bit offset: 13 desc: Memory data size
PINCOS: bool, // bit offset: 15 desc: Peripheral increment offset size
PL: u2, // bit offset: 16 desc: Priority level
DBM: bool, // bit offset: 18 desc: Double buffer mode
CT: bool, // bit offset: 19 desc: Current target (only in double buffer mode)
ACK: bool, // bit offset: 20 desc: ACK
PBURST: u2, // bit offset: 21 desc: Peripheral burst transfer configuration
MBURST: u2, // bit offset: 23 desc: Memory burst transfer configuration
CHSEL: u3, // bit offset: 25 desc: Channel selection
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S1NDTR = MMIO(Address + 0x0000002c, u32, packed struct { // byte offset: 44 stream x number of data register
NDT: u16, // bit offset: 0 desc: Number of data items to transfer
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S1PAR = MMIO(Address + 0x00000030, u32, packed struct { // byte offset: 48 stream x peripheral address register
PA: u32, // bit offset: 0 desc: Peripheral address
});
pub const S1M0AR = MMIO(Address + 0x00000034, u32, packed struct { // byte offset: 52 stream x memory 0 address register
M0A: u32, // bit offset: 0 desc: Memory 0 address
});
pub const S1M1AR = MMIO(Address + 0x00000038, u32, packed struct { // byte offset: 56 stream x memory 1 address register
M1A: u32, // bit offset: 0 desc: Memory 1 address (used in case of Double buffer mode)
});
pub const S1FCR = MMIO(Address + 0x0000003c, u32, packed struct { // byte offset: 60 stream x FIFO control register
FTH: u2, // bit offset: 0 desc: FIFO threshold selection
DMDIS: bool, // bit offset: 2 desc: Direct mode disable
FS: u3, // bit offset: 3 desc: FIFO status
reserved0: u1 = 0,
FEIE: bool, // bit offset: 7 desc: FIFO error interrupt enable
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S2CR = MMIO(Address + 0x00000040, u32, packed struct { // byte offset: 64 stream x configuration register
EN: bool, // bit offset: 0 desc: Stream enable / flag stream ready when read low
DMEIE: bool, // bit offset: 1 desc: Direct mode error interrupt enable
TEIE: bool, // bit offset: 2 desc: Transfer error interrupt enable
HTIE: bool, // bit offset: 3 desc: Half transfer interrupt enable
TCIE: bool, // bit offset: 4 desc: Transfer complete interrupt enable
PFCTRL: bool, // bit offset: 5 desc: Peripheral flow controller
DIR: u2, // bit offset: 6 desc: Data transfer direction
CIRC: bool, // bit offset: 8 desc: Circular mode
PINC: bool, // bit offset: 9 desc: Peripheral increment mode
MINC: bool, // bit offset: 10 desc: Memory increment mode
PSIZE: u2, // bit offset: 11 desc: Peripheral data size
MSIZE: u2, // bit offset: 13 desc: Memory data size
PINCOS: bool, // bit offset: 15 desc: Peripheral increment offset size
PL: u2, // bit offset: 16 desc: Priority level
DBM: bool, // bit offset: 18 desc: Double buffer mode
CT: bool, // bit offset: 19 desc: Current target (only in double buffer mode)
ACK: bool, // bit offset: 20 desc: ACK
PBURST: u2, // bit offset: 21 desc: Peripheral burst transfer configuration
MBURST: u2, // bit offset: 23 desc: Memory burst transfer configuration
CHSEL: u3, // bit offset: 25 desc: Channel selection
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S2NDTR = MMIO(Address + 0x00000044, u32, packed struct { // byte offset: 68 stream x number of data register
NDT: u16, // bit offset: 0 desc: Number of data items to transfer
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S2PAR = MMIO(Address + 0x00000048, u32, packed struct { // byte offset: 72 stream x peripheral address register
PA: u32, // bit offset: 0 desc: Peripheral address
});
pub const S2M0AR = MMIO(Address + 0x0000004c, u32, packed struct { // byte offset: 76 stream x memory 0 address register
M0A: u32, // bit offset: 0 desc: Memory 0 address
});
pub const S2M1AR = MMIO(Address + 0x00000050, u32, packed struct { // byte offset: 80 stream x memory 1 address register
M1A: u32, // bit offset: 0 desc: Memory 1 address (used in case of Double buffer mode)
});
pub const S2FCR = MMIO(Address + 0x00000054, u32, packed struct { // byte offset: 84 stream x FIFO control register
FTH: u2, // bit offset: 0 desc: FIFO threshold selection
DMDIS: bool, // bit offset: 2 desc: Direct mode disable
FS: u3, // bit offset: 3 desc: FIFO status
reserved0: u1 = 0,
FEIE: bool, // bit offset: 7 desc: FIFO error interrupt enable
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S3CR = MMIO(Address + 0x00000058, u32, packed struct { // byte offset: 88 stream x configuration register
EN: bool, // bit offset: 0 desc: Stream enable / flag stream ready when read low
DMEIE: bool, // bit offset: 1 desc: Direct mode error interrupt enable
TEIE: bool, // bit offset: 2 desc: Transfer error interrupt enable
HTIE: bool, // bit offset: 3 desc: Half transfer interrupt enable
TCIE: bool, // bit offset: 4 desc: Transfer complete interrupt enable
PFCTRL: bool, // bit offset: 5 desc: Peripheral flow controller
DIR: u2, // bit offset: 6 desc: Data transfer direction
CIRC: bool, // bit offset: 8 desc: Circular mode
PINC: bool, // bit offset: 9 desc: Peripheral increment mode
MINC: bool, // bit offset: 10 desc: Memory increment mode
PSIZE: u2, // bit offset: 11 desc: Peripheral data size
MSIZE: u2, // bit offset: 13 desc: Memory data size
PINCOS: bool, // bit offset: 15 desc: Peripheral increment offset size
PL: u2, // bit offset: 16 desc: Priority level
DBM: bool, // bit offset: 18 desc: Double buffer mode
CT: bool, // bit offset: 19 desc: Current target (only in double buffer mode)
ACK: bool, // bit offset: 20 desc: ACK
PBURST: u2, // bit offset: 21 desc: Peripheral burst transfer configuration
MBURST: u2, // bit offset: 23 desc: Memory burst transfer configuration
CHSEL: u3, // bit offset: 25 desc: Channel selection
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S3NDTR = MMIO(Address + 0x0000005c, u32, packed struct { // byte offset: 92 stream x number of data register
NDT: u16, // bit offset: 0 desc: Number of data items to transfer
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S3PAR = MMIO(Address + 0x00000060, u32, packed struct { // byte offset: 96 stream x peripheral address register
PA: u32, // bit offset: 0 desc: Peripheral address
});
pub const S3M0AR = MMIO(Address + 0x00000064, u32, packed struct { // byte offset: 100 stream x memory 0 address register
M0A: u32, // bit offset: 0 desc: Memory 0 address
});
pub const S3M1AR = MMIO(Address + 0x00000068, u32, packed struct { // byte offset: 104 stream x memory 1 address register
M1A: u32, // bit offset: 0 desc: Memory 1 address (used in case of Double buffer mode)
});
pub const S3FCR = MMIO(Address + 0x0000006c, u32, packed struct { // byte offset: 108 stream x FIFO control register
FTH: u2, // bit offset: 0 desc: FIFO threshold selection
DMDIS: bool, // bit offset: 2 desc: Direct mode disable
FS: u3, // bit offset: 3 desc: FIFO status
reserved0: u1 = 0,
FEIE: bool, // bit offset: 7 desc: FIFO error interrupt enable
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S4CR = MMIO(Address + 0x00000070, u32, packed struct { // byte offset: 112 stream x configuration register
EN: bool, // bit offset: 0 desc: Stream enable / flag stream ready when read low
DMEIE: bool, // bit offset: 1 desc: Direct mode error interrupt enable
TEIE: bool, // bit offset: 2 desc: Transfer error interrupt enable
HTIE: bool, // bit offset: 3 desc: Half transfer interrupt enable
TCIE: bool, // bit offset: 4 desc: Transfer complete interrupt enable
PFCTRL: bool, // bit offset: 5 desc: Peripheral flow controller
DIR: u2, // bit offset: 6 desc: Data transfer direction
CIRC: bool, // bit offset: 8 desc: Circular mode
PINC: bool, // bit offset: 9 desc: Peripheral increment mode
MINC: bool, // bit offset: 10 desc: Memory increment mode
PSIZE: u2, // bit offset: 11 desc: Peripheral data size
MSIZE: u2, // bit offset: 13 desc: Memory data size
PINCOS: bool, // bit offset: 15 desc: Peripheral increment offset size
PL: u2, // bit offset: 16 desc: Priority level
DBM: bool, // bit offset: 18 desc: Double buffer mode
CT: bool, // bit offset: 19 desc: Current target (only in double buffer mode)
ACK: bool, // bit offset: 20 desc: ACK
PBURST: u2, // bit offset: 21 desc: Peripheral burst transfer configuration
MBURST: u2, // bit offset: 23 desc: Memory burst transfer configuration
CHSEL: u3, // bit offset: 25 desc: Channel selection
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S4NDTR = MMIO(Address + 0x00000074, u32, packed struct { // byte offset: 116 stream x number of data register
NDT: u16, // bit offset: 0 desc: Number of data items to transfer
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S4PAR = MMIO(Address + 0x00000078, u32, packed struct { // byte offset: 120 stream x peripheral address register
PA: u32, // bit offset: 0 desc: Peripheral address
});
pub const S4M0AR = MMIO(Address + 0x0000007c, u32, packed struct { // byte offset: 124 stream x memory 0 address register
M0A: u32, // bit offset: 0 desc: Memory 0 address
});
pub const S4M1AR = MMIO(Address + 0x00000080, u32, packed struct { // byte offset: 128 stream x memory 1 address register
M1A: u32, // bit offset: 0 desc: Memory 1 address (used in case of Double buffer mode)
});
pub const S4FCR = MMIO(Address + 0x00000084, u32, packed struct { // byte offset: 132 stream x FIFO control register
FTH: u2, // bit offset: 0 desc: FIFO threshold selection
DMDIS: bool, // bit offset: 2 desc: Direct mode disable
FS: u3, // bit offset: 3 desc: FIFO status
reserved0: u1 = 0,
FEIE: bool, // bit offset: 7 desc: FIFO error interrupt enable
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S5CR = MMIO(Address + 0x00000088, u32, packed struct { // byte offset: 136 stream x configuration register
EN: bool, // bit offset: 0 desc: Stream enable / flag stream ready when read low
DMEIE: bool, // bit offset: 1 desc: Direct mode error interrupt enable
TEIE: bool, // bit offset: 2 desc: Transfer error interrupt enable
HTIE: bool, // bit offset: 3 desc: Half transfer interrupt enable
TCIE: bool, // bit offset: 4 desc: Transfer complete interrupt enable
PFCTRL: bool, // bit offset: 5 desc: Peripheral flow controller
DIR: u2, // bit offset: 6 desc: Data transfer direction
CIRC: bool, // bit offset: 8 desc: Circular mode
PINC: bool, // bit offset: 9 desc: Peripheral increment mode
MINC: bool, // bit offset: 10 desc: Memory increment mode
PSIZE: u2, // bit offset: 11 desc: Peripheral data size
MSIZE: u2, // bit offset: 13 desc: Memory data size
PINCOS: bool, // bit offset: 15 desc: Peripheral increment offset size
PL: u2, // bit offset: 16 desc: Priority level
DBM: bool, // bit offset: 18 desc: Double buffer mode
CT: bool, // bit offset: 19 desc: Current target (only in double buffer mode)
ACK: bool, // bit offset: 20 desc: ACK
PBURST: u2, // bit offset: 21 desc: Peripheral burst transfer configuration
MBURST: u2, // bit offset: 23 desc: Memory burst transfer configuration
CHSEL: u3, // bit offset: 25 desc: Channel selection
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S5NDTR = MMIO(Address + 0x0000008c, u32, packed struct { // byte offset: 140 stream x number of data register
NDT: u16, // bit offset: 0 desc: Number of data items to transfer
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S5PAR = MMIO(Address + 0x00000090, u32, packed struct { // byte offset: 144 stream x peripheral address register
PA: u32, // bit offset: 0 desc: Peripheral address
});
pub const S5M0AR = MMIO(Address + 0x00000094, u32, packed struct { // byte offset: 148 stream x memory 0 address register
M0A: u32, // bit offset: 0 desc: Memory 0 address
});
pub const S5M1AR = MMIO(Address + 0x00000098, u32, packed struct { // byte offset: 152 stream x memory 1 address register
M1A: u32, // bit offset: 0 desc: Memory 1 address (used in case of Double buffer mode)
});
pub const S5FCR = MMIO(Address + 0x0000009c, u32, packed struct { // byte offset: 156 stream x FIFO control register
FTH: u2, // bit offset: 0 desc: FIFO threshold selection
DMDIS: bool, // bit offset: 2 desc: Direct mode disable
FS: u3, // bit offset: 3 desc: FIFO status
reserved0: u1 = 0,
FEIE: bool, // bit offset: 7 desc: FIFO error interrupt enable
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S6CR = MMIO(Address + 0x000000a0, u32, packed struct { // byte offset: 160 stream x configuration register
EN: bool, // bit offset: 0 desc: Stream enable / flag stream ready when read low
DMEIE: bool, // bit offset: 1 desc: Direct mode error interrupt enable
TEIE: bool, // bit offset: 2 desc: Transfer error interrupt enable
HTIE: bool, // bit offset: 3 desc: Half transfer interrupt enable
TCIE: bool, // bit offset: 4 desc: Transfer complete interrupt enable
PFCTRL: bool, // bit offset: 5 desc: Peripheral flow controller
DIR: u2, // bit offset: 6 desc: Data transfer direction
CIRC: bool, // bit offset: 8 desc: Circular mode
PINC: bool, // bit offset: 9 desc: Peripheral increment mode
MINC: bool, // bit offset: 10 desc: Memory increment mode
PSIZE: u2, // bit offset: 11 desc: Peripheral data size
MSIZE: u2, // bit offset: 13 desc: Memory data size
PINCOS: bool, // bit offset: 15 desc: Peripheral increment offset size
PL: u2, // bit offset: 16 desc: Priority level
DBM: bool, // bit offset: 18 desc: Double buffer mode
CT: bool, // bit offset: 19 desc: Current target (only in double buffer mode)
ACK: bool, // bit offset: 20 desc: ACK
PBURST: u2, // bit offset: 21 desc: Peripheral burst transfer configuration
MBURST: u2, // bit offset: 23 desc: Memory burst transfer configuration
CHSEL: u3, // bit offset: 25 desc: Channel selection
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S6NDTR = MMIO(Address + 0x000000a4, u32, packed struct { // byte offset: 164 stream x number of data register
NDT: u16, // bit offset: 0 desc: Number of data items to transfer
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S6PAR = MMIO(Address + 0x000000a8, u32, packed struct { // byte offset: 168 stream x peripheral address register
PA: u32, // bit offset: 0 desc: Peripheral address
});
pub const S6M0AR = MMIO(Address + 0x000000ac, u32, packed struct { // byte offset: 172 stream x memory 0 address register
M0A: u32, // bit offset: 0 desc: Memory 0 address
});
pub const S6M1AR = MMIO(Address + 0x000000b0, u32, packed struct { // byte offset: 176 stream x memory 1 address register
M1A: u32, // bit offset: 0 desc: Memory 1 address (used in case of Double buffer mode)
});
pub const S6FCR = MMIO(Address + 0x000000b4, u32, packed struct { // byte offset: 180 stream x FIFO control register
FTH: u2, // bit offset: 0 desc: FIFO threshold selection
DMDIS: bool, // bit offset: 2 desc: Direct mode disable
FS: u3, // bit offset: 3 desc: FIFO status
reserved0: u1 = 0,
FEIE: bool, // bit offset: 7 desc: FIFO error interrupt enable
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S7CR = MMIO(Address + 0x000000b8, u32, packed struct { // byte offset: 184 stream x configuration register
EN: bool, // bit offset: 0 desc: Stream enable / flag stream ready when read low
DMEIE: bool, // bit offset: 1 desc: Direct mode error interrupt enable
TEIE: bool, // bit offset: 2 desc: Transfer error interrupt enable
HTIE: bool, // bit offset: 3 desc: Half transfer interrupt enable
TCIE: bool, // bit offset: 4 desc: Transfer complete interrupt enable
PFCTRL: bool, // bit offset: 5 desc: Peripheral flow controller
DIR: u2, // bit offset: 6 desc: Data transfer direction
CIRC: bool, // bit offset: 8 desc: Circular mode
PINC: bool, // bit offset: 9 desc: Peripheral increment mode
MINC: bool, // bit offset: 10 desc: Memory increment mode
PSIZE: u2, // bit offset: 11 desc: Peripheral data size
MSIZE: u2, // bit offset: 13 desc: Memory data size
PINCOS: bool, // bit offset: 15 desc: Peripheral increment offset size
PL: u2, // bit offset: 16 desc: Priority level
DBM: bool, // bit offset: 18 desc: Double buffer mode
CT: bool, // bit offset: 19 desc: Current target (only in double buffer mode)
ACK: bool, // bit offset: 20 desc: ACK
PBURST: u2, // bit offset: 21 desc: Peripheral burst transfer configuration
MBURST: u2, // bit offset: 23 desc: Memory burst transfer configuration
CHSEL: u3, // bit offset: 25 desc: Channel selection
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S7NDTR = MMIO(Address + 0x000000bc, u32, packed struct { // byte offset: 188 stream x number of data register
NDT: u16, // bit offset: 0 desc: Number of data items to transfer
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S7PAR = MMIO(Address + 0x000000c0, u32, packed struct { // byte offset: 192 stream x peripheral address register
PA: u32, // bit offset: 0 desc: Peripheral address
});
pub const S7M0AR = MMIO(Address + 0x000000c4, u32, packed struct { // byte offset: 196 stream x memory 0 address register
M0A: u32, // bit offset: 0 desc: Memory 0 address
});
pub const S7M1AR = MMIO(Address + 0x000000c8, u32, packed struct { // byte offset: 200 stream x memory 1 address register
M1A: u32, // bit offset: 0 desc: Memory 1 address (used in case of Double buffer mode)
});
pub const S7FCR = MMIO(Address + 0x000000cc, u32, packed struct { // byte offset: 204 stream x FIFO control register
FTH: u2, // bit offset: 0 desc: FIFO threshold selection
DMDIS: bool, // bit offset: 2 desc: Direct mode disable
FS: u3, // bit offset: 3 desc: FIFO status
reserved0: u1 = 0,
FEIE: bool, // bit offset: 7 desc: FIFO error interrupt enable
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const DMA1 = extern struct {
pub const Address: u32 = 0x40026000;
pub const LISR = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 low interrupt status register
FEIF0: bool, // bit offset: 0 desc: Stream x FIFO error interrupt flag (x=3..0)
reserved0: u1 = 0,
DMEIF0: bool, // bit offset: 2 desc: Stream x direct mode error interrupt flag (x=3..0)
TEIF0: bool, // bit offset: 3 desc: Stream x transfer error interrupt flag (x=3..0)
HTIF0: bool, // bit offset: 4 desc: Stream x half transfer interrupt flag (x=3..0)
TCIF0: bool, // bit offset: 5 desc: Stream x transfer complete interrupt flag (x = 3..0)
FEIF1: bool, // bit offset: 6 desc: Stream x FIFO error interrupt flag (x=3..0)
reserved1: u1 = 0,
DMEIF1: bool, // bit offset: 8 desc: Stream x direct mode error interrupt flag (x=3..0)
TEIF1: bool, // bit offset: 9 desc: Stream x transfer error interrupt flag (x=3..0)
HTIF1: bool, // bit offset: 10 desc: Stream x half transfer interrupt flag (x=3..0)
TCIF1: bool, // bit offset: 11 desc: Stream x transfer complete interrupt flag (x = 3..0)
reserved2: u4 = 0,
FEIF2: bool, // bit offset: 16 desc: Stream x FIFO error interrupt flag (x=3..0)
reserved3: u1 = 0,
DMEIF2: bool, // bit offset: 18 desc: Stream x direct mode error interrupt flag (x=3..0)
TEIF2: bool, // bit offset: 19 desc: Stream x transfer error interrupt flag (x=3..0)
HTIF2: bool, // bit offset: 20 desc: Stream x half transfer interrupt flag (x=3..0)
TCIF2: bool, // bit offset: 21 desc: Stream x transfer complete interrupt flag (x = 3..0)
FEIF3: bool, // bit offset: 22 desc: Stream x FIFO error interrupt flag (x=3..0)
reserved4: u1 = 0,
DMEIF3: bool, // bit offset: 24 desc: Stream x direct mode error interrupt flag (x=3..0)
TEIF3: bool, // bit offset: 25 desc: Stream x transfer error interrupt flag (x=3..0)
HTIF3: bool, // bit offset: 26 desc: Stream x half transfer interrupt flag (x=3..0)
TCIF3: bool, // bit offset: 27 desc: Stream x transfer complete interrupt flag (x = 3..0)
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const HISR = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 high interrupt status register
FEIF4: bool, // bit offset: 0 desc: Stream x FIFO error interrupt flag (x=7..4)
reserved0: u1 = 0,
DMEIF4: bool, // bit offset: 2 desc: Stream x direct mode error interrupt flag (x=7..4)
TEIF4: bool, // bit offset: 3 desc: Stream x transfer error interrupt flag (x=7..4)
HTIF4: bool, // bit offset: 4 desc: Stream x half transfer interrupt flag (x=7..4)
TCIF4: bool, // bit offset: 5 desc: Stream x transfer complete interrupt flag (x=7..4)
FEIF5: bool, // bit offset: 6 desc: Stream x FIFO error interrupt flag (x=7..4)
reserved1: u1 = 0,
DMEIF5: bool, // bit offset: 8 desc: Stream x direct mode error interrupt flag (x=7..4)
TEIF5: bool, // bit offset: 9 desc: Stream x transfer error interrupt flag (x=7..4)
HTIF5: bool, // bit offset: 10 desc: Stream x half transfer interrupt flag (x=7..4)
TCIF5: bool, // bit offset: 11 desc: Stream x transfer complete interrupt flag (x=7..4)
reserved2: u4 = 0,
FEIF6: bool, // bit offset: 16 desc: Stream x FIFO error interrupt flag (x=7..4)
reserved3: u1 = 0,
DMEIF6: bool, // bit offset: 18 desc: Stream x direct mode error interrupt flag (x=7..4)
TEIF6: bool, // bit offset: 19 desc: Stream x transfer error interrupt flag (x=7..4)
HTIF6: bool, // bit offset: 20 desc: Stream x half transfer interrupt flag (x=7..4)
TCIF6: bool, // bit offset: 21 desc: Stream x transfer complete interrupt flag (x=7..4)
FEIF7: bool, // bit offset: 22 desc: Stream x FIFO error interrupt flag (x=7..4)
reserved4: u1 = 0,
DMEIF7: bool, // bit offset: 24 desc: Stream x direct mode error interrupt flag (x=7..4)
TEIF7: bool, // bit offset: 25 desc: Stream x transfer error interrupt flag (x=7..4)
HTIF7: bool, // bit offset: 26 desc: Stream x half transfer interrupt flag (x=7..4)
TCIF7: bool, // bit offset: 27 desc: Stream x transfer complete interrupt flag (x=7..4)
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const LIFCR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 low interrupt flag clear register
CFEIF0: bool, // bit offset: 0 desc: Stream x clear FIFO error interrupt flag (x = 3..0)
reserved0: u1 = 0,
CDMEIF0: bool, // bit offset: 2 desc: Stream x clear direct mode error interrupt flag (x = 3..0)
CTEIF0: bool, // bit offset: 3 desc: Stream x clear transfer error interrupt flag (x = 3..0)
CHTIF0: bool, // bit offset: 4 desc: Stream x clear half transfer interrupt flag (x = 3..0)
CTCIF0: bool, // bit offset: 5 desc: Stream x clear transfer complete interrupt flag (x = 3..0)
CFEIF1: bool, // bit offset: 6 desc: Stream x clear FIFO error interrupt flag (x = 3..0)
reserved1: u1 = 0,
CDMEIF1: bool, // bit offset: 8 desc: Stream x clear direct mode error interrupt flag (x = 3..0)
CTEIF1: bool, // bit offset: 9 desc: Stream x clear transfer error interrupt flag (x = 3..0)
CHTIF1: bool, // bit offset: 10 desc: Stream x clear half transfer interrupt flag (x = 3..0)
CTCIF1: bool, // bit offset: 11 desc: Stream x clear transfer complete interrupt flag (x = 3..0)
reserved2: u4 = 0,
CFEIF2: bool, // bit offset: 16 desc: Stream x clear FIFO error interrupt flag (x = 3..0)
reserved3: u1 = 0,
CDMEIF2: bool, // bit offset: 18 desc: Stream x clear direct mode error interrupt flag (x = 3..0)
CTEIF2: bool, // bit offset: 19 desc: Stream x clear transfer error interrupt flag (x = 3..0)
CHTIF2: bool, // bit offset: 20 desc: Stream x clear half transfer interrupt flag (x = 3..0)
CTCIF2: bool, // bit offset: 21 desc: Stream x clear transfer complete interrupt flag (x = 3..0)
CFEIF3: bool, // bit offset: 22 desc: Stream x clear FIFO error interrupt flag (x = 3..0)
reserved4: u1 = 0,
CDMEIF3: bool, // bit offset: 24 desc: Stream x clear direct mode error interrupt flag (x = 3..0)
CTEIF3: bool, // bit offset: 25 desc: Stream x clear transfer error interrupt flag (x = 3..0)
CHTIF3: bool, // bit offset: 26 desc: Stream x clear half transfer interrupt flag (x = 3..0)
CTCIF3: bool, // bit offset: 27 desc: Stream x clear transfer complete interrupt flag (x = 3..0)
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const HIFCR = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 high interrupt flag clear register
CFEIF4: bool, // bit offset: 0 desc: Stream x clear FIFO error interrupt flag (x = 7..4)
reserved0: u1 = 0,
CDMEIF4: bool, // bit offset: 2 desc: Stream x clear direct mode error interrupt flag (x = 7..4)
CTEIF4: bool, // bit offset: 3 desc: Stream x clear transfer error interrupt flag (x = 7..4)
CHTIF4: bool, // bit offset: 4 desc: Stream x clear half transfer interrupt flag (x = 7..4)
CTCIF4: bool, // bit offset: 5 desc: Stream x clear transfer complete interrupt flag (x = 7..4)
CFEIF5: bool, // bit offset: 6 desc: Stream x clear FIFO error interrupt flag (x = 7..4)
reserved1: u1 = 0,
CDMEIF5: bool, // bit offset: 8 desc: Stream x clear direct mode error interrupt flag (x = 7..4)
CTEIF5: bool, // bit offset: 9 desc: Stream x clear transfer error interrupt flag (x = 7..4)
CHTIF5: bool, // bit offset: 10 desc: Stream x clear half transfer interrupt flag (x = 7..4)
CTCIF5: bool, // bit offset: 11 desc: Stream x clear transfer complete interrupt flag (x = 7..4)
reserved2: u4 = 0,
CFEIF6: bool, // bit offset: 16 desc: Stream x clear FIFO error interrupt flag (x = 7..4)
reserved3: u1 = 0,
CDMEIF6: bool, // bit offset: 18 desc: Stream x clear direct mode error interrupt flag (x = 7..4)
CTEIF6: bool, // bit offset: 19 desc: Stream x clear transfer error interrupt flag (x = 7..4)
CHTIF6: bool, // bit offset: 20 desc: Stream x clear half transfer interrupt flag (x = 7..4)
CTCIF6: bool, // bit offset: 21 desc: Stream x clear transfer complete interrupt flag (x = 7..4)
CFEIF7: bool, // bit offset: 22 desc: Stream x clear FIFO error interrupt flag (x = 7..4)
reserved4: u1 = 0,
CDMEIF7: bool, // bit offset: 24 desc: Stream x clear direct mode error interrupt flag (x = 7..4)
CTEIF7: bool, // bit offset: 25 desc: Stream x clear transfer error interrupt flag (x = 7..4)
CHTIF7: bool, // bit offset: 26 desc: Stream x clear half transfer interrupt flag (x = 7..4)
CTCIF7: bool, // bit offset: 27 desc: Stream x clear transfer complete interrupt flag (x = 7..4)
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S0CR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 stream x configuration register
EN: bool, // bit offset: 0 desc: Stream enable / flag stream ready when read low
DMEIE: bool, // bit offset: 1 desc: Direct mode error interrupt enable
TEIE: bool, // bit offset: 2 desc: Transfer error interrupt enable
HTIE: bool, // bit offset: 3 desc: Half transfer interrupt enable
TCIE: bool, // bit offset: 4 desc: Transfer complete interrupt enable
PFCTRL: bool, // bit offset: 5 desc: Peripheral flow controller
DIR: u2, // bit offset: 6 desc: Data transfer direction
CIRC: bool, // bit offset: 8 desc: Circular mode
PINC: bool, // bit offset: 9 desc: Peripheral increment mode
MINC: bool, // bit offset: 10 desc: Memory increment mode
PSIZE: u2, // bit offset: 11 desc: Peripheral data size
MSIZE: u2, // bit offset: 13 desc: Memory data size
PINCOS: bool, // bit offset: 15 desc: Peripheral increment offset size
PL: u2, // bit offset: 16 desc: Priority level
DBM: bool, // bit offset: 18 desc: Double buffer mode
CT: bool, // bit offset: 19 desc: Current target (only in double buffer mode)
reserved0: u1 = 0,
PBURST: u2, // bit offset: 21 desc: Peripheral burst transfer configuration
MBURST: u2, // bit offset: 23 desc: Memory burst transfer configuration
CHSEL: u3, // bit offset: 25 desc: Channel selection
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S0NDTR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 stream x number of data register
NDT: u16, // bit offset: 0 desc: Number of data items to transfer
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S0PAR = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 stream x peripheral address register
PA: u32, // bit offset: 0 desc: Peripheral address
});
pub const S0M0AR = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 stream x memory 0 address register
M0A: u32, // bit offset: 0 desc: Memory 0 address
});
pub const S0M1AR = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 stream x memory 1 address register
M1A: u32, // bit offset: 0 desc: Memory 1 address (used in case of Double buffer mode)
});
pub const S0FCR = MMIO(Address + 0x00000024, u32, packed struct { // byte offset: 36 stream x FIFO control register
FTH: u2, // bit offset: 0 desc: FIFO threshold selection
DMDIS: bool, // bit offset: 2 desc: Direct mode disable
FS: u3, // bit offset: 3 desc: FIFO status
reserved0: u1 = 0,
FEIE: bool, // bit offset: 7 desc: FIFO error interrupt enable
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S1CR = MMIO(Address + 0x00000028, u32, packed struct { // byte offset: 40 stream x configuration register
EN: bool, // bit offset: 0 desc: Stream enable / flag stream ready when read low
DMEIE: bool, // bit offset: 1 desc: Direct mode error interrupt enable
TEIE: bool, // bit offset: 2 desc: Transfer error interrupt enable
HTIE: bool, // bit offset: 3 desc: Half transfer interrupt enable
TCIE: bool, // bit offset: 4 desc: Transfer complete interrupt enable
PFCTRL: bool, // bit offset: 5 desc: Peripheral flow controller
DIR: u2, // bit offset: 6 desc: Data transfer direction
CIRC: bool, // bit offset: 8 desc: Circular mode
PINC: bool, // bit offset: 9 desc: Peripheral increment mode
MINC: bool, // bit offset: 10 desc: Memory increment mode
PSIZE: u2, // bit offset: 11 desc: Peripheral data size
MSIZE: u2, // bit offset: 13 desc: Memory data size
PINCOS: bool, // bit offset: 15 desc: Peripheral increment offset size
PL: u2, // bit offset: 16 desc: Priority level
DBM: bool, // bit offset: 18 desc: Double buffer mode
CT: bool, // bit offset: 19 desc: Current target (only in double buffer mode)
ACK: bool, // bit offset: 20 desc: ACK
PBURST: u2, // bit offset: 21 desc: Peripheral burst transfer configuration
MBURST: u2, // bit offset: 23 desc: Memory burst transfer configuration
CHSEL: u3, // bit offset: 25 desc: Channel selection
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S1NDTR = MMIO(Address + 0x0000002c, u32, packed struct { // byte offset: 44 stream x number of data register
NDT: u16, // bit offset: 0 desc: Number of data items to transfer
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S1PAR = MMIO(Address + 0x00000030, u32, packed struct { // byte offset: 48 stream x peripheral address register
PA: u32, // bit offset: 0 desc: Peripheral address
});
pub const S1M0AR = MMIO(Address + 0x00000034, u32, packed struct { // byte offset: 52 stream x memory 0 address register
M0A: u32, // bit offset: 0 desc: Memory 0 address
});
pub const S1M1AR = MMIO(Address + 0x00000038, u32, packed struct { // byte offset: 56 stream x memory 1 address register
M1A: u32, // bit offset: 0 desc: Memory 1 address (used in case of Double buffer mode)
});
pub const S1FCR = MMIO(Address + 0x0000003c, u32, packed struct { // byte offset: 60 stream x FIFO control register
FTH: u2, // bit offset: 0 desc: FIFO threshold selection
DMDIS: bool, // bit offset: 2 desc: Direct mode disable
FS: u3, // bit offset: 3 desc: FIFO status
reserved0: u1 = 0,
FEIE: bool, // bit offset: 7 desc: FIFO error interrupt enable
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S2CR = MMIO(Address + 0x00000040, u32, packed struct { // byte offset: 64 stream x configuration register
EN: bool, // bit offset: 0 desc: Stream enable / flag stream ready when read low
DMEIE: bool, // bit offset: 1 desc: Direct mode error interrupt enable
TEIE: bool, // bit offset: 2 desc: Transfer error interrupt enable
HTIE: bool, // bit offset: 3 desc: Half transfer interrupt enable
TCIE: bool, // bit offset: 4 desc: Transfer complete interrupt enable
PFCTRL: bool, // bit offset: 5 desc: Peripheral flow controller
DIR: u2, // bit offset: 6 desc: Data transfer direction
CIRC: bool, // bit offset: 8 desc: Circular mode
PINC: bool, // bit offset: 9 desc: Peripheral increment mode
MINC: bool, // bit offset: 10 desc: Memory increment mode
PSIZE: u2, // bit offset: 11 desc: Peripheral data size
MSIZE: u2, // bit offset: 13 desc: Memory data size
PINCOS: bool, // bit offset: 15 desc: Peripheral increment offset size
PL: u2, // bit offset: 16 desc: Priority level
DBM: bool, // bit offset: 18 desc: Double buffer mode
CT: bool, // bit offset: 19 desc: Current target (only in double buffer mode)
ACK: bool, // bit offset: 20 desc: ACK
PBURST: u2, // bit offset: 21 desc: Peripheral burst transfer configuration
MBURST: u2, // bit offset: 23 desc: Memory burst transfer configuration
CHSEL: u3, // bit offset: 25 desc: Channel selection
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S2NDTR = MMIO(Address + 0x00000044, u32, packed struct { // byte offset: 68 stream x number of data register
NDT: u16, // bit offset: 0 desc: Number of data items to transfer
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S2PAR = MMIO(Address + 0x00000048, u32, packed struct { // byte offset: 72 stream x peripheral address register
PA: u32, // bit offset: 0 desc: Peripheral address
});
pub const S2M0AR = MMIO(Address + 0x0000004c, u32, packed struct { // byte offset: 76 stream x memory 0 address register
M0A: u32, // bit offset: 0 desc: Memory 0 address
});
pub const S2M1AR = MMIO(Address + 0x00000050, u32, packed struct { // byte offset: 80 stream x memory 1 address register
M1A: u32, // bit offset: 0 desc: Memory 1 address (used in case of Double buffer mode)
});
pub const S2FCR = MMIO(Address + 0x00000054, u32, packed struct { // byte offset: 84 stream x FIFO control register
FTH: u2, // bit offset: 0 desc: FIFO threshold selection
DMDIS: bool, // bit offset: 2 desc: Direct mode disable
FS: u3, // bit offset: 3 desc: FIFO status
reserved0: u1 = 0,
FEIE: bool, // bit offset: 7 desc: FIFO error interrupt enable
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S3CR = MMIO(Address + 0x00000058, u32, packed struct { // byte offset: 88 stream x configuration register
EN: bool, // bit offset: 0 desc: Stream enable / flag stream ready when read low
DMEIE: bool, // bit offset: 1 desc: Direct mode error interrupt enable
TEIE: bool, // bit offset: 2 desc: Transfer error interrupt enable
HTIE: bool, // bit offset: 3 desc: Half transfer interrupt enable
TCIE: bool, // bit offset: 4 desc: Transfer complete interrupt enable
PFCTRL: bool, // bit offset: 5 desc: Peripheral flow controller
DIR: u2, // bit offset: 6 desc: Data transfer direction
CIRC: bool, // bit offset: 8 desc: Circular mode
PINC: bool, // bit offset: 9 desc: Peripheral increment mode
MINC: bool, // bit offset: 10 desc: Memory increment mode
PSIZE: u2, // bit offset: 11 desc: Peripheral data size
MSIZE: u2, // bit offset: 13 desc: Memory data size
PINCOS: bool, // bit offset: 15 desc: Peripheral increment offset size
PL: u2, // bit offset: 16 desc: Priority level
DBM: bool, // bit offset: 18 desc: Double buffer mode
CT: bool, // bit offset: 19 desc: Current target (only in double buffer mode)
ACK: bool, // bit offset: 20 desc: ACK
PBURST: u2, // bit offset: 21 desc: Peripheral burst transfer configuration
MBURST: u2, // bit offset: 23 desc: Memory burst transfer configuration
CHSEL: u3, // bit offset: 25 desc: Channel selection
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S3NDTR = MMIO(Address + 0x0000005c, u32, packed struct { // byte offset: 92 stream x number of data register
NDT: u16, // bit offset: 0 desc: Number of data items to transfer
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S3PAR = MMIO(Address + 0x00000060, u32, packed struct { // byte offset: 96 stream x peripheral address register
PA: u32, // bit offset: 0 desc: Peripheral address
});
pub const S3M0AR = MMIO(Address + 0x00000064, u32, packed struct { // byte offset: 100 stream x memory 0 address register
M0A: u32, // bit offset: 0 desc: Memory 0 address
});
pub const S3M1AR = MMIO(Address + 0x00000068, u32, packed struct { // byte offset: 104 stream x memory 1 address register
M1A: u32, // bit offset: 0 desc: Memory 1 address (used in case of Double buffer mode)
});
pub const S3FCR = MMIO(Address + 0x0000006c, u32, packed struct { // byte offset: 108 stream x FIFO control register
FTH: u2, // bit offset: 0 desc: FIFO threshold selection
DMDIS: bool, // bit offset: 2 desc: Direct mode disable
FS: u3, // bit offset: 3 desc: FIFO status
reserved0: u1 = 0,
FEIE: bool, // bit offset: 7 desc: FIFO error interrupt enable
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S4CR = MMIO(Address + 0x00000070, u32, packed struct { // byte offset: 112 stream x configuration register
EN: bool, // bit offset: 0 desc: Stream enable / flag stream ready when read low
DMEIE: bool, // bit offset: 1 desc: Direct mode error interrupt enable
TEIE: bool, // bit offset: 2 desc: Transfer error interrupt enable
HTIE: bool, // bit offset: 3 desc: Half transfer interrupt enable
TCIE: bool, // bit offset: 4 desc: Transfer complete interrupt enable
PFCTRL: bool, // bit offset: 5 desc: Peripheral flow controller
DIR: u2, // bit offset: 6 desc: Data transfer direction
CIRC: bool, // bit offset: 8 desc: Circular mode
PINC: bool, // bit offset: 9 desc: Peripheral increment mode
MINC: bool, // bit offset: 10 desc: Memory increment mode
PSIZE: u2, // bit offset: 11 desc: Peripheral data size
MSIZE: u2, // bit offset: 13 desc: Memory data size
PINCOS: bool, // bit offset: 15 desc: Peripheral increment offset size
PL: u2, // bit offset: 16 desc: Priority level
DBM: bool, // bit offset: 18 desc: Double buffer mode
CT: bool, // bit offset: 19 desc: Current target (only in double buffer mode)
ACK: bool, // bit offset: 20 desc: ACK
PBURST: u2, // bit offset: 21 desc: Peripheral burst transfer configuration
MBURST: u2, // bit offset: 23 desc: Memory burst transfer configuration
CHSEL: u3, // bit offset: 25 desc: Channel selection
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S4NDTR = MMIO(Address + 0x00000074, u32, packed struct { // byte offset: 116 stream x number of data register
NDT: u16, // bit offset: 0 desc: Number of data items to transfer
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S4PAR = MMIO(Address + 0x00000078, u32, packed struct { // byte offset: 120 stream x peripheral address register
PA: u32, // bit offset: 0 desc: Peripheral address
});
pub const S4M0AR = MMIO(Address + 0x0000007c, u32, packed struct { // byte offset: 124 stream x memory 0 address register
M0A: u32, // bit offset: 0 desc: Memory 0 address
});
pub const S4M1AR = MMIO(Address + 0x00000080, u32, packed struct { // byte offset: 128 stream x memory 1 address register
M1A: u32, // bit offset: 0 desc: Memory 1 address (used in case of Double buffer mode)
});
pub const S4FCR = MMIO(Address + 0x00000084, u32, packed struct { // byte offset: 132 stream x FIFO control register
FTH: u2, // bit offset: 0 desc: FIFO threshold selection
DMDIS: bool, // bit offset: 2 desc: Direct mode disable
FS: u3, // bit offset: 3 desc: FIFO status
reserved0: u1 = 0,
FEIE: bool, // bit offset: 7 desc: FIFO error interrupt enable
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S5CR = MMIO(Address + 0x00000088, u32, packed struct { // byte offset: 136 stream x configuration register
EN: bool, // bit offset: 0 desc: Stream enable / flag stream ready when read low
DMEIE: bool, // bit offset: 1 desc: Direct mode error interrupt enable
TEIE: bool, // bit offset: 2 desc: Transfer error interrupt enable
HTIE: bool, // bit offset: 3 desc: Half transfer interrupt enable
TCIE: bool, // bit offset: 4 desc: Transfer complete interrupt enable
PFCTRL: bool, // bit offset: 5 desc: Peripheral flow controller
DIR: u2, // bit offset: 6 desc: Data transfer direction
CIRC: bool, // bit offset: 8 desc: Circular mode
PINC: bool, // bit offset: 9 desc: Peripheral increment mode
MINC: bool, // bit offset: 10 desc: Memory increment mode
PSIZE: u2, // bit offset: 11 desc: Peripheral data size
MSIZE: u2, // bit offset: 13 desc: Memory data size
PINCOS: bool, // bit offset: 15 desc: Peripheral increment offset size
PL: u2, // bit offset: 16 desc: Priority level
DBM: bool, // bit offset: 18 desc: Double buffer mode
CT: bool, // bit offset: 19 desc: Current target (only in double buffer mode)
ACK: bool, // bit offset: 20 desc: ACK
PBURST: u2, // bit offset: 21 desc: Peripheral burst transfer configuration
MBURST: u2, // bit offset: 23 desc: Memory burst transfer configuration
CHSEL: u3, // bit offset: 25 desc: Channel selection
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S5NDTR = MMIO(Address + 0x0000008c, u32, packed struct { // byte offset: 140 stream x number of data register
NDT: u16, // bit offset: 0 desc: Number of data items to transfer
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S5PAR = MMIO(Address + 0x00000090, u32, packed struct { // byte offset: 144 stream x peripheral address register
PA: u32, // bit offset: 0 desc: Peripheral address
});
pub const S5M0AR = MMIO(Address + 0x00000094, u32, packed struct { // byte offset: 148 stream x memory 0 address register
M0A: u32, // bit offset: 0 desc: Memory 0 address
});
pub const S5M1AR = MMIO(Address + 0x00000098, u32, packed struct { // byte offset: 152 stream x memory 1 address register
M1A: u32, // bit offset: 0 desc: Memory 1 address (used in case of Double buffer mode)
});
pub const S5FCR = MMIO(Address + 0x0000009c, u32, packed struct { // byte offset: 156 stream x FIFO control register
FTH: u2, // bit offset: 0 desc: FIFO threshold selection
DMDIS: bool, // bit offset: 2 desc: Direct mode disable
FS: u3, // bit offset: 3 desc: FIFO status
reserved0: u1 = 0,
FEIE: bool, // bit offset: 7 desc: FIFO error interrupt enable
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S6CR = MMIO(Address + 0x000000a0, u32, packed struct { // byte offset: 160 stream x configuration register
EN: bool, // bit offset: 0 desc: Stream enable / flag stream ready when read low
DMEIE: bool, // bit offset: 1 desc: Direct mode error interrupt enable
TEIE: bool, // bit offset: 2 desc: Transfer error interrupt enable
HTIE: bool, // bit offset: 3 desc: Half transfer interrupt enable
TCIE: bool, // bit offset: 4 desc: Transfer complete interrupt enable
PFCTRL: bool, // bit offset: 5 desc: Peripheral flow controller
DIR: u2, // bit offset: 6 desc: Data transfer direction
CIRC: bool, // bit offset: 8 desc: Circular mode
PINC: bool, // bit offset: 9 desc: Peripheral increment mode
MINC: bool, // bit offset: 10 desc: Memory increment mode
PSIZE: u2, // bit offset: 11 desc: Peripheral data size
MSIZE: u2, // bit offset: 13 desc: Memory data size
PINCOS: bool, // bit offset: 15 desc: Peripheral increment offset size
PL: u2, // bit offset: 16 desc: Priority level
DBM: bool, // bit offset: 18 desc: Double buffer mode
CT: bool, // bit offset: 19 desc: Current target (only in double buffer mode)
ACK: bool, // bit offset: 20 desc: ACK
PBURST: u2, // bit offset: 21 desc: Peripheral burst transfer configuration
MBURST: u2, // bit offset: 23 desc: Memory burst transfer configuration
CHSEL: u3, // bit offset: 25 desc: Channel selection
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S6NDTR = MMIO(Address + 0x000000a4, u32, packed struct { // byte offset: 164 stream x number of data register
NDT: u16, // bit offset: 0 desc: Number of data items to transfer
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S6PAR = MMIO(Address + 0x000000a8, u32, packed struct { // byte offset: 168 stream x peripheral address register
PA: u32, // bit offset: 0 desc: Peripheral address
});
pub const S6M0AR = MMIO(Address + 0x000000ac, u32, packed struct { // byte offset: 172 stream x memory 0 address register
M0A: u32, // bit offset: 0 desc: Memory 0 address
});
pub const S6M1AR = MMIO(Address + 0x000000b0, u32, packed struct { // byte offset: 176 stream x memory 1 address register
M1A: u32, // bit offset: 0 desc: Memory 1 address (used in case of Double buffer mode)
});
pub const S6FCR = MMIO(Address + 0x000000b4, u32, packed struct { // byte offset: 180 stream x FIFO control register
FTH: u2, // bit offset: 0 desc: FIFO threshold selection
DMDIS: bool, // bit offset: 2 desc: Direct mode disable
FS: u3, // bit offset: 3 desc: FIFO status
reserved0: u1 = 0,
FEIE: bool, // bit offset: 7 desc: FIFO error interrupt enable
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S7CR = MMIO(Address + 0x000000b8, u32, packed struct { // byte offset: 184 stream x configuration register
EN: bool, // bit offset: 0 desc: Stream enable / flag stream ready when read low
DMEIE: bool, // bit offset: 1 desc: Direct mode error interrupt enable
TEIE: bool, // bit offset: 2 desc: Transfer error interrupt enable
HTIE: bool, // bit offset: 3 desc: Half transfer interrupt enable
TCIE: bool, // bit offset: 4 desc: Transfer complete interrupt enable
PFCTRL: bool, // bit offset: 5 desc: Peripheral flow controller
DIR: u2, // bit offset: 6 desc: Data transfer direction
CIRC: bool, // bit offset: 8 desc: Circular mode
PINC: bool, // bit offset: 9 desc: Peripheral increment mode
MINC: bool, // bit offset: 10 desc: Memory increment mode
PSIZE: u2, // bit offset: 11 desc: Peripheral data size
MSIZE: u2, // bit offset: 13 desc: Memory data size
PINCOS: bool, // bit offset: 15 desc: Peripheral increment offset size
PL: u2, // bit offset: 16 desc: Priority level
DBM: bool, // bit offset: 18 desc: Double buffer mode
CT: bool, // bit offset: 19 desc: Current target (only in double buffer mode)
ACK: bool, // bit offset: 20 desc: ACK
PBURST: u2, // bit offset: 21 desc: Peripheral burst transfer configuration
MBURST: u2, // bit offset: 23 desc: Memory burst transfer configuration
CHSEL: u3, // bit offset: 25 desc: Channel selection
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S7NDTR = MMIO(Address + 0x000000bc, u32, packed struct { // byte offset: 188 stream x number of data register
NDT: u16, // bit offset: 0 desc: Number of data items to transfer
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const S7PAR = MMIO(Address + 0x000000c0, u32, packed struct { // byte offset: 192 stream x peripheral address register
PA: u32, // bit offset: 0 desc: Peripheral address
});
pub const S7M0AR = MMIO(Address + 0x000000c4, u32, packed struct { // byte offset: 196 stream x memory 0 address register
M0A: u32, // bit offset: 0 desc: Memory 0 address
});
pub const S7M1AR = MMIO(Address + 0x000000c8, u32, packed struct { // byte offset: 200 stream x memory 1 address register
M1A: u32, // bit offset: 0 desc: Memory 1 address (used in case of Double buffer mode)
});
pub const S7FCR = MMIO(Address + 0x000000cc, u32, packed struct { // byte offset: 204 stream x FIFO control register
FTH: u2, // bit offset: 0 desc: FIFO threshold selection
DMDIS: bool, // bit offset: 2 desc: Direct mode disable
FS: u3, // bit offset: 3 desc: FIFO status
reserved0: u1 = 0,
FEIE: bool, // bit offset: 7 desc: FIFO error interrupt enable
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const GPIOH = extern struct {
pub const Address: u32 = 0x40021c00;
pub const MODER = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 GPIO port mode register
MODER0: u2, // bit offset: 0 desc: Port x configuration bits (y = 0..15)
MODER1: u2, // bit offset: 2 desc: Port x configuration bits (y = 0..15)
MODER2: u2, // bit offset: 4 desc: Port x configuration bits (y = 0..15)
MODER3: u2, // bit offset: 6 desc: Port x configuration bits (y = 0..15)
MODER4: u2, // bit offset: 8 desc: Port x configuration bits (y = 0..15)
MODER5: u2, // bit offset: 10 desc: Port x configuration bits (y = 0..15)
MODER6: u2, // bit offset: 12 desc: Port x configuration bits (y = 0..15)
MODER7: u2, // bit offset: 14 desc: Port x configuration bits (y = 0..15)
MODER8: u2, // bit offset: 16 desc: Port x configuration bits (y = 0..15)
MODER9: u2, // bit offset: 18 desc: Port x configuration bits (y = 0..15)
MODER10: u2, // bit offset: 20 desc: Port x configuration bits (y = 0..15)
MODER11: u2, // bit offset: 22 desc: Port x configuration bits (y = 0..15)
MODER12: u2, // bit offset: 24 desc: Port x configuration bits (y = 0..15)
MODER13: u2, // bit offset: 26 desc: Port x configuration bits (y = 0..15)
MODER14: u2, // bit offset: 28 desc: Port x configuration bits (y = 0..15)
MODER15: u2, // bit offset: 30 desc: Port x configuration bits (y = 0..15)
});
pub const OTYPER = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 GPIO port output type register
OT0: bool, // bit offset: 0 desc: Port x configuration bits (y = 0..15)
OT1: bool, // bit offset: 1 desc: Port x configuration bits (y = 0..15)
OT2: bool, // bit offset: 2 desc: Port x configuration bits (y = 0..15)
OT3: bool, // bit offset: 3 desc: Port x configuration bits (y = 0..15)
OT4: bool, // bit offset: 4 desc: Port x configuration bits (y = 0..15)
OT5: bool, // bit offset: 5 desc: Port x configuration bits (y = 0..15)
OT6: bool, // bit offset: 6 desc: Port x configuration bits (y = 0..15)
OT7: bool, // bit offset: 7 desc: Port x configuration bits (y = 0..15)
OT8: bool, // bit offset: 8 desc: Port x configuration bits (y = 0..15)
OT9: bool, // bit offset: 9 desc: Port x configuration bits (y = 0..15)
OT10: bool, // bit offset: 10 desc: Port x configuration bits (y = 0..15)
OT11: bool, // bit offset: 11 desc: Port x configuration bits (y = 0..15)
OT12: bool, // bit offset: 12 desc: Port x configuration bits (y = 0..15)
OT13: bool, // bit offset: 13 desc: Port x configuration bits (y = 0..15)
OT14: bool, // bit offset: 14 desc: Port x configuration bits (y = 0..15)
OT15: bool, // bit offset: 15 desc: Port x configuration bits (y = 0..15)
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const OSPEEDR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 GPIO port output speed register
OSPEEDR0: u2, // bit offset: 0 desc: Port x configuration bits (y = 0..15)
OSPEEDR1: u2, // bit offset: 2 desc: Port x configuration bits (y = 0..15)
OSPEEDR2: u2, // bit offset: 4 desc: Port x configuration bits (y = 0..15)
OSPEEDR3: u2, // bit offset: 6 desc: Port x configuration bits (y = 0..15)
OSPEEDR4: u2, // bit offset: 8 desc: Port x configuration bits (y = 0..15)
OSPEEDR5: u2, // bit offset: 10 desc: Port x configuration bits (y = 0..15)
OSPEEDR6: u2, // bit offset: 12 desc: Port x configuration bits (y = 0..15)
OSPEEDR7: u2, // bit offset: 14 desc: Port x configuration bits (y = 0..15)
OSPEEDR8: u2, // bit offset: 16 desc: Port x configuration bits (y = 0..15)
OSPEEDR9: u2, // bit offset: 18 desc: Port x configuration bits (y = 0..15)
OSPEEDR10: u2, // bit offset: 20 desc: Port x configuration bits (y = 0..15)
OSPEEDR11: u2, // bit offset: 22 desc: Port x configuration bits (y = 0..15)
OSPEEDR12: u2, // bit offset: 24 desc: Port x configuration bits (y = 0..15)
OSPEEDR13: u2, // bit offset: 26 desc: Port x configuration bits (y = 0..15)
OSPEEDR14: u2, // bit offset: 28 desc: Port x configuration bits (y = 0..15)
OSPEEDR15: u2, // bit offset: 30 desc: Port x configuration bits (y = 0..15)
});
pub const PUPDR = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 GPIO port pull-up/pull-down register
PUPDR0: u2, // bit offset: 0 desc: Port x configuration bits (y = 0..15)
PUPDR1: u2, // bit offset: 2 desc: Port x configuration bits (y = 0..15)
PUPDR2: u2, // bit offset: 4 desc: Port x configuration bits (y = 0..15)
PUPDR3: u2, // bit offset: 6 desc: Port x configuration bits (y = 0..15)
PUPDR4: u2, // bit offset: 8 desc: Port x configuration bits (y = 0..15)
PUPDR5: u2, // bit offset: 10 desc: Port x configuration bits (y = 0..15)
PUPDR6: u2, // bit offset: 12 desc: Port x configuration bits (y = 0..15)
PUPDR7: u2, // bit offset: 14 desc: Port x configuration bits (y = 0..15)
PUPDR8: u2, // bit offset: 16 desc: Port x configuration bits (y = 0..15)
PUPDR9: u2, // bit offset: 18 desc: Port x configuration bits (y = 0..15)
PUPDR10: u2, // bit offset: 20 desc: Port x configuration bits (y = 0..15)
PUPDR11: u2, // bit offset: 22 desc: Port x configuration bits (y = 0..15)
PUPDR12: u2, // bit offset: 24 desc: Port x configuration bits (y = 0..15)
PUPDR13: u2, // bit offset: 26 desc: Port x configuration bits (y = 0..15)
PUPDR14: u2, // bit offset: 28 desc: Port x configuration bits (y = 0..15)
PUPDR15: u2, // bit offset: 30 desc: Port x configuration bits (y = 0..15)
});
pub const IDR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 GPIO port input data register
IDR0: bool, // bit offset: 0 desc: Port input data (y = 0..15)
IDR1: bool, // bit offset: 1 desc: Port input data (y = 0..15)
IDR2: bool, // bit offset: 2 desc: Port input data (y = 0..15)
IDR3: bool, // bit offset: 3 desc: Port input data (y = 0..15)
IDR4: bool, // bit offset: 4 desc: Port input data (y = 0..15)
IDR5: bool, // bit offset: 5 desc: Port input data (y = 0..15)
IDR6: bool, // bit offset: 6 desc: Port input data (y = 0..15)
IDR7: bool, // bit offset: 7 desc: Port input data (y = 0..15)
IDR8: bool, // bit offset: 8 desc: Port input data (y = 0..15)
IDR9: bool, // bit offset: 9 desc: Port input data (y = 0..15)
IDR10: bool, // bit offset: 10 desc: Port input data (y = 0..15)
IDR11: bool, // bit offset: 11 desc: Port input data (y = 0..15)
IDR12: bool, // bit offset: 12 desc: Port input data (y = 0..15)
IDR13: bool, // bit offset: 13 desc: Port input data (y = 0..15)
IDR14: bool, // bit offset: 14 desc: Port input data (y = 0..15)
IDR15: bool, // bit offset: 15 desc: Port input data (y = 0..15)
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const ODR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 GPIO port output data register
ODR0: bool, // bit offset: 0 desc: Port output data (y = 0..15)
ODR1: bool, // bit offset: 1 desc: Port output data (y = 0..15)
ODR2: bool, // bit offset: 2 desc: Port output data (y = 0..15)
ODR3: bool, // bit offset: 3 desc: Port output data (y = 0..15)
ODR4: bool, // bit offset: 4 desc: Port output data (y = 0..15)
ODR5: bool, // bit offset: 5 desc: Port output data (y = 0..15)
ODR6: bool, // bit offset: 6 desc: Port output data (y = 0..15)
ODR7: bool, // bit offset: 7 desc: Port output data (y = 0..15)
ODR8: bool, // bit offset: 8 desc: Port output data (y = 0..15)
ODR9: bool, // bit offset: 9 desc: Port output data (y = 0..15)
ODR10: bool, // bit offset: 10 desc: Port output data (y = 0..15)
ODR11: bool, // bit offset: 11 desc: Port output data (y = 0..15)
ODR12: bool, // bit offset: 12 desc: Port output data (y = 0..15)
ODR13: bool, // bit offset: 13 desc: Port output data (y = 0..15)
ODR14: bool, // bit offset: 14 desc: Port output data (y = 0..15)
ODR15: bool, // bit offset: 15 desc: Port output data (y = 0..15)
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const BSRR = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 GPIO port bit set/reset register
BS0: bool, // bit offset: 0 desc: Port x set bit y (y= 0..15)
BS1: bool, // bit offset: 1 desc: Port x set bit y (y= 0..15)
BS2: bool, // bit offset: 2 desc: Port x set bit y (y= 0..15)
BS3: bool, // bit offset: 3 desc: Port x set bit y (y= 0..15)
BS4: bool, // bit offset: 4 desc: Port x set bit y (y= 0..15)
BS5: bool, // bit offset: 5 desc: Port x set bit y (y= 0..15)
BS6: bool, // bit offset: 6 desc: Port x set bit y (y= 0..15)
BS7: bool, // bit offset: 7 desc: Port x set bit y (y= 0..15)
BS8: bool, // bit offset: 8 desc: Port x set bit y (y= 0..15)
BS9: bool, // bit offset: 9 desc: Port x set bit y (y= 0..15)
BS10: bool, // bit offset: 10 desc: Port x set bit y (y= 0..15)
BS11: bool, // bit offset: 11 desc: Port x set bit y (y= 0..15)
BS12: bool, // bit offset: 12 desc: Port x set bit y (y= 0..15)
BS13: bool, // bit offset: 13 desc: Port x set bit y (y= 0..15)
BS14: bool, // bit offset: 14 desc: Port x set bit y (y= 0..15)
BS15: bool, // bit offset: 15 desc: Port x set bit y (y= 0..15)
BR0: bool, // bit offset: 16 desc: Port x set bit y (y= 0..15)
BR1: bool, // bit offset: 17 desc: Port x reset bit y (y = 0..15)
BR2: bool, // bit offset: 18 desc: Port x reset bit y (y = 0..15)
BR3: bool, // bit offset: 19 desc: Port x reset bit y (y = 0..15)
BR4: bool, // bit offset: 20 desc: Port x reset bit y (y = 0..15)
BR5: bool, // bit offset: 21 desc: Port x reset bit y (y = 0..15)
BR6: bool, // bit offset: 22 desc: Port x reset bit y (y = 0..15)
BR7: bool, // bit offset: 23 desc: Port x reset bit y (y = 0..15)
BR8: bool, // bit offset: 24 desc: Port x reset bit y (y = 0..15)
BR9: bool, // bit offset: 25 desc: Port x reset bit y (y = 0..15)
BR10: bool, // bit offset: 26 desc: Port x reset bit y (y = 0..15)
BR11: bool, // bit offset: 27 desc: Port x reset bit y (y = 0..15)
BR12: bool, // bit offset: 28 desc: Port x reset bit y (y = 0..15)
BR13: bool, // bit offset: 29 desc: Port x reset bit y (y = 0..15)
BR14: bool, // bit offset: 30 desc: Port x reset bit y (y = 0..15)
BR15: bool, // bit offset: 31 desc: Port x reset bit y (y = 0..15)
});
pub const LCKR = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 GPIO port configuration lock register
LCK0: bool, // bit offset: 0 desc: Port x lock bit y (y= 0..15)
LCK1: bool, // bit offset: 1 desc: Port x lock bit y (y= 0..15)
LCK2: bool, // bit offset: 2 desc: Port x lock bit y (y= 0..15)
LCK3: bool, // bit offset: 3 desc: Port x lock bit y (y= 0..15)
LCK4: bool, // bit offset: 4 desc: Port x lock bit y (y= 0..15)
LCK5: bool, // bit offset: 5 desc: Port x lock bit y (y= 0..15)
LCK6: bool, // bit offset: 6 desc: Port x lock bit y (y= 0..15)
LCK7: bool, // bit offset: 7 desc: Port x lock bit y (y= 0..15)
LCK8: bool, // bit offset: 8 desc: Port x lock bit y (y= 0..15)
LCK9: bool, // bit offset: 9 desc: Port x lock bit y (y= 0..15)
LCK10: bool, // bit offset: 10 desc: Port x lock bit y (y= 0..15)
LCK11: bool, // bit offset: 11 desc: Port x lock bit y (y= 0..15)
LCK12: bool, // bit offset: 12 desc: Port x lock bit y (y= 0..15)
LCK13: bool, // bit offset: 13 desc: Port x lock bit y (y= 0..15)
LCK14: bool, // bit offset: 14 desc: Port x lock bit y (y= 0..15)
LCK15: bool, // bit offset: 15 desc: Port x lock bit y (y= 0..15)
LCKK: bool, // bit offset: 16 desc: Port x lock bit y (y= 0..15)
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const AFRL = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 GPIO alternate function low register
AFRL0: u4, // bit offset: 0 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL1: u4, // bit offset: 4 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL2: u4, // bit offset: 8 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL3: u4, // bit offset: 12 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL4: u4, // bit offset: 16 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL5: u4, // bit offset: 20 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL6: u4, // bit offset: 24 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL7: u4, // bit offset: 28 desc: Alternate function selection for port x bit y (y = 0..7)
});
pub const AFRH = MMIO(Address + 0x00000024, u32, packed struct { // byte offset: 36 GPIO alternate function high register
AFRH8: u4, // bit offset: 0 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH9: u4, // bit offset: 4 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH10: u4, // bit offset: 8 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH11: u4, // bit offset: 12 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH12: u4, // bit offset: 16 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH13: u4, // bit offset: 20 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH14: u4, // bit offset: 24 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH15: u4, // bit offset: 28 desc: Alternate function selection for port x bit y (y = 8..15)
});
};
pub const GPIOE = extern struct {
pub const Address: u32 = 0x40021000;
pub const MODER = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 GPIO port mode register
MODER0: u2, // bit offset: 0 desc: Port x configuration bits (y = 0..15)
MODER1: u2, // bit offset: 2 desc: Port x configuration bits (y = 0..15)
MODER2: u2, // bit offset: 4 desc: Port x configuration bits (y = 0..15)
MODER3: u2, // bit offset: 6 desc: Port x configuration bits (y = 0..15)
MODER4: u2, // bit offset: 8 desc: Port x configuration bits (y = 0..15)
MODER5: u2, // bit offset: 10 desc: Port x configuration bits (y = 0..15)
MODER6: u2, // bit offset: 12 desc: Port x configuration bits (y = 0..15)
MODER7: u2, // bit offset: 14 desc: Port x configuration bits (y = 0..15)
MODER8: u2, // bit offset: 16 desc: Port x configuration bits (y = 0..15)
MODER9: u2, // bit offset: 18 desc: Port x configuration bits (y = 0..15)
MODER10: u2, // bit offset: 20 desc: Port x configuration bits (y = 0..15)
MODER11: u2, // bit offset: 22 desc: Port x configuration bits (y = 0..15)
MODER12: u2, // bit offset: 24 desc: Port x configuration bits (y = 0..15)
MODER13: u2, // bit offset: 26 desc: Port x configuration bits (y = 0..15)
MODER14: u2, // bit offset: 28 desc: Port x configuration bits (y = 0..15)
MODER15: u2, // bit offset: 30 desc: Port x configuration bits (y = 0..15)
});
pub const OTYPER = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 GPIO port output type register
OT0: bool, // bit offset: 0 desc: Port x configuration bits (y = 0..15)
OT1: bool, // bit offset: 1 desc: Port x configuration bits (y = 0..15)
OT2: bool, // bit offset: 2 desc: Port x configuration bits (y = 0..15)
OT3: bool, // bit offset: 3 desc: Port x configuration bits (y = 0..15)
OT4: bool, // bit offset: 4 desc: Port x configuration bits (y = 0..15)
OT5: bool, // bit offset: 5 desc: Port x configuration bits (y = 0..15)
OT6: bool, // bit offset: 6 desc: Port x configuration bits (y = 0..15)
OT7: bool, // bit offset: 7 desc: Port x configuration bits (y = 0..15)
OT8: bool, // bit offset: 8 desc: Port x configuration bits (y = 0..15)
OT9: bool, // bit offset: 9 desc: Port x configuration bits (y = 0..15)
OT10: bool, // bit offset: 10 desc: Port x configuration bits (y = 0..15)
OT11: bool, // bit offset: 11 desc: Port x configuration bits (y = 0..15)
OT12: bool, // bit offset: 12 desc: Port x configuration bits (y = 0..15)
OT13: bool, // bit offset: 13 desc: Port x configuration bits (y = 0..15)
OT14: bool, // bit offset: 14 desc: Port x configuration bits (y = 0..15)
OT15: bool, // bit offset: 15 desc: Port x configuration bits (y = 0..15)
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const OSPEEDR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 GPIO port output speed register
OSPEEDR0: u2, // bit offset: 0 desc: Port x configuration bits (y = 0..15)
OSPEEDR1: u2, // bit offset: 2 desc: Port x configuration bits (y = 0..15)
OSPEEDR2: u2, // bit offset: 4 desc: Port x configuration bits (y = 0..15)
OSPEEDR3: u2, // bit offset: 6 desc: Port x configuration bits (y = 0..15)
OSPEEDR4: u2, // bit offset: 8 desc: Port x configuration bits (y = 0..15)
OSPEEDR5: u2, // bit offset: 10 desc: Port x configuration bits (y = 0..15)
OSPEEDR6: u2, // bit offset: 12 desc: Port x configuration bits (y = 0..15)
OSPEEDR7: u2, // bit offset: 14 desc: Port x configuration bits (y = 0..15)
OSPEEDR8: u2, // bit offset: 16 desc: Port x configuration bits (y = 0..15)
OSPEEDR9: u2, // bit offset: 18 desc: Port x configuration bits (y = 0..15)
OSPEEDR10: u2, // bit offset: 20 desc: Port x configuration bits (y = 0..15)
OSPEEDR11: u2, // bit offset: 22 desc: Port x configuration bits (y = 0..15)
OSPEEDR12: u2, // bit offset: 24 desc: Port x configuration bits (y = 0..15)
OSPEEDR13: u2, // bit offset: 26 desc: Port x configuration bits (y = 0..15)
OSPEEDR14: u2, // bit offset: 28 desc: Port x configuration bits (y = 0..15)
OSPEEDR15: u2, // bit offset: 30 desc: Port x configuration bits (y = 0..15)
});
pub const PUPDR = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 GPIO port pull-up/pull-down register
PUPDR0: u2, // bit offset: 0 desc: Port x configuration bits (y = 0..15)
PUPDR1: u2, // bit offset: 2 desc: Port x configuration bits (y = 0..15)
PUPDR2: u2, // bit offset: 4 desc: Port x configuration bits (y = 0..15)
PUPDR3: u2, // bit offset: 6 desc: Port x configuration bits (y = 0..15)
PUPDR4: u2, // bit offset: 8 desc: Port x configuration bits (y = 0..15)
PUPDR5: u2, // bit offset: 10 desc: Port x configuration bits (y = 0..15)
PUPDR6: u2, // bit offset: 12 desc: Port x configuration bits (y = 0..15)
PUPDR7: u2, // bit offset: 14 desc: Port x configuration bits (y = 0..15)
PUPDR8: u2, // bit offset: 16 desc: Port x configuration bits (y = 0..15)
PUPDR9: u2, // bit offset: 18 desc: Port x configuration bits (y = 0..15)
PUPDR10: u2, // bit offset: 20 desc: Port x configuration bits (y = 0..15)
PUPDR11: u2, // bit offset: 22 desc: Port x configuration bits (y = 0..15)
PUPDR12: u2, // bit offset: 24 desc: Port x configuration bits (y = 0..15)
PUPDR13: u2, // bit offset: 26 desc: Port x configuration bits (y = 0..15)
PUPDR14: u2, // bit offset: 28 desc: Port x configuration bits (y = 0..15)
PUPDR15: u2, // bit offset: 30 desc: Port x configuration bits (y = 0..15)
});
pub const IDR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 GPIO port input data register
IDR0: bool, // bit offset: 0 desc: Port input data (y = 0..15)
IDR1: bool, // bit offset: 1 desc: Port input data (y = 0..15)
IDR2: bool, // bit offset: 2 desc: Port input data (y = 0..15)
IDR3: bool, // bit offset: 3 desc: Port input data (y = 0..15)
IDR4: bool, // bit offset: 4 desc: Port input data (y = 0..15)
IDR5: bool, // bit offset: 5 desc: Port input data (y = 0..15)
IDR6: bool, // bit offset: 6 desc: Port input data (y = 0..15)
IDR7: bool, // bit offset: 7 desc: Port input data (y = 0..15)
IDR8: bool, // bit offset: 8 desc: Port input data (y = 0..15)
IDR9: bool, // bit offset: 9 desc: Port input data (y = 0..15)
IDR10: bool, // bit offset: 10 desc: Port input data (y = 0..15)
IDR11: bool, // bit offset: 11 desc: Port input data (y = 0..15)
IDR12: bool, // bit offset: 12 desc: Port input data (y = 0..15)
IDR13: bool, // bit offset: 13 desc: Port input data (y = 0..15)
IDR14: bool, // bit offset: 14 desc: Port input data (y = 0..15)
IDR15: bool, // bit offset: 15 desc: Port input data (y = 0..15)
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const ODR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 GPIO port output data register
ODR0: bool, // bit offset: 0 desc: Port output data (y = 0..15)
ODR1: bool, // bit offset: 1 desc: Port output data (y = 0..15)
ODR2: bool, // bit offset: 2 desc: Port output data (y = 0..15)
ODR3: bool, // bit offset: 3 desc: Port output data (y = 0..15)
ODR4: bool, // bit offset: 4 desc: Port output data (y = 0..15)
ODR5: bool, // bit offset: 5 desc: Port output data (y = 0..15)
ODR6: bool, // bit offset: 6 desc: Port output data (y = 0..15)
ODR7: bool, // bit offset: 7 desc: Port output data (y = 0..15)
ODR8: bool, // bit offset: 8 desc: Port output data (y = 0..15)
ODR9: bool, // bit offset: 9 desc: Port output data (y = 0..15)
ODR10: bool, // bit offset: 10 desc: Port output data (y = 0..15)
ODR11: bool, // bit offset: 11 desc: Port output data (y = 0..15)
ODR12: bool, // bit offset: 12 desc: Port output data (y = 0..15)
ODR13: bool, // bit offset: 13 desc: Port output data (y = 0..15)
ODR14: bool, // bit offset: 14 desc: Port output data (y = 0..15)
ODR15: bool, // bit offset: 15 desc: Port output data (y = 0..15)
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const BSRR = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 GPIO port bit set/reset register
BS0: bool, // bit offset: 0 desc: Port x set bit y (y= 0..15)
BS1: bool, // bit offset: 1 desc: Port x set bit y (y= 0..15)
BS2: bool, // bit offset: 2 desc: Port x set bit y (y= 0..15)
BS3: bool, // bit offset: 3 desc: Port x set bit y (y= 0..15)
BS4: bool, // bit offset: 4 desc: Port x set bit y (y= 0..15)
BS5: bool, // bit offset: 5 desc: Port x set bit y (y= 0..15)
BS6: bool, // bit offset: 6 desc: Port x set bit y (y= 0..15)
BS7: bool, // bit offset: 7 desc: Port x set bit y (y= 0..15)
BS8: bool, // bit offset: 8 desc: Port x set bit y (y= 0..15)
BS9: bool, // bit offset: 9 desc: Port x set bit y (y= 0..15)
BS10: bool, // bit offset: 10 desc: Port x set bit y (y= 0..15)
BS11: bool, // bit offset: 11 desc: Port x set bit y (y= 0..15)
BS12: bool, // bit offset: 12 desc: Port x set bit y (y= 0..15)
BS13: bool, // bit offset: 13 desc: Port x set bit y (y= 0..15)
BS14: bool, // bit offset: 14 desc: Port x set bit y (y= 0..15)
BS15: bool, // bit offset: 15 desc: Port x set bit y (y= 0..15)
BR0: bool, // bit offset: 16 desc: Port x set bit y (y= 0..15)
BR1: bool, // bit offset: 17 desc: Port x reset bit y (y = 0..15)
BR2: bool, // bit offset: 18 desc: Port x reset bit y (y = 0..15)
BR3: bool, // bit offset: 19 desc: Port x reset bit y (y = 0..15)
BR4: bool, // bit offset: 20 desc: Port x reset bit y (y = 0..15)
BR5: bool, // bit offset: 21 desc: Port x reset bit y (y = 0..15)
BR6: bool, // bit offset: 22 desc: Port x reset bit y (y = 0..15)
BR7: bool, // bit offset: 23 desc: Port x reset bit y (y = 0..15)
BR8: bool, // bit offset: 24 desc: Port x reset bit y (y = 0..15)
BR9: bool, // bit offset: 25 desc: Port x reset bit y (y = 0..15)
BR10: bool, // bit offset: 26 desc: Port x reset bit y (y = 0..15)
BR11: bool, // bit offset: 27 desc: Port x reset bit y (y = 0..15)
BR12: bool, // bit offset: 28 desc: Port x reset bit y (y = 0..15)
BR13: bool, // bit offset: 29 desc: Port x reset bit y (y = 0..15)
BR14: bool, // bit offset: 30 desc: Port x reset bit y (y = 0..15)
BR15: bool, // bit offset: 31 desc: Port x reset bit y (y = 0..15)
});
pub const LCKR = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 GPIO port configuration lock register
LCK0: bool, // bit offset: 0 desc: Port x lock bit y (y= 0..15)
LCK1: bool, // bit offset: 1 desc: Port x lock bit y (y= 0..15)
LCK2: bool, // bit offset: 2 desc: Port x lock bit y (y= 0..15)
LCK3: bool, // bit offset: 3 desc: Port x lock bit y (y= 0..15)
LCK4: bool, // bit offset: 4 desc: Port x lock bit y (y= 0..15)
LCK5: bool, // bit offset: 5 desc: Port x lock bit y (y= 0..15)
LCK6: bool, // bit offset: 6 desc: Port x lock bit y (y= 0..15)
LCK7: bool, // bit offset: 7 desc: Port x lock bit y (y= 0..15)
LCK8: bool, // bit offset: 8 desc: Port x lock bit y (y= 0..15)
LCK9: bool, // bit offset: 9 desc: Port x lock bit y (y= 0..15)
LCK10: bool, // bit offset: 10 desc: Port x lock bit y (y= 0..15)
LCK11: bool, // bit offset: 11 desc: Port x lock bit y (y= 0..15)
LCK12: bool, // bit offset: 12 desc: Port x lock bit y (y= 0..15)
LCK13: bool, // bit offset: 13 desc: Port x lock bit y (y= 0..15)
LCK14: bool, // bit offset: 14 desc: Port x lock bit y (y= 0..15)
LCK15: bool, // bit offset: 15 desc: Port x lock bit y (y= 0..15)
LCKK: bool, // bit offset: 16 desc: Port x lock bit y (y= 0..15)
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const AFRL = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 GPIO alternate function low register
AFRL0: u4, // bit offset: 0 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL1: u4, // bit offset: 4 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL2: u4, // bit offset: 8 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL3: u4, // bit offset: 12 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL4: u4, // bit offset: 16 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL5: u4, // bit offset: 20 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL6: u4, // bit offset: 24 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL7: u4, // bit offset: 28 desc: Alternate function selection for port x bit y (y = 0..7)
});
pub const AFRH = MMIO(Address + 0x00000024, u32, packed struct { // byte offset: 36 GPIO alternate function high register
AFRH8: u4, // bit offset: 0 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH9: u4, // bit offset: 4 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH10: u4, // bit offset: 8 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH11: u4, // bit offset: 12 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH12: u4, // bit offset: 16 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH13: u4, // bit offset: 20 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH14: u4, // bit offset: 24 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH15: u4, // bit offset: 28 desc: Alternate function selection for port x bit y (y = 8..15)
});
};
pub const GPIOD = extern struct {
pub const Address: u32 = 0x40020c00;
pub const MODER = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 GPIO port mode register
MODER0: u2, // bit offset: 0 desc: Port x configuration bits (y = 0..15)
MODER1: u2, // bit offset: 2 desc: Port x configuration bits (y = 0..15)
MODER2: u2, // bit offset: 4 desc: Port x configuration bits (y = 0..15)
MODER3: u2, // bit offset: 6 desc: Port x configuration bits (y = 0..15)
MODER4: u2, // bit offset: 8 desc: Port x configuration bits (y = 0..15)
MODER5: u2, // bit offset: 10 desc: Port x configuration bits (y = 0..15)
MODER6: u2, // bit offset: 12 desc: Port x configuration bits (y = 0..15)
MODER7: u2, // bit offset: 14 desc: Port x configuration bits (y = 0..15)
MODER8: u2, // bit offset: 16 desc: Port x configuration bits (y = 0..15)
MODER9: u2, // bit offset: 18 desc: Port x configuration bits (y = 0..15)
MODER10: u2, // bit offset: 20 desc: Port x configuration bits (y = 0..15)
MODER11: u2, // bit offset: 22 desc: Port x configuration bits (y = 0..15)
MODER12: u2, // bit offset: 24 desc: Port x configuration bits (y = 0..15)
MODER13: u2, // bit offset: 26 desc: Port x configuration bits (y = 0..15)
MODER14: u2, // bit offset: 28 desc: Port x configuration bits (y = 0..15)
MODER15: u2, // bit offset: 30 desc: Port x configuration bits (y = 0..15)
});
pub const OTYPER = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 GPIO port output type register
OT0: bool, // bit offset: 0 desc: Port x configuration bits (y = 0..15)
OT1: bool, // bit offset: 1 desc: Port x configuration bits (y = 0..15)
OT2: bool, // bit offset: 2 desc: Port x configuration bits (y = 0..15)
OT3: bool, // bit offset: 3 desc: Port x configuration bits (y = 0..15)
OT4: bool, // bit offset: 4 desc: Port x configuration bits (y = 0..15)
OT5: bool, // bit offset: 5 desc: Port x configuration bits (y = 0..15)
OT6: bool, // bit offset: 6 desc: Port x configuration bits (y = 0..15)
OT7: bool, // bit offset: 7 desc: Port x configuration bits (y = 0..15)
OT8: bool, // bit offset: 8 desc: Port x configuration bits (y = 0..15)
OT9: bool, // bit offset: 9 desc: Port x configuration bits (y = 0..15)
OT10: bool, // bit offset: 10 desc: Port x configuration bits (y = 0..15)
OT11: bool, // bit offset: 11 desc: Port x configuration bits (y = 0..15)
OT12: bool, // bit offset: 12 desc: Port x configuration bits (y = 0..15)
OT13: bool, // bit offset: 13 desc: Port x configuration bits (y = 0..15)
OT14: bool, // bit offset: 14 desc: Port x configuration bits (y = 0..15)
OT15: bool, // bit offset: 15 desc: Port x configuration bits (y = 0..15)
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const OSPEEDR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 GPIO port output speed register
OSPEEDR0: u2, // bit offset: 0 desc: Port x configuration bits (y = 0..15)
OSPEEDR1: u2, // bit offset: 2 desc: Port x configuration bits (y = 0..15)
OSPEEDR2: u2, // bit offset: 4 desc: Port x configuration bits (y = 0..15)
OSPEEDR3: u2, // bit offset: 6 desc: Port x configuration bits (y = 0..15)
OSPEEDR4: u2, // bit offset: 8 desc: Port x configuration bits (y = 0..15)
OSPEEDR5: u2, // bit offset: 10 desc: Port x configuration bits (y = 0..15)
OSPEEDR6: u2, // bit offset: 12 desc: Port x configuration bits (y = 0..15)
OSPEEDR7: u2, // bit offset: 14 desc: Port x configuration bits (y = 0..15)
OSPEEDR8: u2, // bit offset: 16 desc: Port x configuration bits (y = 0..15)
OSPEEDR9: u2, // bit offset: 18 desc: Port x configuration bits (y = 0..15)
OSPEEDR10: u2, // bit offset: 20 desc: Port x configuration bits (y = 0..15)
OSPEEDR11: u2, // bit offset: 22 desc: Port x configuration bits (y = 0..15)
OSPEEDR12: u2, // bit offset: 24 desc: Port x configuration bits (y = 0..15)
OSPEEDR13: u2, // bit offset: 26 desc: Port x configuration bits (y = 0..15)
OSPEEDR14: u2, // bit offset: 28 desc: Port x configuration bits (y = 0..15)
OSPEEDR15: u2, // bit offset: 30 desc: Port x configuration bits (y = 0..15)
});
pub const PUPDR = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 GPIO port pull-up/pull-down register
PUPDR0: u2, // bit offset: 0 desc: Port x configuration bits (y = 0..15)
PUPDR1: u2, // bit offset: 2 desc: Port x configuration bits (y = 0..15)
PUPDR2: u2, // bit offset: 4 desc: Port x configuration bits (y = 0..15)
PUPDR3: u2, // bit offset: 6 desc: Port x configuration bits (y = 0..15)
PUPDR4: u2, // bit offset: 8 desc: Port x configuration bits (y = 0..15)
PUPDR5: u2, // bit offset: 10 desc: Port x configuration bits (y = 0..15)
PUPDR6: u2, // bit offset: 12 desc: Port x configuration bits (y = 0..15)
PUPDR7: u2, // bit offset: 14 desc: Port x configuration bits (y = 0..15)
PUPDR8: u2, // bit offset: 16 desc: Port x configuration bits (y = 0..15)
PUPDR9: u2, // bit offset: 18 desc: Port x configuration bits (y = 0..15)
PUPDR10: u2, // bit offset: 20 desc: Port x configuration bits (y = 0..15)
PUPDR11: u2, // bit offset: 22 desc: Port x configuration bits (y = 0..15)
PUPDR12: u2, // bit offset: 24 desc: Port x configuration bits (y = 0..15)
PUPDR13: u2, // bit offset: 26 desc: Port x configuration bits (y = 0..15)
PUPDR14: u2, // bit offset: 28 desc: Port x configuration bits (y = 0..15)
PUPDR15: u2, // bit offset: 30 desc: Port x configuration bits (y = 0..15)
});
pub const IDR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 GPIO port input data register
IDR0: bool, // bit offset: 0 desc: Port input data (y = 0..15)
IDR1: bool, // bit offset: 1 desc: Port input data (y = 0..15)
IDR2: bool, // bit offset: 2 desc: Port input data (y = 0..15)
IDR3: bool, // bit offset: 3 desc: Port input data (y = 0..15)
IDR4: bool, // bit offset: 4 desc: Port input data (y = 0..15)
IDR5: bool, // bit offset: 5 desc: Port input data (y = 0..15)
IDR6: bool, // bit offset: 6 desc: Port input data (y = 0..15)
IDR7: bool, // bit offset: 7 desc: Port input data (y = 0..15)
IDR8: bool, // bit offset: 8 desc: Port input data (y = 0..15)
IDR9: bool, // bit offset: 9 desc: Port input data (y = 0..15)
IDR10: bool, // bit offset: 10 desc: Port input data (y = 0..15)
IDR11: bool, // bit offset: 11 desc: Port input data (y = 0..15)
IDR12: bool, // bit offset: 12 desc: Port input data (y = 0..15)
IDR13: bool, // bit offset: 13 desc: Port input data (y = 0..15)
IDR14: bool, // bit offset: 14 desc: Port input data (y = 0..15)
IDR15: bool, // bit offset: 15 desc: Port input data (y = 0..15)
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const ODR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 GPIO port output data register
ODR0: bool, // bit offset: 0 desc: Port output data (y = 0..15)
ODR1: bool, // bit offset: 1 desc: Port output data (y = 0..15)
ODR2: bool, // bit offset: 2 desc: Port output data (y = 0..15)
ODR3: bool, // bit offset: 3 desc: Port output data (y = 0..15)
ODR4: bool, // bit offset: 4 desc: Port output data (y = 0..15)
ODR5: bool, // bit offset: 5 desc: Port output data (y = 0..15)
ODR6: bool, // bit offset: 6 desc: Port output data (y = 0..15)
ODR7: bool, // bit offset: 7 desc: Port output data (y = 0..15)
ODR8: bool, // bit offset: 8 desc: Port output data (y = 0..15)
ODR9: bool, // bit offset: 9 desc: Port output data (y = 0..15)
ODR10: bool, // bit offset: 10 desc: Port output data (y = 0..15)
ODR11: bool, // bit offset: 11 desc: Port output data (y = 0..15)
ODR12: bool, // bit offset: 12 desc: Port output data (y = 0..15)
ODR13: bool, // bit offset: 13 desc: Port output data (y = 0..15)
ODR14: bool, // bit offset: 14 desc: Port output data (y = 0..15)
ODR15: bool, // bit offset: 15 desc: Port output data (y = 0..15)
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const BSRR = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 GPIO port bit set/reset register
BS0: bool, // bit offset: 0 desc: Port x set bit y (y= 0..15)
BS1: bool, // bit offset: 1 desc: Port x set bit y (y= 0..15)
BS2: bool, // bit offset: 2 desc: Port x set bit y (y= 0..15)
BS3: bool, // bit offset: 3 desc: Port x set bit y (y= 0..15)
BS4: bool, // bit offset: 4 desc: Port x set bit y (y= 0..15)
BS5: bool, // bit offset: 5 desc: Port x set bit y (y= 0..15)
BS6: bool, // bit offset: 6 desc: Port x set bit y (y= 0..15)
BS7: bool, // bit offset: 7 desc: Port x set bit y (y= 0..15)
BS8: bool, // bit offset: 8 desc: Port x set bit y (y= 0..15)
BS9: bool, // bit offset: 9 desc: Port x set bit y (y= 0..15)
BS10: bool, // bit offset: 10 desc: Port x set bit y (y= 0..15)
BS11: bool, // bit offset: 11 desc: Port x set bit y (y= 0..15)
BS12: bool, // bit offset: 12 desc: Port x set bit y (y= 0..15)
BS13: bool, // bit offset: 13 desc: Port x set bit y (y= 0..15)
BS14: bool, // bit offset: 14 desc: Port x set bit y (y= 0..15)
BS15: bool, // bit offset: 15 desc: Port x set bit y (y= 0..15)
BR0: bool, // bit offset: 16 desc: Port x set bit y (y= 0..15)
BR1: bool, // bit offset: 17 desc: Port x reset bit y (y = 0..15)
BR2: bool, // bit offset: 18 desc: Port x reset bit y (y = 0..15)
BR3: bool, // bit offset: 19 desc: Port x reset bit y (y = 0..15)
BR4: bool, // bit offset: 20 desc: Port x reset bit y (y = 0..15)
BR5: bool, // bit offset: 21 desc: Port x reset bit y (y = 0..15)
BR6: bool, // bit offset: 22 desc: Port x reset bit y (y = 0..15)
BR7: bool, // bit offset: 23 desc: Port x reset bit y (y = 0..15)
BR8: bool, // bit offset: 24 desc: Port x reset bit y (y = 0..15)
BR9: bool, // bit offset: 25 desc: Port x reset bit y (y = 0..15)
BR10: bool, // bit offset: 26 desc: Port x reset bit y (y = 0..15)
BR11: bool, // bit offset: 27 desc: Port x reset bit y (y = 0..15)
BR12: bool, // bit offset: 28 desc: Port x reset bit y (y = 0..15)
BR13: bool, // bit offset: 29 desc: Port x reset bit y (y = 0..15)
BR14: bool, // bit offset: 30 desc: Port x reset bit y (y = 0..15)
BR15: bool, // bit offset: 31 desc: Port x reset bit y (y = 0..15)
});
pub const LCKR = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 GPIO port configuration lock register
LCK0: bool, // bit offset: 0 desc: Port x lock bit y (y= 0..15)
LCK1: bool, // bit offset: 1 desc: Port x lock bit y (y= 0..15)
LCK2: bool, // bit offset: 2 desc: Port x lock bit y (y= 0..15)
LCK3: bool, // bit offset: 3 desc: Port x lock bit y (y= 0..15)
LCK4: bool, // bit offset: 4 desc: Port x lock bit y (y= 0..15)
LCK5: bool, // bit offset: 5 desc: Port x lock bit y (y= 0..15)
LCK6: bool, // bit offset: 6 desc: Port x lock bit y (y= 0..15)
LCK7: bool, // bit offset: 7 desc: Port x lock bit y (y= 0..15)
LCK8: bool, // bit offset: 8 desc: Port x lock bit y (y= 0..15)
LCK9: bool, // bit offset: 9 desc: Port x lock bit y (y= 0..15)
LCK10: bool, // bit offset: 10 desc: Port x lock bit y (y= 0..15)
LCK11: bool, // bit offset: 11 desc: Port x lock bit y (y= 0..15)
LCK12: bool, // bit offset: 12 desc: Port x lock bit y (y= 0..15)
LCK13: bool, // bit offset: 13 desc: Port x lock bit y (y= 0..15)
LCK14: bool, // bit offset: 14 desc: Port x lock bit y (y= 0..15)
LCK15: bool, // bit offset: 15 desc: Port x lock bit y (y= 0..15)
LCKK: bool, // bit offset: 16 desc: Port x lock bit y (y= 0..15)
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const AFRL = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 GPIO alternate function low register
AFRL0: u4, // bit offset: 0 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL1: u4, // bit offset: 4 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL2: u4, // bit offset: 8 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL3: u4, // bit offset: 12 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL4: u4, // bit offset: 16 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL5: u4, // bit offset: 20 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL6: u4, // bit offset: 24 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL7: u4, // bit offset: 28 desc: Alternate function selection for port x bit y (y = 0..7)
});
pub const AFRH = MMIO(Address + 0x00000024, u32, packed struct { // byte offset: 36 GPIO alternate function high register
AFRH8: u4, // bit offset: 0 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH9: u4, // bit offset: 4 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH10: u4, // bit offset: 8 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH11: u4, // bit offset: 12 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH12: u4, // bit offset: 16 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH13: u4, // bit offset: 20 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH14: u4, // bit offset: 24 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH15: u4, // bit offset: 28 desc: Alternate function selection for port x bit y (y = 8..15)
});
};
pub const GPIOC = extern struct {
pub const Address: u32 = 0x40020800;
pub const MODER = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 GPIO port mode register
MODER0: u2, // bit offset: 0 desc: Port x configuration bits (y = 0..15)
MODER1: u2, // bit offset: 2 desc: Port x configuration bits (y = 0..15)
MODER2: u2, // bit offset: 4 desc: Port x configuration bits (y = 0..15)
MODER3: u2, // bit offset: 6 desc: Port x configuration bits (y = 0..15)
MODER4: u2, // bit offset: 8 desc: Port x configuration bits (y = 0..15)
MODER5: u2, // bit offset: 10 desc: Port x configuration bits (y = 0..15)
MODER6: u2, // bit offset: 12 desc: Port x configuration bits (y = 0..15)
MODER7: u2, // bit offset: 14 desc: Port x configuration bits (y = 0..15)
MODER8: u2, // bit offset: 16 desc: Port x configuration bits (y = 0..15)
MODER9: u2, // bit offset: 18 desc: Port x configuration bits (y = 0..15)
MODER10: u2, // bit offset: 20 desc: Port x configuration bits (y = 0..15)
MODER11: u2, // bit offset: 22 desc: Port x configuration bits (y = 0..15)
MODER12: u2, // bit offset: 24 desc: Port x configuration bits (y = 0..15)
MODER13: u2, // bit offset: 26 desc: Port x configuration bits (y = 0..15)
MODER14: u2, // bit offset: 28 desc: Port x configuration bits (y = 0..15)
MODER15: u2, // bit offset: 30 desc: Port x configuration bits (y = 0..15)
});
pub const OTYPER = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 GPIO port output type register
OT0: bool, // bit offset: 0 desc: Port x configuration bits (y = 0..15)
OT1: bool, // bit offset: 1 desc: Port x configuration bits (y = 0..15)
OT2: bool, // bit offset: 2 desc: Port x configuration bits (y = 0..15)
OT3: bool, // bit offset: 3 desc: Port x configuration bits (y = 0..15)
OT4: bool, // bit offset: 4 desc: Port x configuration bits (y = 0..15)
OT5: bool, // bit offset: 5 desc: Port x configuration bits (y = 0..15)
OT6: bool, // bit offset: 6 desc: Port x configuration bits (y = 0..15)
OT7: bool, // bit offset: 7 desc: Port x configuration bits (y = 0..15)
OT8: bool, // bit offset: 8 desc: Port x configuration bits (y = 0..15)
OT9: bool, // bit offset: 9 desc: Port x configuration bits (y = 0..15)
OT10: bool, // bit offset: 10 desc: Port x configuration bits (y = 0..15)
OT11: bool, // bit offset: 11 desc: Port x configuration bits (y = 0..15)
OT12: bool, // bit offset: 12 desc: Port x configuration bits (y = 0..15)
OT13: bool, // bit offset: 13 desc: Port x configuration bits (y = 0..15)
OT14: bool, // bit offset: 14 desc: Port x configuration bits (y = 0..15)
OT15: bool, // bit offset: 15 desc: Port x configuration bits (y = 0..15)
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const OSPEEDR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 GPIO port output speed register
OSPEEDR0: u2, // bit offset: 0 desc: Port x configuration bits (y = 0..15)
OSPEEDR1: u2, // bit offset: 2 desc: Port x configuration bits (y = 0..15)
OSPEEDR2: u2, // bit offset: 4 desc: Port x configuration bits (y = 0..15)
OSPEEDR3: u2, // bit offset: 6 desc: Port x configuration bits (y = 0..15)
OSPEEDR4: u2, // bit offset: 8 desc: Port x configuration bits (y = 0..15)
OSPEEDR5: u2, // bit offset: 10 desc: Port x configuration bits (y = 0..15)
OSPEEDR6: u2, // bit offset: 12 desc: Port x configuration bits (y = 0..15)
OSPEEDR7: u2, // bit offset: 14 desc: Port x configuration bits (y = 0..15)
OSPEEDR8: u2, // bit offset: 16 desc: Port x configuration bits (y = 0..15)
OSPEEDR9: u2, // bit offset: 18 desc: Port x configuration bits (y = 0..15)
OSPEEDR10: u2, // bit offset: 20 desc: Port x configuration bits (y = 0..15)
OSPEEDR11: u2, // bit offset: 22 desc: Port x configuration bits (y = 0..15)
OSPEEDR12: u2, // bit offset: 24 desc: Port x configuration bits (y = 0..15)
OSPEEDR13: u2, // bit offset: 26 desc: Port x configuration bits (y = 0..15)
OSPEEDR14: u2, // bit offset: 28 desc: Port x configuration bits (y = 0..15)
OSPEEDR15: u2, // bit offset: 30 desc: Port x configuration bits (y = 0..15)
});
pub const PUPDR = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 GPIO port pull-up/pull-down register
PUPDR0: u2, // bit offset: 0 desc: Port x configuration bits (y = 0..15)
PUPDR1: u2, // bit offset: 2 desc: Port x configuration bits (y = 0..15)
PUPDR2: u2, // bit offset: 4 desc: Port x configuration bits (y = 0..15)
PUPDR3: u2, // bit offset: 6 desc: Port x configuration bits (y = 0..15)
PUPDR4: u2, // bit offset: 8 desc: Port x configuration bits (y = 0..15)
PUPDR5: u2, // bit offset: 10 desc: Port x configuration bits (y = 0..15)
PUPDR6: u2, // bit offset: 12 desc: Port x configuration bits (y = 0..15)
PUPDR7: u2, // bit offset: 14 desc: Port x configuration bits (y = 0..15)
PUPDR8: u2, // bit offset: 16 desc: Port x configuration bits (y = 0..15)
PUPDR9: u2, // bit offset: 18 desc: Port x configuration bits (y = 0..15)
PUPDR10: u2, // bit offset: 20 desc: Port x configuration bits (y = 0..15)
PUPDR11: u2, // bit offset: 22 desc: Port x configuration bits (y = 0..15)
PUPDR12: u2, // bit offset: 24 desc: Port x configuration bits (y = 0..15)
PUPDR13: u2, // bit offset: 26 desc: Port x configuration bits (y = 0..15)
PUPDR14: u2, // bit offset: 28 desc: Port x configuration bits (y = 0..15)
PUPDR15: u2, // bit offset: 30 desc: Port x configuration bits (y = 0..15)
});
pub const IDR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 GPIO port input data register
IDR0: bool, // bit offset: 0 desc: Port input data (y = 0..15)
IDR1: bool, // bit offset: 1 desc: Port input data (y = 0..15)
IDR2: bool, // bit offset: 2 desc: Port input data (y = 0..15)
IDR3: bool, // bit offset: 3 desc: Port input data (y = 0..15)
IDR4: bool, // bit offset: 4 desc: Port input data (y = 0..15)
IDR5: bool, // bit offset: 5 desc: Port input data (y = 0..15)
IDR6: bool, // bit offset: 6 desc: Port input data (y = 0..15)
IDR7: bool, // bit offset: 7 desc: Port input data (y = 0..15)
IDR8: bool, // bit offset: 8 desc: Port input data (y = 0..15)
IDR9: bool, // bit offset: 9 desc: Port input data (y = 0..15)
IDR10: bool, // bit offset: 10 desc: Port input data (y = 0..15)
IDR11: bool, // bit offset: 11 desc: Port input data (y = 0..15)
IDR12: bool, // bit offset: 12 desc: Port input data (y = 0..15)
IDR13: bool, // bit offset: 13 desc: Port input data (y = 0..15)
IDR14: bool, // bit offset: 14 desc: Port input data (y = 0..15)
IDR15: bool, // bit offset: 15 desc: Port input data (y = 0..15)
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const ODR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 GPIO port output data register
ODR0: bool, // bit offset: 0 desc: Port output data (y = 0..15)
ODR1: bool, // bit offset: 1 desc: Port output data (y = 0..15)
ODR2: bool, // bit offset: 2 desc: Port output data (y = 0..15)
ODR3: bool, // bit offset: 3 desc: Port output data (y = 0..15)
ODR4: bool, // bit offset: 4 desc: Port output data (y = 0..15)
ODR5: bool, // bit offset: 5 desc: Port output data (y = 0..15)
ODR6: bool, // bit offset: 6 desc: Port output data (y = 0..15)
ODR7: bool, // bit offset: 7 desc: Port output data (y = 0..15)
ODR8: bool, // bit offset: 8 desc: Port output data (y = 0..15)
ODR9: bool, // bit offset: 9 desc: Port output data (y = 0..15)
ODR10: bool, // bit offset: 10 desc: Port output data (y = 0..15)
ODR11: bool, // bit offset: 11 desc: Port output data (y = 0..15)
ODR12: bool, // bit offset: 12 desc: Port output data (y = 0..15)
ODR13: bool, // bit offset: 13 desc: Port output data (y = 0..15)
ODR14: bool, // bit offset: 14 desc: Port output data (y = 0..15)
ODR15: bool, // bit offset: 15 desc: Port output data (y = 0..15)
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const BSRR = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 GPIO port bit set/reset register
BS0: bool, // bit offset: 0 desc: Port x set bit y (y= 0..15)
BS1: bool, // bit offset: 1 desc: Port x set bit y (y= 0..15)
BS2: bool, // bit offset: 2 desc: Port x set bit y (y= 0..15)
BS3: bool, // bit offset: 3 desc: Port x set bit y (y= 0..15)
BS4: bool, // bit offset: 4 desc: Port x set bit y (y= 0..15)
BS5: bool, // bit offset: 5 desc: Port x set bit y (y= 0..15)
BS6: bool, // bit offset: 6 desc: Port x set bit y (y= 0..15)
BS7: bool, // bit offset: 7 desc: Port x set bit y (y= 0..15)
BS8: bool, // bit offset: 8 desc: Port x set bit y (y= 0..15)
BS9: bool, // bit offset: 9 desc: Port x set bit y (y= 0..15)
BS10: bool, // bit offset: 10 desc: Port x set bit y (y= 0..15)
BS11: bool, // bit offset: 11 desc: Port x set bit y (y= 0..15)
BS12: bool, // bit offset: 12 desc: Port x set bit y (y= 0..15)
BS13: bool, // bit offset: 13 desc: Port x set bit y (y= 0..15)
BS14: bool, // bit offset: 14 desc: Port x set bit y (y= 0..15)
BS15: bool, // bit offset: 15 desc: Port x set bit y (y= 0..15)
BR0: bool, // bit offset: 16 desc: Port x set bit y (y= 0..15)
BR1: bool, // bit offset: 17 desc: Port x reset bit y (y = 0..15)
BR2: bool, // bit offset: 18 desc: Port x reset bit y (y = 0..15)
BR3: bool, // bit offset: 19 desc: Port x reset bit y (y = 0..15)
BR4: bool, // bit offset: 20 desc: Port x reset bit y (y = 0..15)
BR5: bool, // bit offset: 21 desc: Port x reset bit y (y = 0..15)
BR6: bool, // bit offset: 22 desc: Port x reset bit y (y = 0..15)
BR7: bool, // bit offset: 23 desc: Port x reset bit y (y = 0..15)
BR8: bool, // bit offset: 24 desc: Port x reset bit y (y = 0..15)
BR9: bool, // bit offset: 25 desc: Port x reset bit y (y = 0..15)
BR10: bool, // bit offset: 26 desc: Port x reset bit y (y = 0..15)
BR11: bool, // bit offset: 27 desc: Port x reset bit y (y = 0..15)
BR12: bool, // bit offset: 28 desc: Port x reset bit y (y = 0..15)
BR13: bool, // bit offset: 29 desc: Port x reset bit y (y = 0..15)
BR14: bool, // bit offset: 30 desc: Port x reset bit y (y = 0..15)
BR15: bool, // bit offset: 31 desc: Port x reset bit y (y = 0..15)
});
pub const LCKR = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 GPIO port configuration lock register
LCK0: bool, // bit offset: 0 desc: Port x lock bit y (y= 0..15)
LCK1: bool, // bit offset: 1 desc: Port x lock bit y (y= 0..15)
LCK2: bool, // bit offset: 2 desc: Port x lock bit y (y= 0..15)
LCK3: bool, // bit offset: 3 desc: Port x lock bit y (y= 0..15)
LCK4: bool, // bit offset: 4 desc: Port x lock bit y (y= 0..15)
LCK5: bool, // bit offset: 5 desc: Port x lock bit y (y= 0..15)
LCK6: bool, // bit offset: 6 desc: Port x lock bit y (y= 0..15)
LCK7: bool, // bit offset: 7 desc: Port x lock bit y (y= 0..15)
LCK8: bool, // bit offset: 8 desc: Port x lock bit y (y= 0..15)
LCK9: bool, // bit offset: 9 desc: Port x lock bit y (y= 0..15)
LCK10: bool, // bit offset: 10 desc: Port x lock bit y (y= 0..15)
LCK11: bool, // bit offset: 11 desc: Port x lock bit y (y= 0..15)
LCK12: bool, // bit offset: 12 desc: Port x lock bit y (y= 0..15)
LCK13: bool, // bit offset: 13 desc: Port x lock bit y (y= 0..15)
LCK14: bool, // bit offset: 14 desc: Port x lock bit y (y= 0..15)
LCK15: bool, // bit offset: 15 desc: Port x lock bit y (y= 0..15)
LCKK: bool, // bit offset: 16 desc: Port x lock bit y (y= 0..15)
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const AFRL = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 GPIO alternate function low register
AFRL0: u4, // bit offset: 0 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL1: u4, // bit offset: 4 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL2: u4, // bit offset: 8 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL3: u4, // bit offset: 12 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL4: u4, // bit offset: 16 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL5: u4, // bit offset: 20 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL6: u4, // bit offset: 24 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL7: u4, // bit offset: 28 desc: Alternate function selection for port x bit y (y = 0..7)
});
pub const AFRH = MMIO(Address + 0x00000024, u32, packed struct { // byte offset: 36 GPIO alternate function high register
AFRH8: u4, // bit offset: 0 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH9: u4, // bit offset: 4 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH10: u4, // bit offset: 8 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH11: u4, // bit offset: 12 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH12: u4, // bit offset: 16 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH13: u4, // bit offset: 20 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH14: u4, // bit offset: 24 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH15: u4, // bit offset: 28 desc: Alternate function selection for port x bit y (y = 8..15)
});
};
pub const GPIOB = extern struct {
pub const Address: u32 = 0x40020400;
pub const MODER = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 GPIO port mode register
MODER0: u2, // bit offset: 0 desc: Port x configuration bits (y = 0..15)
MODER1: u2, // bit offset: 2 desc: Port x configuration bits (y = 0..15)
MODER2: u2, // bit offset: 4 desc: Port x configuration bits (y = 0..15)
MODER3: u2, // bit offset: 6 desc: Port x configuration bits (y = 0..15)
MODER4: u2, // bit offset: 8 desc: Port x configuration bits (y = 0..15)
MODER5: u2, // bit offset: 10 desc: Port x configuration bits (y = 0..15)
MODER6: u2, // bit offset: 12 desc: Port x configuration bits (y = 0..15)
MODER7: u2, // bit offset: 14 desc: Port x configuration bits (y = 0..15)
MODER8: u2, // bit offset: 16 desc: Port x configuration bits (y = 0..15)
MODER9: u2, // bit offset: 18 desc: Port x configuration bits (y = 0..15)
MODER10: u2, // bit offset: 20 desc: Port x configuration bits (y = 0..15)
MODER11: u2, // bit offset: 22 desc: Port x configuration bits (y = 0..15)
MODER12: u2, // bit offset: 24 desc: Port x configuration bits (y = 0..15)
MODER13: u2, // bit offset: 26 desc: Port x configuration bits (y = 0..15)
MODER14: u2, // bit offset: 28 desc: Port x configuration bits (y = 0..15)
MODER15: u2, // bit offset: 30 desc: Port x configuration bits (y = 0..15)
});
pub const OTYPER = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 GPIO port output type register
OT0: bool, // bit offset: 0 desc: Port x configuration bits (y = 0..15)
OT1: bool, // bit offset: 1 desc: Port x configuration bits (y = 0..15)
OT2: bool, // bit offset: 2 desc: Port x configuration bits (y = 0..15)
OT3: bool, // bit offset: 3 desc: Port x configuration bits (y = 0..15)
OT4: bool, // bit offset: 4 desc: Port x configuration bits (y = 0..15)
OT5: bool, // bit offset: 5 desc: Port x configuration bits (y = 0..15)
OT6: bool, // bit offset: 6 desc: Port x configuration bits (y = 0..15)
OT7: bool, // bit offset: 7 desc: Port x configuration bits (y = 0..15)
OT8: bool, // bit offset: 8 desc: Port x configuration bits (y = 0..15)
OT9: bool, // bit offset: 9 desc: Port x configuration bits (y = 0..15)
OT10: bool, // bit offset: 10 desc: Port x configuration bits (y = 0..15)
OT11: bool, // bit offset: 11 desc: Port x configuration bits (y = 0..15)
OT12: bool, // bit offset: 12 desc: Port x configuration bits (y = 0..15)
OT13: bool, // bit offset: 13 desc: Port x configuration bits (y = 0..15)
OT14: bool, // bit offset: 14 desc: Port x configuration bits (y = 0..15)
OT15: bool, // bit offset: 15 desc: Port x configuration bits (y = 0..15)
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const OSPEEDR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 GPIO port output speed register
OSPEEDR0: u2, // bit offset: 0 desc: Port x configuration bits (y = 0..15)
OSPEEDR1: u2, // bit offset: 2 desc: Port x configuration bits (y = 0..15)
OSPEEDR2: u2, // bit offset: 4 desc: Port x configuration bits (y = 0..15)
OSPEEDR3: u2, // bit offset: 6 desc: Port x configuration bits (y = 0..15)
OSPEEDR4: u2, // bit offset: 8 desc: Port x configuration bits (y = 0..15)
OSPEEDR5: u2, // bit offset: 10 desc: Port x configuration bits (y = 0..15)
OSPEEDR6: u2, // bit offset: 12 desc: Port x configuration bits (y = 0..15)
OSPEEDR7: u2, // bit offset: 14 desc: Port x configuration bits (y = 0..15)
OSPEEDR8: u2, // bit offset: 16 desc: Port x configuration bits (y = 0..15)
OSPEEDR9: u2, // bit offset: 18 desc: Port x configuration bits (y = 0..15)
OSPEEDR10: u2, // bit offset: 20 desc: Port x configuration bits (y = 0..15)
OSPEEDR11: u2, // bit offset: 22 desc: Port x configuration bits (y = 0..15)
OSPEEDR12: u2, // bit offset: 24 desc: Port x configuration bits (y = 0..15)
OSPEEDR13: u2, // bit offset: 26 desc: Port x configuration bits (y = 0..15)
OSPEEDR14: u2, // bit offset: 28 desc: Port x configuration bits (y = 0..15)
OSPEEDR15: u2, // bit offset: 30 desc: Port x configuration bits (y = 0..15)
});
pub const PUPDR = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 GPIO port pull-up/pull-down register
PUPDR0: u2, // bit offset: 0 desc: Port x configuration bits (y = 0..15)
PUPDR1: u2, // bit offset: 2 desc: Port x configuration bits (y = 0..15)
PUPDR2: u2, // bit offset: 4 desc: Port x configuration bits (y = 0..15)
PUPDR3: u2, // bit offset: 6 desc: Port x configuration bits (y = 0..15)
PUPDR4: u2, // bit offset: 8 desc: Port x configuration bits (y = 0..15)
PUPDR5: u2, // bit offset: 10 desc: Port x configuration bits (y = 0..15)
PUPDR6: u2, // bit offset: 12 desc: Port x configuration bits (y = 0..15)
PUPDR7: u2, // bit offset: 14 desc: Port x configuration bits (y = 0..15)
PUPDR8: u2, // bit offset: 16 desc: Port x configuration bits (y = 0..15)
PUPDR9: u2, // bit offset: 18 desc: Port x configuration bits (y = 0..15)
PUPDR10: u2, // bit offset: 20 desc: Port x configuration bits (y = 0..15)
PUPDR11: u2, // bit offset: 22 desc: Port x configuration bits (y = 0..15)
PUPDR12: u2, // bit offset: 24 desc: Port x configuration bits (y = 0..15)
PUPDR13: u2, // bit offset: 26 desc: Port x configuration bits (y = 0..15)
PUPDR14: u2, // bit offset: 28 desc: Port x configuration bits (y = 0..15)
PUPDR15: u2, // bit offset: 30 desc: Port x configuration bits (y = 0..15)
});
pub const IDR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 GPIO port input data register
IDR0: bool, // bit offset: 0 desc: Port input data (y = 0..15)
IDR1: bool, // bit offset: 1 desc: Port input data (y = 0..15)
IDR2: bool, // bit offset: 2 desc: Port input data (y = 0..15)
IDR3: bool, // bit offset: 3 desc: Port input data (y = 0..15)
IDR4: bool, // bit offset: 4 desc: Port input data (y = 0..15)
IDR5: bool, // bit offset: 5 desc: Port input data (y = 0..15)
IDR6: bool, // bit offset: 6 desc: Port input data (y = 0..15)
IDR7: bool, // bit offset: 7 desc: Port input data (y = 0..15)
IDR8: bool, // bit offset: 8 desc: Port input data (y = 0..15)
IDR9: bool, // bit offset: 9 desc: Port input data (y = 0..15)
IDR10: bool, // bit offset: 10 desc: Port input data (y = 0..15)
IDR11: bool, // bit offset: 11 desc: Port input data (y = 0..15)
IDR12: bool, // bit offset: 12 desc: Port input data (y = 0..15)
IDR13: bool, // bit offset: 13 desc: Port input data (y = 0..15)
IDR14: bool, // bit offset: 14 desc: Port input data (y = 0..15)
IDR15: bool, // bit offset: 15 desc: Port input data (y = 0..15)
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const ODR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 GPIO port output data register
ODR0: bool, // bit offset: 0 desc: Port output data (y = 0..15)
ODR1: bool, // bit offset: 1 desc: Port output data (y = 0..15)
ODR2: bool, // bit offset: 2 desc: Port output data (y = 0..15)
ODR3: bool, // bit offset: 3 desc: Port output data (y = 0..15)
ODR4: bool, // bit offset: 4 desc: Port output data (y = 0..15)
ODR5: bool, // bit offset: 5 desc: Port output data (y = 0..15)
ODR6: bool, // bit offset: 6 desc: Port output data (y = 0..15)
ODR7: bool, // bit offset: 7 desc: Port output data (y = 0..15)
ODR8: bool, // bit offset: 8 desc: Port output data (y = 0..15)
ODR9: bool, // bit offset: 9 desc: Port output data (y = 0..15)
ODR10: bool, // bit offset: 10 desc: Port output data (y = 0..15)
ODR11: bool, // bit offset: 11 desc: Port output data (y = 0..15)
ODR12: bool, // bit offset: 12 desc: Port output data (y = 0..15)
ODR13: bool, // bit offset: 13 desc: Port output data (y = 0..15)
ODR14: bool, // bit offset: 14 desc: Port output data (y = 0..15)
ODR15: bool, // bit offset: 15 desc: Port output data (y = 0..15)
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const BSRR = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 GPIO port bit set/reset register
BS0: bool, // bit offset: 0 desc: Port x set bit y (y= 0..15)
BS1: bool, // bit offset: 1 desc: Port x set bit y (y= 0..15)
BS2: bool, // bit offset: 2 desc: Port x set bit y (y= 0..15)
BS3: bool, // bit offset: 3 desc: Port x set bit y (y= 0..15)
BS4: bool, // bit offset: 4 desc: Port x set bit y (y= 0..15)
BS5: bool, // bit offset: 5 desc: Port x set bit y (y= 0..15)
BS6: bool, // bit offset: 6 desc: Port x set bit y (y= 0..15)
BS7: bool, // bit offset: 7 desc: Port x set bit y (y= 0..15)
BS8: bool, // bit offset: 8 desc: Port x set bit y (y= 0..15)
BS9: bool, // bit offset: 9 desc: Port x set bit y (y= 0..15)
BS10: bool, // bit offset: 10 desc: Port x set bit y (y= 0..15)
BS11: bool, // bit offset: 11 desc: Port x set bit y (y= 0..15)
BS12: bool, // bit offset: 12 desc: Port x set bit y (y= 0..15)
BS13: bool, // bit offset: 13 desc: Port x set bit y (y= 0..15)
BS14: bool, // bit offset: 14 desc: Port x set bit y (y= 0..15)
BS15: bool, // bit offset: 15 desc: Port x set bit y (y= 0..15)
BR0: bool, // bit offset: 16 desc: Port x set bit y (y= 0..15)
BR1: bool, // bit offset: 17 desc: Port x reset bit y (y = 0..15)
BR2: bool, // bit offset: 18 desc: Port x reset bit y (y = 0..15)
BR3: bool, // bit offset: 19 desc: Port x reset bit y (y = 0..15)
BR4: bool, // bit offset: 20 desc: Port x reset bit y (y = 0..15)
BR5: bool, // bit offset: 21 desc: Port x reset bit y (y = 0..15)
BR6: bool, // bit offset: 22 desc: Port x reset bit y (y = 0..15)
BR7: bool, // bit offset: 23 desc: Port x reset bit y (y = 0..15)
BR8: bool, // bit offset: 24 desc: Port x reset bit y (y = 0..15)
BR9: bool, // bit offset: 25 desc: Port x reset bit y (y = 0..15)
BR10: bool, // bit offset: 26 desc: Port x reset bit y (y = 0..15)
BR11: bool, // bit offset: 27 desc: Port x reset bit y (y = 0..15)
BR12: bool, // bit offset: 28 desc: Port x reset bit y (y = 0..15)
BR13: bool, // bit offset: 29 desc: Port x reset bit y (y = 0..15)
BR14: bool, // bit offset: 30 desc: Port x reset bit y (y = 0..15)
BR15: bool, // bit offset: 31 desc: Port x reset bit y (y = 0..15)
});
pub const LCKR = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 GPIO port configuration lock register
LCK0: bool, // bit offset: 0 desc: Port x lock bit y (y= 0..15)
LCK1: bool, // bit offset: 1 desc: Port x lock bit y (y= 0..15)
LCK2: bool, // bit offset: 2 desc: Port x lock bit y (y= 0..15)
LCK3: bool, // bit offset: 3 desc: Port x lock bit y (y= 0..15)
LCK4: bool, // bit offset: 4 desc: Port x lock bit y (y= 0..15)
LCK5: bool, // bit offset: 5 desc: Port x lock bit y (y= 0..15)
LCK6: bool, // bit offset: 6 desc: Port x lock bit y (y= 0..15)
LCK7: bool, // bit offset: 7 desc: Port x lock bit y (y= 0..15)
LCK8: bool, // bit offset: 8 desc: Port x lock bit y (y= 0..15)
LCK9: bool, // bit offset: 9 desc: Port x lock bit y (y= 0..15)
LCK10: bool, // bit offset: 10 desc: Port x lock bit y (y= 0..15)
LCK11: bool, // bit offset: 11 desc: Port x lock bit y (y= 0..15)
LCK12: bool, // bit offset: 12 desc: Port x lock bit y (y= 0..15)
LCK13: bool, // bit offset: 13 desc: Port x lock bit y (y= 0..15)
LCK14: bool, // bit offset: 14 desc: Port x lock bit y (y= 0..15)
LCK15: bool, // bit offset: 15 desc: Port x lock bit y (y= 0..15)
LCKK: bool, // bit offset: 16 desc: Port x lock bit y (y= 0..15)
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const AFRL = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 GPIO alternate function low register
AFRL0: u4, // bit offset: 0 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL1: u4, // bit offset: 4 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL2: u4, // bit offset: 8 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL3: u4, // bit offset: 12 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL4: u4, // bit offset: 16 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL5: u4, // bit offset: 20 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL6: u4, // bit offset: 24 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL7: u4, // bit offset: 28 desc: Alternate function selection for port x bit y (y = 0..7)
});
pub const AFRH = MMIO(Address + 0x00000024, u32, packed struct { // byte offset: 36 GPIO alternate function high register
AFRH8: u4, // bit offset: 0 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH9: u4, // bit offset: 4 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH10: u4, // bit offset: 8 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH11: u4, // bit offset: 12 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH12: u4, // bit offset: 16 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH13: u4, // bit offset: 20 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH14: u4, // bit offset: 24 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH15: u4, // bit offset: 28 desc: Alternate function selection for port x bit y (y = 8..15)
});
};
pub const GPIOA = extern struct {
pub const Address: u32 = 0x40020000;
pub const MODER = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 GPIO port mode register
MODER0: u2, // bit offset: 0 desc: Port x configuration bits (y = 0..15)
MODER1: u2, // bit offset: 2 desc: Port x configuration bits (y = 0..15)
MODER2: u2, // bit offset: 4 desc: Port x configuration bits (y = 0..15)
MODER3: u2, // bit offset: 6 desc: Port x configuration bits (y = 0..15)
MODER4: u2, // bit offset: 8 desc: Port x configuration bits (y = 0..15)
MODER5: u2, // bit offset: 10 desc: Port x configuration bits (y = 0..15)
MODER6: u2, // bit offset: 12 desc: Port x configuration bits (y = 0..15)
MODER7: u2, // bit offset: 14 desc: Port x configuration bits (y = 0..15)
MODER8: u2, // bit offset: 16 desc: Port x configuration bits (y = 0..15)
MODER9: u2, // bit offset: 18 desc: Port x configuration bits (y = 0..15)
MODER10: u2, // bit offset: 20 desc: Port x configuration bits (y = 0..15)
MODER11: u2, // bit offset: 22 desc: Port x configuration bits (y = 0..15)
MODER12: u2, // bit offset: 24 desc: Port x configuration bits (y = 0..15)
MODER13: u2, // bit offset: 26 desc: Port x configuration bits (y = 0..15)
MODER14: u2, // bit offset: 28 desc: Port x configuration bits (y = 0..15)
MODER15: u2, // bit offset: 30 desc: Port x configuration bits (y = 0..15)
});
pub const OTYPER = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 GPIO port output type register
OT0: bool, // bit offset: 0 desc: Port x configuration bits (y = 0..15)
OT1: bool, // bit offset: 1 desc: Port x configuration bits (y = 0..15)
OT2: bool, // bit offset: 2 desc: Port x configuration bits (y = 0..15)
OT3: bool, // bit offset: 3 desc: Port x configuration bits (y = 0..15)
OT4: bool, // bit offset: 4 desc: Port x configuration bits (y = 0..15)
OT5: bool, // bit offset: 5 desc: Port x configuration bits (y = 0..15)
OT6: bool, // bit offset: 6 desc: Port x configuration bits (y = 0..15)
OT7: bool, // bit offset: 7 desc: Port x configuration bits (y = 0..15)
OT8: bool, // bit offset: 8 desc: Port x configuration bits (y = 0..15)
OT9: bool, // bit offset: 9 desc: Port x configuration bits (y = 0..15)
OT10: bool, // bit offset: 10 desc: Port x configuration bits (y = 0..15)
OT11: bool, // bit offset: 11 desc: Port x configuration bits (y = 0..15)
OT12: bool, // bit offset: 12 desc: Port x configuration bits (y = 0..15)
OT13: bool, // bit offset: 13 desc: Port x configuration bits (y = 0..15)
OT14: bool, // bit offset: 14 desc: Port x configuration bits (y = 0..15)
OT15: bool, // bit offset: 15 desc: Port x configuration bits (y = 0..15)
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const OSPEEDR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 GPIO port output speed register
OSPEEDR0: u2, // bit offset: 0 desc: Port x configuration bits (y = 0..15)
OSPEEDR1: u2, // bit offset: 2 desc: Port x configuration bits (y = 0..15)
OSPEEDR2: u2, // bit offset: 4 desc: Port x configuration bits (y = 0..15)
OSPEEDR3: u2, // bit offset: 6 desc: Port x configuration bits (y = 0..15)
OSPEEDR4: u2, // bit offset: 8 desc: Port x configuration bits (y = 0..15)
OSPEEDR5: u2, // bit offset: 10 desc: Port x configuration bits (y = 0..15)
OSPEEDR6: u2, // bit offset: 12 desc: Port x configuration bits (y = 0..15)
OSPEEDR7: u2, // bit offset: 14 desc: Port x configuration bits (y = 0..15)
OSPEEDR8: u2, // bit offset: 16 desc: Port x configuration bits (y = 0..15)
OSPEEDR9: u2, // bit offset: 18 desc: Port x configuration bits (y = 0..15)
OSPEEDR10: u2, // bit offset: 20 desc: Port x configuration bits (y = 0..15)
OSPEEDR11: u2, // bit offset: 22 desc: Port x configuration bits (y = 0..15)
OSPEEDR12: u2, // bit offset: 24 desc: Port x configuration bits (y = 0..15)
OSPEEDR13: u2, // bit offset: 26 desc: Port x configuration bits (y = 0..15)
OSPEEDR14: u2, // bit offset: 28 desc: Port x configuration bits (y = 0..15)
OSPEEDR15: u2, // bit offset: 30 desc: Port x configuration bits (y = 0..15)
});
pub const PUPDR = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 GPIO port pull-up/pull-down register
PUPDR0: u2, // bit offset: 0 desc: Port x configuration bits (y = 0..15)
PUPDR1: u2, // bit offset: 2 desc: Port x configuration bits (y = 0..15)
PUPDR2: u2, // bit offset: 4 desc: Port x configuration bits (y = 0..15)
PUPDR3: u2, // bit offset: 6 desc: Port x configuration bits (y = 0..15)
PUPDR4: u2, // bit offset: 8 desc: Port x configuration bits (y = 0..15)
PUPDR5: u2, // bit offset: 10 desc: Port x configuration bits (y = 0..15)
PUPDR6: u2, // bit offset: 12 desc: Port x configuration bits (y = 0..15)
PUPDR7: u2, // bit offset: 14 desc: Port x configuration bits (y = 0..15)
PUPDR8: u2, // bit offset: 16 desc: Port x configuration bits (y = 0..15)
PUPDR9: u2, // bit offset: 18 desc: Port x configuration bits (y = 0..15)
PUPDR10: u2, // bit offset: 20 desc: Port x configuration bits (y = 0..15)
PUPDR11: u2, // bit offset: 22 desc: Port x configuration bits (y = 0..15)
PUPDR12: u2, // bit offset: 24 desc: Port x configuration bits (y = 0..15)
PUPDR13: u2, // bit offset: 26 desc: Port x configuration bits (y = 0..15)
PUPDR14: u2, // bit offset: 28 desc: Port x configuration bits (y = 0..15)
PUPDR15: u2, // bit offset: 30 desc: Port x configuration bits (y = 0..15)
});
pub const IDR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 GPIO port input data register
IDR0: bool, // bit offset: 0 desc: Port input data (y = 0..15)
IDR1: bool, // bit offset: 1 desc: Port input data (y = 0..15)
IDR2: bool, // bit offset: 2 desc: Port input data (y = 0..15)
IDR3: bool, // bit offset: 3 desc: Port input data (y = 0..15)
IDR4: bool, // bit offset: 4 desc: Port input data (y = 0..15)
IDR5: bool, // bit offset: 5 desc: Port input data (y = 0..15)
IDR6: bool, // bit offset: 6 desc: Port input data (y = 0..15)
IDR7: bool, // bit offset: 7 desc: Port input data (y = 0..15)
IDR8: bool, // bit offset: 8 desc: Port input data (y = 0..15)
IDR9: bool, // bit offset: 9 desc: Port input data (y = 0..15)
IDR10: bool, // bit offset: 10 desc: Port input data (y = 0..15)
IDR11: bool, // bit offset: 11 desc: Port input data (y = 0..15)
IDR12: bool, // bit offset: 12 desc: Port input data (y = 0..15)
IDR13: bool, // bit offset: 13 desc: Port input data (y = 0..15)
IDR14: bool, // bit offset: 14 desc: Port input data (y = 0..15)
IDR15: bool, // bit offset: 15 desc: Port input data (y = 0..15)
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const ODR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 GPIO port output data register
ODR0: bool, // bit offset: 0 desc: Port output data (y = 0..15)
ODR1: bool, // bit offset: 1 desc: Port output data (y = 0..15)
ODR2: bool, // bit offset: 2 desc: Port output data (y = 0..15)
ODR3: bool, // bit offset: 3 desc: Port output data (y = 0..15)
ODR4: bool, // bit offset: 4 desc: Port output data (y = 0..15)
ODR5: bool, // bit offset: 5 desc: Port output data (y = 0..15)
ODR6: bool, // bit offset: 6 desc: Port output data (y = 0..15)
ODR7: bool, // bit offset: 7 desc: Port output data (y = 0..15)
ODR8: bool, // bit offset: 8 desc: Port output data (y = 0..15)
ODR9: bool, // bit offset: 9 desc: Port output data (y = 0..15)
ODR10: bool, // bit offset: 10 desc: Port output data (y = 0..15)
ODR11: bool, // bit offset: 11 desc: Port output data (y = 0..15)
ODR12: bool, // bit offset: 12 desc: Port output data (y = 0..15)
ODR13: bool, // bit offset: 13 desc: Port output data (y = 0..15)
ODR14: bool, // bit offset: 14 desc: Port output data (y = 0..15)
ODR15: bool, // bit offset: 15 desc: Port output data (y = 0..15)
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const BSRR = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 GPIO port bit set/reset register
BS0: bool, // bit offset: 0 desc: Port x set bit y (y= 0..15)
BS1: bool, // bit offset: 1 desc: Port x set bit y (y= 0..15)
BS2: bool, // bit offset: 2 desc: Port x set bit y (y= 0..15)
BS3: bool, // bit offset: 3 desc: Port x set bit y (y= 0..15)
BS4: bool, // bit offset: 4 desc: Port x set bit y (y= 0..15)
BS5: bool, // bit offset: 5 desc: Port x set bit y (y= 0..15)
BS6: bool, // bit offset: 6 desc: Port x set bit y (y= 0..15)
BS7: bool, // bit offset: 7 desc: Port x set bit y (y= 0..15)
BS8: bool, // bit offset: 8 desc: Port x set bit y (y= 0..15)
BS9: bool, // bit offset: 9 desc: Port x set bit y (y= 0..15)
BS10: bool, // bit offset: 10 desc: Port x set bit y (y= 0..15)
BS11: bool, // bit offset: 11 desc: Port x set bit y (y= 0..15)
BS12: bool, // bit offset: 12 desc: Port x set bit y (y= 0..15)
BS13: bool, // bit offset: 13 desc: Port x set bit y (y= 0..15)
BS14: bool, // bit offset: 14 desc: Port x set bit y (y= 0..15)
BS15: bool, // bit offset: 15 desc: Port x set bit y (y= 0..15)
BR0: bool, // bit offset: 16 desc: Port x set bit y (y= 0..15)
BR1: bool, // bit offset: 17 desc: Port x reset bit y (y = 0..15)
BR2: bool, // bit offset: 18 desc: Port x reset bit y (y = 0..15)
BR3: bool, // bit offset: 19 desc: Port x reset bit y (y = 0..15)
BR4: bool, // bit offset: 20 desc: Port x reset bit y (y = 0..15)
BR5: bool, // bit offset: 21 desc: Port x reset bit y (y = 0..15)
BR6: bool, // bit offset: 22 desc: Port x reset bit y (y = 0..15)
BR7: bool, // bit offset: 23 desc: Port x reset bit y (y = 0..15)
BR8: bool, // bit offset: 24 desc: Port x reset bit y (y = 0..15)
BR9: bool, // bit offset: 25 desc: Port x reset bit y (y = 0..15)
BR10: bool, // bit offset: 26 desc: Port x reset bit y (y = 0..15)
BR11: bool, // bit offset: 27 desc: Port x reset bit y (y = 0..15)
BR12: bool, // bit offset: 28 desc: Port x reset bit y (y = 0..15)
BR13: bool, // bit offset: 29 desc: Port x reset bit y (y = 0..15)
BR14: bool, // bit offset: 30 desc: Port x reset bit y (y = 0..15)
BR15: bool, // bit offset: 31 desc: Port x reset bit y (y = 0..15)
});
pub const LCKR = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 GPIO port configuration lock register
LCK0: bool, // bit offset: 0 desc: Port x lock bit y (y= 0..15)
LCK1: bool, // bit offset: 1 desc: Port x lock bit y (y= 0..15)
LCK2: bool, // bit offset: 2 desc: Port x lock bit y (y= 0..15)
LCK3: bool, // bit offset: 3 desc: Port x lock bit y (y= 0..15)
LCK4: bool, // bit offset: 4 desc: Port x lock bit y (y= 0..15)
LCK5: bool, // bit offset: 5 desc: Port x lock bit y (y= 0..15)
LCK6: bool, // bit offset: 6 desc: Port x lock bit y (y= 0..15)
LCK7: bool, // bit offset: 7 desc: Port x lock bit y (y= 0..15)
LCK8: bool, // bit offset: 8 desc: Port x lock bit y (y= 0..15)
LCK9: bool, // bit offset: 9 desc: Port x lock bit y (y= 0..15)
LCK10: bool, // bit offset: 10 desc: Port x lock bit y (y= 0..15)
LCK11: bool, // bit offset: 11 desc: Port x lock bit y (y= 0..15)
LCK12: bool, // bit offset: 12 desc: Port x lock bit y (y= 0..15)
LCK13: bool, // bit offset: 13 desc: Port x lock bit y (y= 0..15)
LCK14: bool, // bit offset: 14 desc: Port x lock bit y (y= 0..15)
LCK15: bool, // bit offset: 15 desc: Port x lock bit y (y= 0..15)
LCKK: bool, // bit offset: 16 desc: Port x lock bit y (y= 0..15)
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const AFRL = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 GPIO alternate function low register
AFRL0: u4, // bit offset: 0 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL1: u4, // bit offset: 4 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL2: u4, // bit offset: 8 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL3: u4, // bit offset: 12 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL4: u4, // bit offset: 16 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL5: u4, // bit offset: 20 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL6: u4, // bit offset: 24 desc: Alternate function selection for port x bit y (y = 0..7)
AFRL7: u4, // bit offset: 28 desc: Alternate function selection for port x bit y (y = 0..7)
});
pub const AFRH = MMIO(Address + 0x00000024, u32, packed struct { // byte offset: 36 GPIO alternate function high register
AFRH8: u4, // bit offset: 0 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH9: u4, // bit offset: 4 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH10: u4, // bit offset: 8 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH11: u4, // bit offset: 12 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH12: u4, // bit offset: 16 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH13: u4, // bit offset: 20 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH14: u4, // bit offset: 24 desc: Alternate function selection for port x bit y (y = 8..15)
AFRH15: u4, // bit offset: 28 desc: Alternate function selection for port x bit y (y = 8..15)
});
};
pub const I2C3 = extern struct {
pub const Address: u32 = 0x40005c00;
pub const CR1 = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 Control register 1
PE: bool, // bit offset: 0 desc: Peripheral enable
SMBUS: bool, // bit offset: 1 desc: SMBus mode
reserved0: u1 = 0,
SMBTYPE: bool, // bit offset: 3 desc: SMBus type
ENARP: bool, // bit offset: 4 desc: ARP enable
ENPEC: bool, // bit offset: 5 desc: PEC enable
ENGC: bool, // bit offset: 6 desc: General call enable
NOSTRETCH: bool, // bit offset: 7 desc: Clock stretching disable (Slave mode)
START: bool, // bit offset: 8 desc: Start generation
STOP: bool, // bit offset: 9 desc: Stop generation
ACK: bool, // bit offset: 10 desc: Acknowledge enable
POS: bool, // bit offset: 11 desc: Acknowledge/PEC Position (for data reception)
PEC: bool, // bit offset: 12 desc: Packet error checking
ALERT: bool, // bit offset: 13 desc: SMBus alert
reserved1: u1 = 0,
SWRST: bool, // bit offset: 15 desc: Software reset
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR2 = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 Control register 2
FREQ: u6, // bit offset: 0 desc: Peripheral clock frequency
reserved0: u2 = 0,
ITERREN: bool, // bit offset: 8 desc: Error interrupt enable
ITEVTEN: bool, // bit offset: 9 desc: Event interrupt enable
ITBUFEN: bool, // bit offset: 10 desc: Buffer interrupt enable
DMAEN: bool, // bit offset: 11 desc: DMA requests enable
LAST: bool, // bit offset: 12 desc: DMA last transfer
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const OAR1 = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 Own address register 1
ADD0: bool, // bit offset: 0 desc: Interface address
ADD7: u7, // bit offset: 1 desc: Interface address
ADD10: u2, // bit offset: 8 desc: Interface address
reserved0: u5 = 0,
ADDMODE: bool, // bit offset: 15 desc: Addressing mode (slave mode)
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const OAR2 = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 Own address register 2
ENDUAL: bool, // bit offset: 0 desc: Dual addressing mode enable
ADD2: u7, // bit offset: 1 desc: Interface address
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 Data register
DR: u8, // bit offset: 0 desc: 8-bit data register
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SR1 = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 Status register 1
SB: bool, // bit offset: 0 desc: Start bit (Master mode)
ADDR: bool, // bit offset: 1 desc: Address sent (master mode)/matched (slave mode)
BTF: bool, // bit offset: 2 desc: Byte transfer finished
ADD10: bool, // bit offset: 3 desc: 10-bit header sent (Master mode)
STOPF: bool, // bit offset: 4 desc: Stop detection (slave mode)
reserved0: u1 = 0,
RxNE: bool, // bit offset: 6 desc: Data register not empty (receivers)
TxE: bool, // bit offset: 7 desc: Data register empty (transmitters)
BERR: bool, // bit offset: 8 desc: Bus error
ARLO: bool, // bit offset: 9 desc: Arbitration lost (master mode)
AF: bool, // bit offset: 10 desc: Acknowledge failure
OVR: bool, // bit offset: 11 desc: Overrun/Underrun
PECERR: bool, // bit offset: 12 desc: PEC Error in reception
reserved1: u1 = 0,
TIMEOUT: bool, // bit offset: 14 desc: Timeout or Tlow error
SMBALERT: bool, // bit offset: 15 desc: SMBus alert
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SR2 = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 Status register 2
MSL: bool, // bit offset: 0 desc: Master/slave
BUSY: bool, // bit offset: 1 desc: Bus busy
TRA: bool, // bit offset: 2 desc: Transmitter/receiver
reserved0: u1 = 0,
GENCALL: bool, // bit offset: 4 desc: General call address (Slave mode)
SMBDEFAULT: bool, // bit offset: 5 desc: SMBus device default address (Slave mode)
SMBHOST: bool, // bit offset: 6 desc: SMBus host header (Slave mode)
DUALF: bool, // bit offset: 7 desc: Dual flag (Slave mode)
PEC: u8, // bit offset: 8 desc: acket error checking register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCR = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 Clock control register
CCR: u12, // bit offset: 0 desc: Clock control register in Fast/Standard mode (Master mode)
reserved0: u2 = 0,
DUTY: bool, // bit offset: 14 desc: Fast mode duty cycle
F_S: bool, // bit offset: 15 desc: I2C master mode selection
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const TRISE = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 TRISE register
TRISE: u6, // bit offset: 0 desc: Maximum rise time in Fast/Standard mode (Master mode)
padding26: u1 = 0,
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const I2C2 = extern struct {
pub const Address: u32 = 0x40005800;
pub const CR1 = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 Control register 1
PE: bool, // bit offset: 0 desc: Peripheral enable
SMBUS: bool, // bit offset: 1 desc: SMBus mode
reserved0: u1 = 0,
SMBTYPE: bool, // bit offset: 3 desc: SMBus type
ENARP: bool, // bit offset: 4 desc: ARP enable
ENPEC: bool, // bit offset: 5 desc: PEC enable
ENGC: bool, // bit offset: 6 desc: General call enable
NOSTRETCH: bool, // bit offset: 7 desc: Clock stretching disable (Slave mode)
START: bool, // bit offset: 8 desc: Start generation
STOP: bool, // bit offset: 9 desc: Stop generation
ACK: bool, // bit offset: 10 desc: Acknowledge enable
POS: bool, // bit offset: 11 desc: Acknowledge/PEC Position (for data reception)
PEC: bool, // bit offset: 12 desc: Packet error checking
ALERT: bool, // bit offset: 13 desc: SMBus alert
reserved1: u1 = 0,
SWRST: bool, // bit offset: 15 desc: Software reset
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR2 = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 Control register 2
FREQ: u6, // bit offset: 0 desc: Peripheral clock frequency
reserved0: u2 = 0,
ITERREN: bool, // bit offset: 8 desc: Error interrupt enable
ITEVTEN: bool, // bit offset: 9 desc: Event interrupt enable
ITBUFEN: bool, // bit offset: 10 desc: Buffer interrupt enable
DMAEN: bool, // bit offset: 11 desc: DMA requests enable
LAST: bool, // bit offset: 12 desc: DMA last transfer
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const OAR1 = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 Own address register 1
ADD0: bool, // bit offset: 0 desc: Interface address
ADD7: u7, // bit offset: 1 desc: Interface address
ADD10: u2, // bit offset: 8 desc: Interface address
reserved0: u5 = 0,
ADDMODE: bool, // bit offset: 15 desc: Addressing mode (slave mode)
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const OAR2 = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 Own address register 2
ENDUAL: bool, // bit offset: 0 desc: Dual addressing mode enable
ADD2: u7, // bit offset: 1 desc: Interface address
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 Data register
DR: u8, // bit offset: 0 desc: 8-bit data register
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SR1 = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 Status register 1
SB: bool, // bit offset: 0 desc: Start bit (Master mode)
ADDR: bool, // bit offset: 1 desc: Address sent (master mode)/matched (slave mode)
BTF: bool, // bit offset: 2 desc: Byte transfer finished
ADD10: bool, // bit offset: 3 desc: 10-bit header sent (Master mode)
STOPF: bool, // bit offset: 4 desc: Stop detection (slave mode)
reserved0: u1 = 0,
RxNE: bool, // bit offset: 6 desc: Data register not empty (receivers)
TxE: bool, // bit offset: 7 desc: Data register empty (transmitters)
BERR: bool, // bit offset: 8 desc: Bus error
ARLO: bool, // bit offset: 9 desc: Arbitration lost (master mode)
AF: bool, // bit offset: 10 desc: Acknowledge failure
OVR: bool, // bit offset: 11 desc: Overrun/Underrun
PECERR: bool, // bit offset: 12 desc: PEC Error in reception
reserved1: u1 = 0,
TIMEOUT: bool, // bit offset: 14 desc: Timeout or Tlow error
SMBALERT: bool, // bit offset: 15 desc: SMBus alert
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SR2 = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 Status register 2
MSL: bool, // bit offset: 0 desc: Master/slave
BUSY: bool, // bit offset: 1 desc: Bus busy
TRA: bool, // bit offset: 2 desc: Transmitter/receiver
reserved0: u1 = 0,
GENCALL: bool, // bit offset: 4 desc: General call address (Slave mode)
SMBDEFAULT: bool, // bit offset: 5 desc: SMBus device default address (Slave mode)
SMBHOST: bool, // bit offset: 6 desc: SMBus host header (Slave mode)
DUALF: bool, // bit offset: 7 desc: Dual flag (Slave mode)
PEC: u8, // bit offset: 8 desc: acket error checking register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCR = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 Clock control register
CCR: u12, // bit offset: 0 desc: Clock control register in Fast/Standard mode (Master mode)
reserved0: u2 = 0,
DUTY: bool, // bit offset: 14 desc: Fast mode duty cycle
F_S: bool, // bit offset: 15 desc: I2C master mode selection
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const TRISE = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 TRISE register
TRISE: u6, // bit offset: 0 desc: Maximum rise time in Fast/Standard mode (Master mode)
padding26: u1 = 0,
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const I2C1 = extern struct {
pub const Address: u32 = 0x40005400;
pub const CR1 = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 Control register 1
PE: bool, // bit offset: 0 desc: Peripheral enable
SMBUS: bool, // bit offset: 1 desc: SMBus mode
reserved0: u1 = 0,
SMBTYPE: bool, // bit offset: 3 desc: SMBus type
ENARP: bool, // bit offset: 4 desc: ARP enable
ENPEC: bool, // bit offset: 5 desc: PEC enable
ENGC: bool, // bit offset: 6 desc: General call enable
NOSTRETCH: bool, // bit offset: 7 desc: Clock stretching disable (Slave mode)
START: bool, // bit offset: 8 desc: Start generation
STOP: bool, // bit offset: 9 desc: Stop generation
ACK: bool, // bit offset: 10 desc: Acknowledge enable
POS: bool, // bit offset: 11 desc: Acknowledge/PEC Position (for data reception)
PEC: bool, // bit offset: 12 desc: Packet error checking
ALERT: bool, // bit offset: 13 desc: SMBus alert
reserved1: u1 = 0,
SWRST: bool, // bit offset: 15 desc: Software reset
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR2 = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 Control register 2
FREQ: u6, // bit offset: 0 desc: Peripheral clock frequency
reserved0: u2 = 0,
ITERREN: bool, // bit offset: 8 desc: Error interrupt enable
ITEVTEN: bool, // bit offset: 9 desc: Event interrupt enable
ITBUFEN: bool, // bit offset: 10 desc: Buffer interrupt enable
DMAEN: bool, // bit offset: 11 desc: DMA requests enable
LAST: bool, // bit offset: 12 desc: DMA last transfer
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const OAR1 = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 Own address register 1
ADD0: bool, // bit offset: 0 desc: Interface address
ADD7: u7, // bit offset: 1 desc: Interface address
ADD10: u2, // bit offset: 8 desc: Interface address
reserved0: u5 = 0,
ADDMODE: bool, // bit offset: 15 desc: Addressing mode (slave mode)
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const OAR2 = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 Own address register 2
ENDUAL: bool, // bit offset: 0 desc: Dual addressing mode enable
ADD2: u7, // bit offset: 1 desc: Interface address
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 Data register
DR: u8, // bit offset: 0 desc: 8-bit data register
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SR1 = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 Status register 1
SB: bool, // bit offset: 0 desc: Start bit (Master mode)
ADDR: bool, // bit offset: 1 desc: Address sent (master mode)/matched (slave mode)
BTF: bool, // bit offset: 2 desc: Byte transfer finished
ADD10: bool, // bit offset: 3 desc: 10-bit header sent (Master mode)
STOPF: bool, // bit offset: 4 desc: Stop detection (slave mode)
reserved0: u1 = 0,
RxNE: bool, // bit offset: 6 desc: Data register not empty (receivers)
TxE: bool, // bit offset: 7 desc: Data register empty (transmitters)
BERR: bool, // bit offset: 8 desc: Bus error
ARLO: bool, // bit offset: 9 desc: Arbitration lost (master mode)
AF: bool, // bit offset: 10 desc: Acknowledge failure
OVR: bool, // bit offset: 11 desc: Overrun/Underrun
PECERR: bool, // bit offset: 12 desc: PEC Error in reception
reserved1: u1 = 0,
TIMEOUT: bool, // bit offset: 14 desc: Timeout or Tlow error
SMBALERT: bool, // bit offset: 15 desc: SMBus alert
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SR2 = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 Status register 2
MSL: bool, // bit offset: 0 desc: Master/slave
BUSY: bool, // bit offset: 1 desc: Bus busy
TRA: bool, // bit offset: 2 desc: Transmitter/receiver
reserved0: u1 = 0,
GENCALL: bool, // bit offset: 4 desc: General call address (Slave mode)
SMBDEFAULT: bool, // bit offset: 5 desc: SMBus device default address (Slave mode)
SMBHOST: bool, // bit offset: 6 desc: SMBus host header (Slave mode)
DUALF: bool, // bit offset: 7 desc: Dual flag (Slave mode)
PEC: u8, // bit offset: 8 desc: acket error checking register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCR = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 Clock control register
CCR: u12, // bit offset: 0 desc: Clock control register in Fast/Standard mode (Master mode)
reserved0: u2 = 0,
DUTY: bool, // bit offset: 14 desc: Fast mode duty cycle
F_S: bool, // bit offset: 15 desc: I2C master mode selection
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const TRISE = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 TRISE register
TRISE: u6, // bit offset: 0 desc: Maximum rise time in Fast/Standard mode (Master mode)
padding26: u1 = 0,
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const I2S2ext = extern struct {
pub const Address: u32 = 0x40003400;
pub const CR1 = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 control register 1
CPHA: bool, // bit offset: 0 desc: Clock phase
CPOL: bool, // bit offset: 1 desc: Clock polarity
MSTR: bool, // bit offset: 2 desc: Master selection
BR: u3, // bit offset: 3 desc: Baud rate control
SPE: bool, // bit offset: 6 desc: SPI enable
LSBFIRST: bool, // bit offset: 7 desc: Frame format
SSI: bool, // bit offset: 8 desc: Internal slave select
SSM: bool, // bit offset: 9 desc: Software slave management
RXONLY: bool, // bit offset: 10 desc: Receive only
DFF: bool, // bit offset: 11 desc: Data frame format
CRCNEXT: bool, // bit offset: 12 desc: CRC transfer next
CRCEN: bool, // bit offset: 13 desc: Hardware CRC calculation enable
BIDIOE: bool, // bit offset: 14 desc: Output enable in bidirectional mode
BIDIMODE: bool, // bit offset: 15 desc: Bidirectional data mode enable
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR2 = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 control register 2
RXDMAEN: bool, // bit offset: 0 desc: Rx buffer DMA enable
TXDMAEN: bool, // bit offset: 1 desc: Tx buffer DMA enable
SSOE: bool, // bit offset: 2 desc: SS output enable
reserved0: u1 = 0,
FRF: bool, // bit offset: 4 desc: Frame format
ERRIE: bool, // bit offset: 5 desc: Error interrupt enable
RXNEIE: bool, // bit offset: 6 desc: RX buffer not empty interrupt enable
TXEIE: bool, // bit offset: 7 desc: Tx buffer empty interrupt enable
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 status register
RXNE: bool, // bit offset: 0 desc: Receive buffer not empty
TXE: bool, // bit offset: 1 desc: Transmit buffer empty
CHSIDE: bool, // bit offset: 2 desc: Channel side
UDR: bool, // bit offset: 3 desc: Underrun flag
CRCERR: bool, // bit offset: 4 desc: CRC error flag
MODF: bool, // bit offset: 5 desc: Mode fault
OVR: bool, // bit offset: 6 desc: Overrun flag
BSY: bool, // bit offset: 7 desc: Busy flag
TIFRFE: bool, // bit offset: 8 desc: TI frame format error
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DR = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 data register
DR: u16, // bit offset: 0 desc: Data register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CRCPR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 CRC polynomial register
CRCPOLY: u16, // bit offset: 0 desc: CRC polynomial register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const RXCRCR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 RX CRC register
RxCRC: u16, // bit offset: 0 desc: Rx CRC register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const TXCRCR = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 TX CRC register
TxCRC: u16, // bit offset: 0 desc: Tx CRC register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const I2SCFGR = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 I2S configuration register
CHLEN: bool, // bit offset: 0 desc: Channel length (number of bits per audio channel)
DATLEN: u2, // bit offset: 1 desc: Data length to be transferred
CKPOL: bool, // bit offset: 3 desc: Steady state clock polarity
I2SSTD: u2, // bit offset: 4 desc: I2S standard selection
reserved0: u1 = 0,
PCMSYNC: bool, // bit offset: 7 desc: PCM frame synchronization
I2SCFG: u2, // bit offset: 8 desc: I2S configuration mode
I2SE: bool, // bit offset: 10 desc: I2S Enable
I2SMOD: bool, // bit offset: 11 desc: I2S mode selection
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const I2SPR = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 I2S prescaler register
I2SDIV: u8, // bit offset: 0 desc: I2S Linear prescaler
ODD: bool, // bit offset: 8 desc: Odd factor for the prescaler
MCKOE: bool, // bit offset: 9 desc: Master clock output enable
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const I2S3ext = extern struct {
pub const Address: u32 = 0x40004000;
pub const CR1 = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 control register 1
CPHA: bool, // bit offset: 0 desc: Clock phase
CPOL: bool, // bit offset: 1 desc: Clock polarity
MSTR: bool, // bit offset: 2 desc: Master selection
BR: u3, // bit offset: 3 desc: Baud rate control
SPE: bool, // bit offset: 6 desc: SPI enable
LSBFIRST: bool, // bit offset: 7 desc: Frame format
SSI: bool, // bit offset: 8 desc: Internal slave select
SSM: bool, // bit offset: 9 desc: Software slave management
RXONLY: bool, // bit offset: 10 desc: Receive only
DFF: bool, // bit offset: 11 desc: Data frame format
CRCNEXT: bool, // bit offset: 12 desc: CRC transfer next
CRCEN: bool, // bit offset: 13 desc: Hardware CRC calculation enable
BIDIOE: bool, // bit offset: 14 desc: Output enable in bidirectional mode
BIDIMODE: bool, // bit offset: 15 desc: Bidirectional data mode enable
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR2 = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 control register 2
RXDMAEN: bool, // bit offset: 0 desc: Rx buffer DMA enable
TXDMAEN: bool, // bit offset: 1 desc: Tx buffer DMA enable
SSOE: bool, // bit offset: 2 desc: SS output enable
reserved0: u1 = 0,
FRF: bool, // bit offset: 4 desc: Frame format
ERRIE: bool, // bit offset: 5 desc: Error interrupt enable
RXNEIE: bool, // bit offset: 6 desc: RX buffer not empty interrupt enable
TXEIE: bool, // bit offset: 7 desc: Tx buffer empty interrupt enable
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 status register
RXNE: bool, // bit offset: 0 desc: Receive buffer not empty
TXE: bool, // bit offset: 1 desc: Transmit buffer empty
CHSIDE: bool, // bit offset: 2 desc: Channel side
UDR: bool, // bit offset: 3 desc: Underrun flag
CRCERR: bool, // bit offset: 4 desc: CRC error flag
MODF: bool, // bit offset: 5 desc: Mode fault
OVR: bool, // bit offset: 6 desc: Overrun flag
BSY: bool, // bit offset: 7 desc: Busy flag
TIFRFE: bool, // bit offset: 8 desc: TI frame format error
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DR = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 data register
DR: u16, // bit offset: 0 desc: Data register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CRCPR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 CRC polynomial register
CRCPOLY: u16, // bit offset: 0 desc: CRC polynomial register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const RXCRCR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 RX CRC register
RxCRC: u16, // bit offset: 0 desc: Rx CRC register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const TXCRCR = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 TX CRC register
TxCRC: u16, // bit offset: 0 desc: Tx CRC register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const I2SCFGR = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 I2S configuration register
CHLEN: bool, // bit offset: 0 desc: Channel length (number of bits per audio channel)
DATLEN: u2, // bit offset: 1 desc: Data length to be transferred
CKPOL: bool, // bit offset: 3 desc: Steady state clock polarity
I2SSTD: u2, // bit offset: 4 desc: I2S standard selection
reserved0: u1 = 0,
PCMSYNC: bool, // bit offset: 7 desc: PCM frame synchronization
I2SCFG: u2, // bit offset: 8 desc: I2S configuration mode
I2SE: bool, // bit offset: 10 desc: I2S Enable
I2SMOD: bool, // bit offset: 11 desc: I2S mode selection
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const I2SPR = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 I2S prescaler register
I2SDIV: u8, // bit offset: 0 desc: I2S Linear prescaler
ODD: bool, // bit offset: 8 desc: Odd factor for the prescaler
MCKOE: bool, // bit offset: 9 desc: Master clock output enable
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const SPI1 = extern struct {
pub const Address: u32 = 0x40013000;
pub const CR1 = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 control register 1
CPHA: bool, // bit offset: 0 desc: Clock phase
CPOL: bool, // bit offset: 1 desc: Clock polarity
MSTR: bool, // bit offset: 2 desc: Master selection
BR: u3, // bit offset: 3 desc: Baud rate control
SPE: bool, // bit offset: 6 desc: SPI enable
LSBFIRST: bool, // bit offset: 7 desc: Frame format
SSI: bool, // bit offset: 8 desc: Internal slave select
SSM: bool, // bit offset: 9 desc: Software slave management
RXONLY: bool, // bit offset: 10 desc: Receive only
DFF: bool, // bit offset: 11 desc: Data frame format
CRCNEXT: bool, // bit offset: 12 desc: CRC transfer next
CRCEN: bool, // bit offset: 13 desc: Hardware CRC calculation enable
BIDIOE: bool, // bit offset: 14 desc: Output enable in bidirectional mode
BIDIMODE: bool, // bit offset: 15 desc: Bidirectional data mode enable
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR2 = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 control register 2
RXDMAEN: bool, // bit offset: 0 desc: Rx buffer DMA enable
TXDMAEN: bool, // bit offset: 1 desc: Tx buffer DMA enable
SSOE: bool, // bit offset: 2 desc: SS output enable
reserved0: u1 = 0,
FRF: bool, // bit offset: 4 desc: Frame format
ERRIE: bool, // bit offset: 5 desc: Error interrupt enable
RXNEIE: bool, // bit offset: 6 desc: RX buffer not empty interrupt enable
TXEIE: bool, // bit offset: 7 desc: Tx buffer empty interrupt enable
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 status register
RXNE: bool, // bit offset: 0 desc: Receive buffer not empty
TXE: bool, // bit offset: 1 desc: Transmit buffer empty
CHSIDE: bool, // bit offset: 2 desc: Channel side
UDR: bool, // bit offset: 3 desc: Underrun flag
CRCERR: bool, // bit offset: 4 desc: CRC error flag
MODF: bool, // bit offset: 5 desc: Mode fault
OVR: bool, // bit offset: 6 desc: Overrun flag
BSY: bool, // bit offset: 7 desc: Busy flag
TIFRFE: bool, // bit offset: 8 desc: TI frame format error
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DR = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 data register
DR: u16, // bit offset: 0 desc: Data register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CRCPR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 CRC polynomial register
CRCPOLY: u16, // bit offset: 0 desc: CRC polynomial register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const RXCRCR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 RX CRC register
RxCRC: u16, // bit offset: 0 desc: Rx CRC register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const TXCRCR = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 TX CRC register
TxCRC: u16, // bit offset: 0 desc: Tx CRC register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const I2SCFGR = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 I2S configuration register
CHLEN: bool, // bit offset: 0 desc: Channel length (number of bits per audio channel)
DATLEN: u2, // bit offset: 1 desc: Data length to be transferred
CKPOL: bool, // bit offset: 3 desc: Steady state clock polarity
I2SSTD: u2, // bit offset: 4 desc: I2S standard selection
reserved0: u1 = 0,
PCMSYNC: bool, // bit offset: 7 desc: PCM frame synchronization
I2SCFG: u2, // bit offset: 8 desc: I2S configuration mode
I2SE: bool, // bit offset: 10 desc: I2S Enable
I2SMOD: bool, // bit offset: 11 desc: I2S mode selection
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const I2SPR = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 I2S prescaler register
I2SDIV: u8, // bit offset: 0 desc: I2S Linear prescaler
ODD: bool, // bit offset: 8 desc: Odd factor for the prescaler
MCKOE: bool, // bit offset: 9 desc: Master clock output enable
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const SPI2 = extern struct {
pub const Address: u32 = 0x40003800;
pub const CR1 = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 control register 1
CPHA: bool, // bit offset: 0 desc: Clock phase
CPOL: bool, // bit offset: 1 desc: Clock polarity
MSTR: bool, // bit offset: 2 desc: Master selection
BR: u3, // bit offset: 3 desc: Baud rate control
SPE: bool, // bit offset: 6 desc: SPI enable
LSBFIRST: bool, // bit offset: 7 desc: Frame format
SSI: bool, // bit offset: 8 desc: Internal slave select
SSM: bool, // bit offset: 9 desc: Software slave management
RXONLY: bool, // bit offset: 10 desc: Receive only
DFF: bool, // bit offset: 11 desc: Data frame format
CRCNEXT: bool, // bit offset: 12 desc: CRC transfer next
CRCEN: bool, // bit offset: 13 desc: Hardware CRC calculation enable
BIDIOE: bool, // bit offset: 14 desc: Output enable in bidirectional mode
BIDIMODE: bool, // bit offset: 15 desc: Bidirectional data mode enable
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR2 = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 control register 2
RXDMAEN: bool, // bit offset: 0 desc: Rx buffer DMA enable
TXDMAEN: bool, // bit offset: 1 desc: Tx buffer DMA enable
SSOE: bool, // bit offset: 2 desc: SS output enable
reserved0: u1 = 0,
FRF: bool, // bit offset: 4 desc: Frame format
ERRIE: bool, // bit offset: 5 desc: Error interrupt enable
RXNEIE: bool, // bit offset: 6 desc: RX buffer not empty interrupt enable
TXEIE: bool, // bit offset: 7 desc: Tx buffer empty interrupt enable
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 status register
RXNE: bool, // bit offset: 0 desc: Receive buffer not empty
TXE: bool, // bit offset: 1 desc: Transmit buffer empty
CHSIDE: bool, // bit offset: 2 desc: Channel side
UDR: bool, // bit offset: 3 desc: Underrun flag
CRCERR: bool, // bit offset: 4 desc: CRC error flag
MODF: bool, // bit offset: 5 desc: Mode fault
OVR: bool, // bit offset: 6 desc: Overrun flag
BSY: bool, // bit offset: 7 desc: Busy flag
TIFRFE: bool, // bit offset: 8 desc: TI frame format error
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DR = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 data register
DR: u16, // bit offset: 0 desc: Data register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CRCPR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 CRC polynomial register
CRCPOLY: u16, // bit offset: 0 desc: CRC polynomial register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const RXCRCR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 RX CRC register
RxCRC: u16, // bit offset: 0 desc: Rx CRC register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const TXCRCR = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 TX CRC register
TxCRC: u16, // bit offset: 0 desc: Tx CRC register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const I2SCFGR = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 I2S configuration register
CHLEN: bool, // bit offset: 0 desc: Channel length (number of bits per audio channel)
DATLEN: u2, // bit offset: 1 desc: Data length to be transferred
CKPOL: bool, // bit offset: 3 desc: Steady state clock polarity
I2SSTD: u2, // bit offset: 4 desc: I2S standard selection
reserved0: u1 = 0,
PCMSYNC: bool, // bit offset: 7 desc: PCM frame synchronization
I2SCFG: u2, // bit offset: 8 desc: I2S configuration mode
I2SE: bool, // bit offset: 10 desc: I2S Enable
I2SMOD: bool, // bit offset: 11 desc: I2S mode selection
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const I2SPR = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 I2S prescaler register
I2SDIV: u8, // bit offset: 0 desc: I2S Linear prescaler
ODD: bool, // bit offset: 8 desc: Odd factor for the prescaler
MCKOE: bool, // bit offset: 9 desc: Master clock output enable
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const SPI3 = extern struct {
pub const Address: u32 = 0x40003c00;
pub const CR1 = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 control register 1
CPHA: bool, // bit offset: 0 desc: Clock phase
CPOL: bool, // bit offset: 1 desc: Clock polarity
MSTR: bool, // bit offset: 2 desc: Master selection
BR: u3, // bit offset: 3 desc: Baud rate control
SPE: bool, // bit offset: 6 desc: SPI enable
LSBFIRST: bool, // bit offset: 7 desc: Frame format
SSI: bool, // bit offset: 8 desc: Internal slave select
SSM: bool, // bit offset: 9 desc: Software slave management
RXONLY: bool, // bit offset: 10 desc: Receive only
DFF: bool, // bit offset: 11 desc: Data frame format
CRCNEXT: bool, // bit offset: 12 desc: CRC transfer next
CRCEN: bool, // bit offset: 13 desc: Hardware CRC calculation enable
BIDIOE: bool, // bit offset: 14 desc: Output enable in bidirectional mode
BIDIMODE: bool, // bit offset: 15 desc: Bidirectional data mode enable
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR2 = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 control register 2
RXDMAEN: bool, // bit offset: 0 desc: Rx buffer DMA enable
TXDMAEN: bool, // bit offset: 1 desc: Tx buffer DMA enable
SSOE: bool, // bit offset: 2 desc: SS output enable
reserved0: u1 = 0,
FRF: bool, // bit offset: 4 desc: Frame format
ERRIE: bool, // bit offset: 5 desc: Error interrupt enable
RXNEIE: bool, // bit offset: 6 desc: RX buffer not empty interrupt enable
TXEIE: bool, // bit offset: 7 desc: Tx buffer empty interrupt enable
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 status register
RXNE: bool, // bit offset: 0 desc: Receive buffer not empty
TXE: bool, // bit offset: 1 desc: Transmit buffer empty
CHSIDE: bool, // bit offset: 2 desc: Channel side
UDR: bool, // bit offset: 3 desc: Underrun flag
CRCERR: bool, // bit offset: 4 desc: CRC error flag
MODF: bool, // bit offset: 5 desc: Mode fault
OVR: bool, // bit offset: 6 desc: Overrun flag
BSY: bool, // bit offset: 7 desc: Busy flag
TIFRFE: bool, // bit offset: 8 desc: TI frame format error
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DR = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 data register
DR: u16, // bit offset: 0 desc: Data register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CRCPR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 CRC polynomial register
CRCPOLY: u16, // bit offset: 0 desc: CRC polynomial register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const RXCRCR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 RX CRC register
RxCRC: u16, // bit offset: 0 desc: Rx CRC register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const TXCRCR = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 TX CRC register
TxCRC: u16, // bit offset: 0 desc: Tx CRC register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const I2SCFGR = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 I2S configuration register
CHLEN: bool, // bit offset: 0 desc: Channel length (number of bits per audio channel)
DATLEN: u2, // bit offset: 1 desc: Data length to be transferred
CKPOL: bool, // bit offset: 3 desc: Steady state clock polarity
I2SSTD: u2, // bit offset: 4 desc: I2S standard selection
reserved0: u1 = 0,
PCMSYNC: bool, // bit offset: 7 desc: PCM frame synchronization
I2SCFG: u2, // bit offset: 8 desc: I2S configuration mode
I2SE: bool, // bit offset: 10 desc: I2S Enable
I2SMOD: bool, // bit offset: 11 desc: I2S mode selection
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const I2SPR = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 I2S prescaler register
I2SDIV: u8, // bit offset: 0 desc: I2S Linear prescaler
ODD: bool, // bit offset: 8 desc: Odd factor for the prescaler
MCKOE: bool, // bit offset: 9 desc: Master clock output enable
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const SPI4 = extern struct {
pub const Address: u32 = 0x40013400;
pub const CR1 = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 control register 1
CPHA: bool, // bit offset: 0 desc: Clock phase
CPOL: bool, // bit offset: 1 desc: Clock polarity
MSTR: bool, // bit offset: 2 desc: Master selection
BR: u3, // bit offset: 3 desc: Baud rate control
SPE: bool, // bit offset: 6 desc: SPI enable
LSBFIRST: bool, // bit offset: 7 desc: Frame format
SSI: bool, // bit offset: 8 desc: Internal slave select
SSM: bool, // bit offset: 9 desc: Software slave management
RXONLY: bool, // bit offset: 10 desc: Receive only
DFF: bool, // bit offset: 11 desc: Data frame format
CRCNEXT: bool, // bit offset: 12 desc: CRC transfer next
CRCEN: bool, // bit offset: 13 desc: Hardware CRC calculation enable
BIDIOE: bool, // bit offset: 14 desc: Output enable in bidirectional mode
BIDIMODE: bool, // bit offset: 15 desc: Bidirectional data mode enable
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR2 = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 control register 2
RXDMAEN: bool, // bit offset: 0 desc: Rx buffer DMA enable
TXDMAEN: bool, // bit offset: 1 desc: Tx buffer DMA enable
SSOE: bool, // bit offset: 2 desc: SS output enable
reserved0: u1 = 0,
FRF: bool, // bit offset: 4 desc: Frame format
ERRIE: bool, // bit offset: 5 desc: Error interrupt enable
RXNEIE: bool, // bit offset: 6 desc: RX buffer not empty interrupt enable
TXEIE: bool, // bit offset: 7 desc: Tx buffer empty interrupt enable
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 status register
RXNE: bool, // bit offset: 0 desc: Receive buffer not empty
TXE: bool, // bit offset: 1 desc: Transmit buffer empty
CHSIDE: bool, // bit offset: 2 desc: Channel side
UDR: bool, // bit offset: 3 desc: Underrun flag
CRCERR: bool, // bit offset: 4 desc: CRC error flag
MODF: bool, // bit offset: 5 desc: Mode fault
OVR: bool, // bit offset: 6 desc: Overrun flag
BSY: bool, // bit offset: 7 desc: Busy flag
TIFRFE: bool, // bit offset: 8 desc: TI frame format error
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DR = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 data register
DR: u16, // bit offset: 0 desc: Data register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CRCPR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 CRC polynomial register
CRCPOLY: u16, // bit offset: 0 desc: CRC polynomial register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const RXCRCR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 RX CRC register
RxCRC: u16, // bit offset: 0 desc: Rx CRC register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const TXCRCR = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 TX CRC register
TxCRC: u16, // bit offset: 0 desc: Tx CRC register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const I2SCFGR = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 I2S configuration register
CHLEN: bool, // bit offset: 0 desc: Channel length (number of bits per audio channel)
DATLEN: u2, // bit offset: 1 desc: Data length to be transferred
CKPOL: bool, // bit offset: 3 desc: Steady state clock polarity
I2SSTD: u2, // bit offset: 4 desc: I2S standard selection
reserved0: u1 = 0,
PCMSYNC: bool, // bit offset: 7 desc: PCM frame synchronization
I2SCFG: u2, // bit offset: 8 desc: I2S configuration mode
I2SE: bool, // bit offset: 10 desc: I2S Enable
I2SMOD: bool, // bit offset: 11 desc: I2S mode selection
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const I2SPR = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 I2S prescaler register
I2SDIV: u8, // bit offset: 0 desc: I2S Linear prescaler
ODD: bool, // bit offset: 8 desc: Odd factor for the prescaler
MCKOE: bool, // bit offset: 9 desc: Master clock output enable
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const SPI5 = extern struct {
pub const Address: u32 = 0x40015000;
pub const CR1 = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 control register 1
CPHA: bool, // bit offset: 0 desc: Clock phase
CPOL: bool, // bit offset: 1 desc: Clock polarity
MSTR: bool, // bit offset: 2 desc: Master selection
BR: u3, // bit offset: 3 desc: Baud rate control
SPE: bool, // bit offset: 6 desc: SPI enable
LSBFIRST: bool, // bit offset: 7 desc: Frame format
SSI: bool, // bit offset: 8 desc: Internal slave select
SSM: bool, // bit offset: 9 desc: Software slave management
RXONLY: bool, // bit offset: 10 desc: Receive only
DFF: bool, // bit offset: 11 desc: Data frame format
CRCNEXT: bool, // bit offset: 12 desc: CRC transfer next
CRCEN: bool, // bit offset: 13 desc: Hardware CRC calculation enable
BIDIOE: bool, // bit offset: 14 desc: Output enable in bidirectional mode
BIDIMODE: bool, // bit offset: 15 desc: Bidirectional data mode enable
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CR2 = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 control register 2
RXDMAEN: bool, // bit offset: 0 desc: Rx buffer DMA enable
TXDMAEN: bool, // bit offset: 1 desc: Tx buffer DMA enable
SSOE: bool, // bit offset: 2 desc: SS output enable
reserved0: u1 = 0,
FRF: bool, // bit offset: 4 desc: Frame format
ERRIE: bool, // bit offset: 5 desc: Error interrupt enable
RXNEIE: bool, // bit offset: 6 desc: RX buffer not empty interrupt enable
TXEIE: bool, // bit offset: 7 desc: Tx buffer empty interrupt enable
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 status register
RXNE: bool, // bit offset: 0 desc: Receive buffer not empty
TXE: bool, // bit offset: 1 desc: Transmit buffer empty
CHSIDE: bool, // bit offset: 2 desc: Channel side
UDR: bool, // bit offset: 3 desc: Underrun flag
CRCERR: bool, // bit offset: 4 desc: CRC error flag
MODF: bool, // bit offset: 5 desc: Mode fault
OVR: bool, // bit offset: 6 desc: Overrun flag
BSY: bool, // bit offset: 7 desc: Busy flag
TIFRFE: bool, // bit offset: 8 desc: TI frame format error
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const DR = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 data register
DR: u16, // bit offset: 0 desc: Data register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CRCPR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 CRC polynomial register
CRCPOLY: u16, // bit offset: 0 desc: CRC polynomial register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const RXCRCR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 RX CRC register
RxCRC: u16, // bit offset: 0 desc: Rx CRC register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const TXCRCR = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 TX CRC register
TxCRC: u16, // bit offset: 0 desc: Tx CRC register
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const I2SCFGR = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 I2S configuration register
CHLEN: bool, // bit offset: 0 desc: Channel length (number of bits per audio channel)
DATLEN: u2, // bit offset: 1 desc: Data length to be transferred
CKPOL: bool, // bit offset: 3 desc: Steady state clock polarity
I2SSTD: u2, // bit offset: 4 desc: I2S standard selection
reserved0: u1 = 0,
PCMSYNC: bool, // bit offset: 7 desc: PCM frame synchronization
I2SCFG: u2, // bit offset: 8 desc: I2S configuration mode
I2SE: bool, // bit offset: 10 desc: I2S Enable
I2SMOD: bool, // bit offset: 11 desc: I2S mode selection
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const I2SPR = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 I2S prescaler register
I2SDIV: u8, // bit offset: 0 desc: I2S Linear prescaler
ODD: bool, // bit offset: 8 desc: Odd factor for the prescaler
MCKOE: bool, // bit offset: 9 desc: Master clock output enable
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const NVIC = extern struct {
pub const Address: u32 = 0xe000e100;
pub const ISER0 = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 Interrupt Set-Enable Register
SETENA: u32, // bit offset: 0 desc: SETENA
});
pub const ISER1 = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 Interrupt Set-Enable Register
SETENA: u32, // bit offset: 0 desc: SETENA
});
pub const ISER2 = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 Interrupt Set-Enable Register
SETENA: u32, // bit offset: 0 desc: SETENA
});
pub const ICER0 = MMIO(Address + 0x00000080, u32, packed struct { // byte offset: 128 Interrupt Clear-Enable Register
CLRENA: u32, // bit offset: 0 desc: CLRENA
});
pub const ICER1 = MMIO(Address + 0x00000084, u32, packed struct { // byte offset: 132 Interrupt Clear-Enable Register
CLRENA: u32, // bit offset: 0 desc: CLRENA
});
pub const ICER2 = MMIO(Address + 0x00000088, u32, packed struct { // byte offset: 136 Interrupt Clear-Enable Register
CLRENA: u32, // bit offset: 0 desc: CLRENA
});
pub const ISPR0 = MMIO(Address + 0x00000100, u32, packed struct { // byte offset: 256 Interrupt Set-Pending Register
SETPEND: u32, // bit offset: 0 desc: SETPEND
});
pub const ISPR1 = MMIO(Address + 0x00000104, u32, packed struct { // byte offset: 260 Interrupt Set-Pending Register
SETPEND: u32, // bit offset: 0 desc: SETPEND
});
pub const ISPR2 = MMIO(Address + 0x00000108, u32, packed struct { // byte offset: 264 Interrupt Set-Pending Register
SETPEND: u32, // bit offset: 0 desc: SETPEND
});
pub const ICPR0 = MMIO(Address + 0x00000180, u32, packed struct { // byte offset: 384 Interrupt Clear-Pending Register
CLRPEND: u32, // bit offset: 0 desc: CLRPEND
});
pub const ICPR1 = MMIO(Address + 0x00000184, u32, packed struct { // byte offset: 388 Interrupt Clear-Pending Register
CLRPEND: u32, // bit offset: 0 desc: CLRPEND
});
pub const ICPR2 = MMIO(Address + 0x00000188, u32, packed struct { // byte offset: 392 Interrupt Clear-Pending Register
CLRPEND: u32, // bit offset: 0 desc: CLRPEND
});
pub const IABR0 = MMIO(Address + 0x00000200, u32, packed struct { // byte offset: 512 Interrupt Active Bit Register
ACTIVE: u32, // bit offset: 0 desc: ACTIVE
});
pub const IABR1 = MMIO(Address + 0x00000204, u32, packed struct { // byte offset: 516 Interrupt Active Bit Register
ACTIVE: u32, // bit offset: 0 desc: ACTIVE
});
pub const IABR2 = MMIO(Address + 0x00000208, u32, packed struct { // byte offset: 520 Interrupt Active Bit Register
ACTIVE: u32, // bit offset: 0 desc: ACTIVE
});
pub const IPR0 = MMIO(Address + 0x00000300, u32, packed struct { // byte offset: 768 Interrupt Priority Register
IPR_N0: u8, // bit offset: 0 desc: IPR_N0
IPR_N1: u8, // bit offset: 8 desc: IPR_N1
IPR_N2: u8, // bit offset: 16 desc: IPR_N2
IPR_N3: u8, // bit offset: 24 desc: IPR_N3
});
pub const IPR1 = MMIO(Address + 0x00000304, u32, packed struct { // byte offset: 772 Interrupt Priority Register
IPR_N0: u8, // bit offset: 0 desc: IPR_N0
IPR_N1: u8, // bit offset: 8 desc: IPR_N1
IPR_N2: u8, // bit offset: 16 desc: IPR_N2
IPR_N3: u8, // bit offset: 24 desc: IPR_N3
});
pub const IPR2 = MMIO(Address + 0x00000308, u32, packed struct { // byte offset: 776 Interrupt Priority Register
IPR_N0: u8, // bit offset: 0 desc: IPR_N0
IPR_N1: u8, // bit offset: 8 desc: IPR_N1
IPR_N2: u8, // bit offset: 16 desc: IPR_N2
IPR_N3: u8, // bit offset: 24 desc: IPR_N3
});
pub const IPR3 = MMIO(Address + 0x0000030c, u32, packed struct { // byte offset: 780 Interrupt Priority Register
IPR_N0: u8, // bit offset: 0 desc: IPR_N0
IPR_N1: u8, // bit offset: 8 desc: IPR_N1
IPR_N2: u8, // bit offset: 16 desc: IPR_N2
IPR_N3: u8, // bit offset: 24 desc: IPR_N3
});
pub const IPR4 = MMIO(Address + 0x00000310, u32, packed struct { // byte offset: 784 Interrupt Priority Register
IPR_N0: u8, // bit offset: 0 desc: IPR_N0
IPR_N1: u8, // bit offset: 8 desc: IPR_N1
IPR_N2: u8, // bit offset: 16 desc: IPR_N2
IPR_N3: u8, // bit offset: 24 desc: IPR_N3
});
pub const IPR5 = MMIO(Address + 0x00000314, u32, packed struct { // byte offset: 788 Interrupt Priority Register
IPR_N0: u8, // bit offset: 0 desc: IPR_N0
IPR_N1: u8, // bit offset: 8 desc: IPR_N1
IPR_N2: u8, // bit offset: 16 desc: IPR_N2
IPR_N3: u8, // bit offset: 24 desc: IPR_N3
});
pub const IPR6 = MMIO(Address + 0x00000318, u32, packed struct { // byte offset: 792 Interrupt Priority Register
IPR_N0: u8, // bit offset: 0 desc: IPR_N0
IPR_N1: u8, // bit offset: 8 desc: IPR_N1
IPR_N2: u8, // bit offset: 16 desc: IPR_N2
IPR_N3: u8, // bit offset: 24 desc: IPR_N3
});
pub const IPR7 = MMIO(Address + 0x0000031c, u32, packed struct { // byte offset: 796 Interrupt Priority Register
IPR_N0: u8, // bit offset: 0 desc: IPR_N0
IPR_N1: u8, // bit offset: 8 desc: IPR_N1
IPR_N2: u8, // bit offset: 16 desc: IPR_N2
IPR_N3: u8, // bit offset: 24 desc: IPR_N3
});
pub const IPR8 = MMIO(Address + 0x00000320, u32, packed struct { // byte offset: 800 Interrupt Priority Register
IPR_N0: u8, // bit offset: 0 desc: IPR_N0
IPR_N1: u8, // bit offset: 8 desc: IPR_N1
IPR_N2: u8, // bit offset: 16 desc: IPR_N2
IPR_N3: u8, // bit offset: 24 desc: IPR_N3
});
pub const IPR9 = MMIO(Address + 0x00000324, u32, packed struct { // byte offset: 804 Interrupt Priority Register
IPR_N0: u8, // bit offset: 0 desc: IPR_N0
IPR_N1: u8, // bit offset: 8 desc: IPR_N1
IPR_N2: u8, // bit offset: 16 desc: IPR_N2
IPR_N3: u8, // bit offset: 24 desc: IPR_N3
});
pub const IPR10 = MMIO(Address + 0x00000328, u32, packed struct { // byte offset: 808 Interrupt Priority Register
IPR_N0: u8, // bit offset: 0 desc: IPR_N0
IPR_N1: u8, // bit offset: 8 desc: IPR_N1
IPR_N2: u8, // bit offset: 16 desc: IPR_N2
IPR_N3: u8, // bit offset: 24 desc: IPR_N3
});
pub const IPR11 = MMIO(Address + 0x0000032c, u32, packed struct { // byte offset: 812 Interrupt Priority Register
IPR_N0: u8, // bit offset: 0 desc: IPR_N0
IPR_N1: u8, // bit offset: 8 desc: IPR_N1
IPR_N2: u8, // bit offset: 16 desc: IPR_N2
IPR_N3: u8, // bit offset: 24 desc: IPR_N3
});
pub const IPR12 = MMIO(Address + 0x00000330, u32, packed struct { // byte offset: 816 Interrupt Priority Register
IPR_N0: u8, // bit offset: 0 desc: IPR_N0
IPR_N1: u8, // bit offset: 8 desc: IPR_N1
IPR_N2: u8, // bit offset: 16 desc: IPR_N2
IPR_N3: u8, // bit offset: 24 desc: IPR_N3
});
pub const IPR13 = MMIO(Address + 0x00000334, u32, packed struct { // byte offset: 820 Interrupt Priority Register
IPR_N0: u8, // bit offset: 0 desc: IPR_N0
IPR_N1: u8, // bit offset: 8 desc: IPR_N1
IPR_N2: u8, // bit offset: 16 desc: IPR_N2
IPR_N3: u8, // bit offset: 24 desc: IPR_N3
});
pub const IPR14 = MMIO(Address + 0x00000338, u32, packed struct { // byte offset: 824 Interrupt Priority Register
IPR_N0: u8, // bit offset: 0 desc: IPR_N0
IPR_N1: u8, // bit offset: 8 desc: IPR_N1
IPR_N2: u8, // bit offset: 16 desc: IPR_N2
IPR_N3: u8, // bit offset: 24 desc: IPR_N3
});
pub const IPR15 = MMIO(Address + 0x0000033c, u32, packed struct { // byte offset: 828 Interrupt Priority Register
IPR_N0: u8, // bit offset: 0 desc: IPR_N0
IPR_N1: u8, // bit offset: 8 desc: IPR_N1
IPR_N2: u8, // bit offset: 16 desc: IPR_N2
IPR_N3: u8, // bit offset: 24 desc: IPR_N3
});
pub const IPR16 = MMIO(Address + 0x00000340, u32, packed struct { // byte offset: 832 Interrupt Priority Register
IPR_N0: u8, // bit offset: 0 desc: IPR_N0
IPR_N1: u8, // bit offset: 8 desc: IPR_N1
IPR_N2: u8, // bit offset: 16 desc: IPR_N2
IPR_N3: u8, // bit offset: 24 desc: IPR_N3
});
pub const IPR17 = MMIO(Address + 0x00000344, u32, packed struct { // byte offset: 836 Interrupt Priority Register
IPR_N0: u8, // bit offset: 0 desc: IPR_N0
IPR_N1: u8, // bit offset: 8 desc: IPR_N1
IPR_N2: u8, // bit offset: 16 desc: IPR_N2
IPR_N3: u8, // bit offset: 24 desc: IPR_N3
});
pub const IPR18 = MMIO(Address + 0x00000348, u32, packed struct { // byte offset: 840 Interrupt Priority Register
IPR_N0: u8, // bit offset: 0 desc: IPR_N0
IPR_N1: u8, // bit offset: 8 desc: IPR_N1
IPR_N2: u8, // bit offset: 16 desc: IPR_N2
IPR_N3: u8, // bit offset: 24 desc: IPR_N3
});
pub const IPR19 = MMIO(Address + 0x0000034c, u32, packed struct { // byte offset: 844 Interrupt Priority Register
IPR_N0: u8, // bit offset: 0 desc: IPR_N0
IPR_N1: u8, // bit offset: 8 desc: IPR_N1
IPR_N2: u8, // bit offset: 16 desc: IPR_N2
IPR_N3: u8, // bit offset: 24 desc: IPR_N3
});
};
pub const FPU = extern struct {
pub const Address: u32 = 0xe000ef34;
pub const FPCCR = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 Floating-point context control register
LSPACT: bool, // bit offset: 0 desc: LSPACT
USER: bool, // bit offset: 1 desc: USER
reserved0: u1 = 0,
THREAD: bool, // bit offset: 3 desc: THREAD
HFRDY: bool, // bit offset: 4 desc: HFRDY
MMRDY: bool, // bit offset: 5 desc: MMRDY
BFRDY: bool, // bit offset: 6 desc: BFRDY
reserved1: u1 = 0,
MONRDY: bool, // bit offset: 8 desc: MONRDY
reserved2: u21 = 0,
LSPEN: bool, // bit offset: 30 desc: LSPEN
ASPEN: bool, // bit offset: 31 desc: ASPEN
});
pub const FPCAR = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 Floating-point context address register
reserved0: u3 = 0,
ADDRESS: u29, // bit offset: 3 desc: Location of unpopulated floating-point
});
pub const FPSCR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 Floating-point status control register
IOC: bool, // bit offset: 0 desc: Invalid operation cumulative exception bit
DZC: bool, // bit offset: 1 desc: Division by zero cumulative exception bit.
OFC: bool, // bit offset: 2 desc: Overflow cumulative exception bit
UFC: bool, // bit offset: 3 desc: Underflow cumulative exception bit
IXC: bool, // bit offset: 4 desc: Inexact cumulative exception bit
reserved0: u2 = 0,
IDC: bool, // bit offset: 7 desc: Input denormal cumulative exception bit.
reserved1: u14 = 0,
RMode: u2, // bit offset: 22 desc: Rounding Mode control field
FZ: bool, // bit offset: 24 desc: Flush-to-zero mode control bit:
DN: bool, // bit offset: 25 desc: Default NaN mode control bit
AHP: bool, // bit offset: 26 desc: Alternative half-precision control bit
reserved2: u1 = 0,
V: bool, // bit offset: 28 desc: Overflow condition code flag
C: bool, // bit offset: 29 desc: Carry condition code flag
Z: bool, // bit offset: 30 desc: Zero condition code flag
N: bool, // bit offset: 31 desc: Negative condition code flag
});
};
pub const MPU = extern struct {
pub const Address: u32 = 0xe000ed90;
pub const MPU_TYPER = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 MPU type register
SEPARATE: bool, // bit offset: 0 desc: Separate flag
reserved0: u7 = 0,
DREGION: u8, // bit offset: 8 desc: Number of MPU data regions
IREGION: u8, // bit offset: 16 desc: Number of MPU instruction regions
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const MPU_CTRL = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 MPU control register
ENABLE: bool, // bit offset: 0 desc: Enables the MPU
HFNMIENA: bool, // bit offset: 1 desc: Enables the operation of MPU during hard fault
PRIVDEFENA: bool, // bit offset: 2 desc: Enable priviliged software access to default memory map
padding29: u1 = 0,
padding28: u1 = 0,
padding27: u1 = 0,
padding26: u1 = 0,
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const MPU_RNR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 MPU region number register
REGION: u8, // bit offset: 0 desc: MPU region
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const MPU_RBAR = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 MPU region base address register
REGION: u4, // bit offset: 0 desc: MPU region field
VALID: bool, // bit offset: 4 desc: MPU region number valid
ADDR: u27, // bit offset: 5 desc: Region base address field
});
pub const MPU_RASR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 MPU region attribute and size register
ENABLE: bool, // bit offset: 0 desc: Region enable bit.
SIZE: u5, // bit offset: 1 desc: Size of the MPU protection region
reserved0: u2 = 0,
SRD: u8, // bit offset: 8 desc: Subregion disable bits
B: bool, // bit offset: 16 desc: memory attribute
C: bool, // bit offset: 17 desc: memory attribute
S: bool, // bit offset: 18 desc: Shareable memory attribute
TEX: u3, // bit offset: 19 desc: memory attribute
reserved1: u2 = 0,
AP: u3, // bit offset: 24 desc: Access permission
reserved2: u1 = 0,
XN: bool, // bit offset: 28 desc: Instruction access disable bit
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const STK = extern struct {
pub const Address: u32 = 0xe000e010;
pub const CTRL = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 SysTick control and status register
ENABLE: bool, // bit offset: 0 desc: Counter enable
TICKINT: bool, // bit offset: 1 desc: SysTick exception request enable
CLKSOURCE: bool, // bit offset: 2 desc: Clock source selection
reserved0: u13 = 0,
COUNTFLAG: bool, // bit offset: 16 desc: COUNTFLAG
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const LOAD = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 SysTick reload value register
RELOAD: u24, // bit offset: 0 desc: RELOAD value
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const VAL = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 SysTick current value register
CURRENT: u24, // bit offset: 0 desc: Current counter value
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CALIB = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 SysTick calibration value register
TENMS: u24, // bit offset: 0 desc: Calibration value
reserved0: u6 = 0,
SKEW: bool, // bit offset: 30 desc: SKEW flag: Indicates whether the TENMS value is exact
NOREF: bool, // bit offset: 31 desc: NOREF flag. Reads as zero
});
};
pub const SCB = extern struct {
pub const Address: u32 = 0xe000ed00;
pub const CPUID = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 CPUID base register
Revision: u4, // bit offset: 0 desc: Revision number
PartNo: u12, // bit offset: 4 desc: Part number of the processor
Constant: u4, // bit offset: 16 desc: Reads as 0xF
Variant: u4, // bit offset: 20 desc: Variant number
Implementer: u8, // bit offset: 24 desc: Implementer code
});
pub const ICSR = MMIO(Address + 0x00000004, u32, packed struct { // byte offset: 4 Interrupt control and state register
VECTACTIVE: u9, // bit offset: 0 desc: Active vector
reserved0: u2 = 0,
RETTOBASE: bool, // bit offset: 11 desc: Return to base level
VECTPENDING: u7, // bit offset: 12 desc: Pending vector
reserved1: u3 = 0,
ISRPENDING: bool, // bit offset: 22 desc: Interrupt pending flag
reserved2: u2 = 0,
PENDSTCLR: bool, // bit offset: 25 desc: SysTick exception clear-pending bit
PENDSTSET: bool, // bit offset: 26 desc: SysTick exception set-pending bit
PENDSVCLR: bool, // bit offset: 27 desc: PendSV clear-pending bit
PENDSVSET: bool, // bit offset: 28 desc: PendSV set-pending bit
reserved3: u2 = 0,
NMIPENDSET: bool, // bit offset: 31 desc: NMI set-pending bit.
});
pub const VTOR = MMIO(Address + 0x00000008, u32, packed struct { // byte offset: 8 Vector table offset register
reserved0: u9 = 0,
TBLOFF: u21, // bit offset: 9 desc: Vector table base offset field
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const AIRCR = MMIO(Address + 0x0000000c, u32, packed struct { // byte offset: 12 Application interrupt and reset control register
VECTRESET: bool, // bit offset: 0 desc: VECTRESET
VECTCLRACTIVE: bool, // bit offset: 1 desc: VECTCLRACTIVE
SYSRESETREQ: bool, // bit offset: 2 desc: SYSRESETREQ
reserved0: u5 = 0,
PRIGROUP: u3, // bit offset: 8 desc: PRIGROUP
reserved1: u4 = 0,
ENDIANESS: bool, // bit offset: 15 desc: ENDIANESS
VECTKEYSTAT: u16, // bit offset: 16 desc: Register key
});
pub const SCR = MMIO(Address + 0x00000010, u32, packed struct { // byte offset: 16 System control register
reserved0: u1 = 0,
SLEEPONEXIT: bool, // bit offset: 1 desc: SLEEPONEXIT
SLEEPDEEP: bool, // bit offset: 2 desc: SLEEPDEEP
reserved1: u1 = 0,
SEVEONPEND: bool, // bit offset: 4 desc: Send Event on Pending bit
padding27: u1 = 0,
padding26: u1 = 0,
padding25: u1 = 0,
padding24: u1 = 0,
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CCR = MMIO(Address + 0x00000014, u32, packed struct { // byte offset: 20 Configuration and control register
NONBASETHRDENA: bool, // bit offset: 0 desc: Configures how the processor enters Thread mode
USERSETMPEND: bool, // bit offset: 1 desc: USERSETMPEND
reserved0: u1 = 0,
UNALIGN__TRP: bool, // bit offset: 3 desc: UNALIGN_ TRP
DIV_0_TRP: bool, // bit offset: 4 desc: DIV_0_TRP
reserved1: u3 = 0,
BFHFNMIGN: bool, // bit offset: 8 desc: BFHFNMIGN
STKALIGN: bool, // bit offset: 9 desc: STKALIGN
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SHPR1 = MMIO(Address + 0x00000018, u32, packed struct { // byte offset: 24 System handler priority registers
PRI_4: u8, // bit offset: 0 desc: Priority of system handler 4
PRI_5: u8, // bit offset: 8 desc: Priority of system handler 5
PRI_6: u8, // bit offset: 16 desc: Priority of system handler 6
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const SHPR2 = MMIO(Address + 0x0000001c, u32, packed struct { // byte offset: 28 System handler priority registers
reserved0: u24 = 0,
PRI_11: u8, // bit offset: 24 desc: Priority of system handler 11
});
pub const SHPR3 = MMIO(Address + 0x00000020, u32, packed struct { // byte offset: 32 System handler priority registers
reserved0: u16 = 0,
PRI_14: u8, // bit offset: 16 desc: Priority of system handler 14
PRI_15: u8, // bit offset: 24 desc: Priority of system handler 15
});
pub const SHCRS = MMIO(Address + 0x00000024, u32, packed struct { // byte offset: 36 System handler control and state register
MEMFAULTACT: bool, // bit offset: 0 desc: Memory management fault exception active bit
BUSFAULTACT: bool, // bit offset: 1 desc: Bus fault exception active bit
reserved0: u1 = 0,
USGFAULTACT: bool, // bit offset: 3 desc: Usage fault exception active bit
reserved1: u3 = 0,
SVCALLACT: bool, // bit offset: 7 desc: SVC call active bit
MONITORACT: bool, // bit offset: 8 desc: Debug monitor active bit
reserved2: u1 = 0,
PENDSVACT: bool, // bit offset: 10 desc: PendSV exception active bit
SYSTICKACT: bool, // bit offset: 11 desc: SysTick exception active bit
USGFAULTPENDED: bool, // bit offset: 12 desc: Usage fault exception pending bit
MEMFAULTPENDED: bool, // bit offset: 13 desc: Memory management fault exception pending bit
BUSFAULTPENDED: bool, // bit offset: 14 desc: Bus fault exception pending bit
SVCALLPENDED: bool, // bit offset: 15 desc: SVC call pending bit
MEMFAULTENA: bool, // bit offset: 16 desc: Memory management fault enable bit
BUSFAULTENA: bool, // bit offset: 17 desc: Bus fault enable bit
USGFAULTENA: bool, // bit offset: 18 desc: Usage fault enable bit
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const CFSR_UFSR_BFSR_MMFSR = MMIO(Address + 0x00000028, u32, packed struct { // byte offset: 40 Configurable fault status register
reserved0: u1 = 0,
IACCVIOL: bool, // bit offset: 1 desc: Instruction access violation flag
reserved1: u1 = 0,
MUNSTKERR: bool, // bit offset: 3 desc: Memory manager fault on unstacking for a return from exception
MSTKERR: bool, // bit offset: 4 desc: Memory manager fault on stacking for exception entry.
MLSPERR: bool, // bit offset: 5 desc: MLSPERR
reserved2: u1 = 0,
MMARVALID: bool, // bit offset: 7 desc: Memory Management Fault Address Register (MMAR) valid flag
IBUSERR: bool, // bit offset: 8 desc: Instruction bus error
PRECISERR: bool, // bit offset: 9 desc: Precise data bus error
IMPRECISERR: bool, // bit offset: 10 desc: Imprecise data bus error
UNSTKERR: bool, // bit offset: 11 desc: Bus fault on unstacking for a return from exception
STKERR: bool, // bit offset: 12 desc: Bus fault on stacking for exception entry
LSPERR: bool, // bit offset: 13 desc: Bus fault on floating-point lazy state preservation
reserved3: u1 = 0,
BFARVALID: bool, // bit offset: 15 desc: Bus Fault Address Register (BFAR) valid flag
UNDEFINSTR: bool, // bit offset: 16 desc: Undefined instruction usage fault
INVSTATE: bool, // bit offset: 17 desc: Invalid state usage fault
INVPC: bool, // bit offset: 18 desc: Invalid PC load usage fault
NOCP: bool, // bit offset: 19 desc: No coprocessor usage fault.
reserved4: u4 = 0,
UNALIGNED: bool, // bit offset: 24 desc: Unaligned access usage fault
DIVBYZERO: bool, // bit offset: 25 desc: Divide by zero usage fault
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
pub const HFSR = MMIO(Address + 0x0000002c, u32, packed struct { // byte offset: 44 Hard fault status register
reserved0: u1 = 0,
VECTTBL: bool, // bit offset: 1 desc: Vector table hard fault
reserved1: u28 = 0,
FORCED: bool, // bit offset: 30 desc: Forced hard fault
DEBUG_VT: bool, // bit offset: 31 desc: Reserved for Debug use
});
pub const MMFAR = MMIO(Address + 0x00000034, u32, packed struct { // byte offset: 52 Memory management fault address register
MMFAR: u32, // bit offset: 0 desc: Memory management fault address
});
pub const BFAR = MMIO(Address + 0x00000038, u32, packed struct { // byte offset: 56 Bus fault address register
BFAR: u32, // bit offset: 0 desc: Bus fault address
});
pub const AFSR = MMIO(Address + 0x0000003c, u32, packed struct { // byte offset: 60 Auxiliary fault status register
IMPDEF: u32, // bit offset: 0 desc: Implementation defined
});
};
pub const NVIC_STIR = extern struct {
pub const Address: u32 = 0xe000ef00;
pub const STIR = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 Software trigger interrupt register
INTID: u9, // bit offset: 0 desc: Software generated interrupt ID
padding23: u1 = 0,
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const FPU_CPACR = extern struct {
pub const Address: u32 = 0xe000ed88;
pub const CPACR = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 Coprocessor access control register
reserved0: u20 = 0,
CP: u4, // bit offset: 20 desc: CP
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
};
pub const SCB_ACTRL = extern struct {
pub const Address: u32 = 0xe000e008;
pub const ACTRL = MMIO(Address + 0x00000000, u32, packed struct { // byte offset: 0 Auxiliary control register
DISMCYCINT: bool, // bit offset: 0 desc: DISMCYCINT
DISDEFWBUF: bool, // bit offset: 1 desc: DISDEFWBUF
DISFOLD: bool, // bit offset: 2 desc: DISFOLD
reserved0: u5 = 0,
DISFPCA: bool, // bit offset: 8 desc: DISFPCA
DISOOFP: bool, // bit offset: 9 desc: DISOOFP
padding22: u1 = 0,
padding21: u1 = 0,
padding20: u1 = 0,
padding19: u1 = 0,
padding18: u1 = 0,
padding17: u1 = 0,
padding16: u1 = 0,
padding15: u1 = 0,
padding14: u1 = 0,
padding13: u1 = 0,
padding12: u1 = 0,
padding11: u1 = 0,
padding10: u1 = 0,
padding9: u1 = 0,
padding8: u1 = 0,
padding7: u1 = 0,
padding6: u1 = 0,
padding5: u1 = 0,
padding4: u1 = 0,
padding3: u1 = 0,
padding2: u1 = 0,
padding1: u1 = 0,
});
}; | src/targets/stm32/stm32f411/mmio.zig |
const c = @import("c.zig");
const std = @import("std");
usingnamespace @import("log.zig");
/// Error set
pub const Error = error{GLFWFailedToInitialize};
fn errorCallback(err: i32, desc: [*c]const u8) callconv(.C) void {
std.log.emerg("GLFW -> {}:{*}", .{ err, desc });
}
/// Initializes glfw
pub fn init() Error!void {
_ = c.glfwSetErrorCallback(errorCallback);
if (c.glfwInit() == 0) return Error.GLFWFailedToInitialize;
}
/// Deinitializes glfw
pub fn deinit() void {
c.glfwTerminate();
}
/// Sets the next created window resize status
pub fn resizable(enable: bool) void {
c.glfwWindowHint(c.GLFW_RESIZABLE, if (enable) 1 else 0);
}
/// Returns the elapsed time
pub fn getElapsedTime() f64 {
return c.glfwGetTime();
}
/// Initialize glfw gl profile
pub fn initGLProfile() void {
c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MAJOR, 3);
c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MINOR, 3);
c.glfwWindowHint(c.GLFW_OPENGL_PROFILE, c.GLFW_OPENGL_CORE_PROFILE);
}
/// Make glfw window context
pub fn makeContext(handle: ?*c_void) void {
c.glfwMakeContextCurrent(@ptrCast(?*c.struct_GLFWwindow, handle));
}
/// Wait while window closes(returns true if should run)
pub fn shouldWindowRun(handle: ?*c_void) bool {
return if (c.glfwWindowShouldClose(@ptrCast(?*c.struct_GLFWwindow, handle)) == 0) true else false;
}
/// Returns width of the primary monitor
pub fn getScreenWidth() i32 {
var monitor = c.glfwGetPrimaryMonitor();
const mode = c.glfwGetVideoMode(monitor);
return mode.*.width;
}
/// Returns height of the primary monitor
pub fn getScreenHeight() i32 {
var monitor = c.glfwGetPrimaryMonitor();
const mode = c.glfwGetVideoMode(monitor);
return mode.*.height;
}
/// Returns refresh rate of the primary monitor
pub fn getScreenRefreshRate() i32 {
var monitor = c.glfwGetPrimaryMonitor();
const mode = c.glfwGetVideoMode(monitor);
return mode.*.refreshRate;
}
/// Polls the events
pub fn processEvents() void {
c.glfwPollEvents();
}
/// Swap buffers/sync the window with opengl
pub fn sync(handle: ?*c_void) void {
c.glfwSwapBuffers(@ptrCast(?*c.struct_GLFWwindow, handle));
}
/// Enable/Disable vsync
pub fn vsync(enable: bool) void {
c.glfwSwapInterval(if (enable) 1 else 0);
} | src/kiragine/kira/glfw.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const c = @cImport(@cInclude("puff.h"));
pub export fn main() void {
zigMain() catch unreachable;
}
fn puffAlloc(allocator: Allocator, input: []const u8) ![]u8 {
// call once to get the uncompressed length
var decoded_len: c_ulong = undefined;
var source_len: c_ulong = input.len;
const result = c.puff(c.NIL, &decoded_len, input.ptr, &source_len);
if (result != 0) {
return translatePuffError(result);
}
var dest = try allocator.alloc(u8, decoded_len);
errdefer allocator.free(dest);
// call again to actually get the output
_ = c.puff(dest.ptr, &decoded_len, input.ptr, &source_len);
return dest;
}
fn translatePuffError(code: c_int) anyerror {
return switch (code) {
2 => error.EndOfStream,
1 => error.OutputSpaceExhausted,
0 => unreachable,
-1 => error.InvalidBlockType,
-2 => error.StoredBlockLengthNotOnesComplement,
-3 => error.TooManyLengthOrDistanceCodes,
-4 => error.CodeLengthsCodesIncomplete,
-5 => error.RepeatLengthsWithNoFirstLengths,
-6 => error.RepeatMoreThanSpecifiedLengths,
-7 => error.InvalidLiteralOrLengthCodeLengths,
-8 => error.InvalidDistanceCodeLengths,
-9 => error.MissingEOBCode,
-10 => error.InvalidLiteralOrLengthOrDistanceCodeInBlock,
-11 => error.DistanceTooFarBackInBlock,
else => unreachable,
};
}
pub fn zigMain() !void {
// Setup an allocator that will detect leaks/use-after-free/etc
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
// this will check for leaks and crash the program if it finds any
defer std.debug.assert(gpa.deinit() == false);
const allocator = gpa.allocator();
// Read the data from stdin
const stdin = std.io.getStdIn();
const data = try stdin.readToEndAlloc(allocator, std.math.maxInt(usize));
defer allocator.free(data);
// Try to parse the data with puff
var puff_error: anyerror = error.NoError;
const inflated_puff: ?[]u8 = puffAlloc(allocator, data) catch |err| blk: {
puff_error = err;
break :blk null;
};
defer if (inflated_puff != null) {
allocator.free(inflated_puff.?);
};
const reader = std.io.fixedBufferStream(data).reader();
var inflate = try std.compress.deflate.decompressor(allocator, reader, null);
defer inflate.deinit();
var zig_error: anyerror = error.NoError;
var inflated: ?[]u8 = inflate.reader().readAllAlloc(allocator, std.math.maxInt(usize)) catch |err| blk: {
zig_error = err;
break :blk null;
};
defer if (inflated != null) {
allocator.free(inflated.?);
};
if (inflated_puff == null or inflated == null) {
if (inflated_puff != null or inflated != null) {
std.debug.print("puff error: {}, zig error: {}\n", .{ puff_error, zig_error });
return error.MismatchedErrors;
}
} else {
try std.testing.expectEqualSlices(u8, inflated_puff.?, inflated.?);
}
} | fuzzers/deflate-puff.zig |
pub const CBT_COLLISION_FILTER_DEFAULT = @as(c_int, 1);
pub const CBT_COLLISION_FILTER_STATIC = @as(c_int, 2);
pub const CBT_COLLISION_FILTER_KINEMATIC = @as(c_int, 4);
pub const CBT_COLLISION_FILTER_DEBRIS = @as(c_int, 8);
pub const CBT_COLLISION_FILTER_SENSOR_TRIGGER = @as(c_int, 16);
pub const CBT_COLLISION_FILTER_CHARACTER = @as(c_int, 32);
pub const CBT_COLLISION_FILTER_ALL = -@as(c_int, 1);
pub const CBT_RAYCAST_FLAG_NONE = @as(c_int, 0);
pub const CBT_RAYCAST_FLAG_TRIMESH_SKIP_BACKFACES = @as(c_int, 1);
pub const CBT_RAYCAST_FLAG_TRIMESH_KEEP_UNFLIPPED_NORMALS = @as(c_int, 2);
pub const CBT_RAYCAST_FLAG_USE_SUB_SIMPLEX_CONVEX_TEST = @as(c_int, 4);
pub const CBT_RAYCAST_FLAG_USE_USE_GJK_CONVEX_TEST = @as(c_int, 8);
pub const CBT_ANISOTROPIC_FRICTION_DISABLED = @as(c_int, 0);
pub const CBT_ANISOTROPIC_FRICTION = @as(c_int, 1);
pub const CBT_ANISOTROPIC_ROLLING_FRICTION = @as(c_int, 2);
pub const CBT_SHAPE_TYPE_BOX = @as(c_int, 0);
pub const CBT_SHAPE_TYPE_SPHERE = @as(c_int, 8);
pub const CBT_SHAPE_TYPE_CAPSULE = @as(c_int, 10);
pub const CBT_SHAPE_TYPE_CONE = @as(c_int, 11);
pub const CBT_SHAPE_TYPE_CYLINDER = @as(c_int, 13);
pub const CBT_SHAPE_TYPE_COMPOUND = @as(c_int, 31);
pub const CBT_SHAPE_TYPE_TRIANGLE_MESH = @as(c_int, 21);
pub const CBT_CONSTRAINT_TYPE_POINT2POINT = @as(c_int, 3);
pub const CBT_CONSTRAINT_TYPE_HINGE = @as(c_int, 4);
pub const CBT_CONSTRAINT_TYPE_CONETWIST = @as(c_int, 5);
pub const CBT_CONSTRAINT_TYPE_SLIDER = @as(c_int, 7);
pub const CBT_CONSTRAINT_TYPE_GEAR = @as(c_int, 10);
pub const CBT_CONSTRAINT_TYPE_D6_SPRING_2 = @as(c_int, 12);
pub const CBT_CONSTRAINT_PARAM_ERP = @as(c_int, 1);
pub const CBT_CONSTRAINT_PARAM_STOP_ERP = @as(c_int, 2);
pub const CBT_CONSTRAINT_PARAM_CFM = @as(c_int, 3);
pub const CBT_CONSTRAINT_PARAM_STOP_CFM = @as(c_int, 4);
pub const CBT_ACTIVE_TAG = @as(c_int, 1);
pub const CBT_ISLAND_SLEEPING = @as(c_int, 2);
pub const CBT_DISABLE_DEACTIVATION = @as(c_int, 4);
pub const CBT_DISABLE_SIMULATION = @as(c_int, 5);
pub const CBT_LINEAR_AXIS_X = @as(c_int, 0);
pub const CBT_LINEAR_AXIS_Y = @as(c_int, 1);
pub const CBT_LINEAR_AXIS_Z = @as(c_int, 2);
pub const CBT_ANGULAR_AXIS_X = @as(c_int, 3);
pub const CBT_ANGULAR_AXIS_Y = @as(c_int, 4);
pub const CBT_ANGULAR_AXIS_Z = @as(c_int, 5);
pub const CBT_ROTATE_ORDER_XYZ = @as(c_int, 0);
pub const CBT_ROTATE_ORDER_XZY = @as(c_int, 1);
pub const CBT_ROTATE_ORDER_YXZ = @as(c_int, 2);
pub const CBT_ROTATE_ORDER_YZX = @as(c_int, 3);
pub const CBT_ROTATE_ORDER_ZXY = @as(c_int, 4);
pub const CBT_ROTATE_ORDER_ZYX = @as(c_int, 5);
pub const CbtVector3 = [3]f32;
pub const struct_CbtWorldHandle__ = extern struct {
unused: c_int,
};
pub const CbtWorldHandle = [*c]struct_CbtWorldHandle__;
pub const struct_CbtShapeHandle__ = extern struct {
unused: c_int,
};
pub const CbtShapeHandle = [*c]struct_CbtShapeHandle__;
pub const struct_CbtBodyHandle__ = extern struct {
unused: c_int,
};
pub const CbtBodyHandle = [*c]struct_CbtBodyHandle__;
pub const struct_CbtConstraintHandle__ = extern struct {
unused: c_int,
};
pub const CbtConstraintHandle = [*c]struct_CbtConstraintHandle__;
pub const CbtDrawLine1Callback = ?fn ([*c]const f32, [*c]const f32, [*c]const f32, ?*anyopaque) callconv(.C) void;
pub const CbtDrawLine2Callback = ?fn ([*c]const f32, [*c]const f32, [*c]const f32, [*c]const f32, ?*anyopaque) callconv(.C) void;
pub const CbtDrawContactPointCallback = ?fn ([*c]const f32, [*c]const f32, f32, c_int, [*c]const f32, ?*anyopaque) callconv(.C) void;
pub const CbtReportErrorWarningCallback = ?fn ([*c]const u8, ?*anyopaque) callconv(.C) void;
pub const struct_CbtDebugDrawCallbacks = extern struct {
drawLine1: CbtDrawLine1Callback,
drawLine2: CbtDrawLine2Callback,
drawContactPoint: CbtDrawContactPointCallback,
reportErrorWarning: CbtReportErrorWarningCallback,
user_data: ?*anyopaque,
};
pub const CbtDebugDrawCallbacks = struct_CbtDebugDrawCallbacks;
pub const struct_CbtRayCastResult = extern struct {
hit_normal_world: CbtVector3,
hit_point_world: CbtVector3,
hit_fraction: f32,
body: CbtBodyHandle,
};
pub const CbtRayCastResult = struct_CbtRayCastResult;
pub extern fn cbtWorldCreate() CbtWorldHandle;
pub extern fn cbtWorldDestroy(world_handle: CbtWorldHandle) void;
pub extern fn cbtWorldSetGravity(world_handle: CbtWorldHandle, gravity: [*c]const f32) void;
pub extern fn cbtWorldGetGravity(world_handle: CbtWorldHandle, gravity: [*c]f32) void;
pub extern fn cbtWorldStepSimulation(world_handle: CbtWorldHandle, time_step: f32, max_sub_steps: c_int, fixed_time_step: f32) c_int;
pub extern fn cbtWorldAddBody(world_handle: CbtWorldHandle, body_handle: CbtBodyHandle) void;
pub extern fn cbtWorldAddConstraint(world_handle: CbtWorldHandle, con_handle: CbtConstraintHandle, disable_collision_between_linked_bodies: bool) void;
pub extern fn cbtWorldRemoveBody(world_handle: CbtWorldHandle, body_handle: CbtBodyHandle) void;
pub extern fn cbtWorldRemoveConstraint(world_handle: CbtWorldHandle, constraint_handle: CbtConstraintHandle) void;
pub extern fn cbtWorldGetNumBodies(world_handle: CbtWorldHandle) c_int;
pub extern fn cbtWorldGetNumConstraints(world_handle: CbtWorldHandle) c_int;
pub extern fn cbtWorldGetBody(world_handle: CbtWorldHandle, body_index: c_int) CbtBodyHandle;
pub extern fn cbtWorldGetConstraint(world_handle: CbtWorldHandle, con_index: c_int) CbtConstraintHandle;
pub extern fn cbtRayTestClosest(world_handle: CbtWorldHandle, ray_from_world: [*c]const f32, ray_to_world: [*c]const f32, collision_filter_group: c_int, collision_filter_mask: c_int, flags: c_uint, result: [*c]CbtRayCastResult) bool;
pub extern fn cbtWorldDebugSetCallbacks(world_handle: CbtWorldHandle, callbacks: [*c]const CbtDebugDrawCallbacks) void;
pub extern fn cbtWorldDebugDraw(world_handle: CbtWorldHandle) void;
pub extern fn cbtWorldDebugDrawLine1(world_handle: CbtWorldHandle, p0: [*c]const f32, p1: [*c]const f32, color: [*c]const f32) void;
pub extern fn cbtWorldDebugDrawLine2(world_handle: CbtWorldHandle, p0: [*c]const f32, p1: [*c]const f32, color0: [*c]const f32, color1: [*c]const f32) void;
pub extern fn cbtWorldDebugDrawSphere(world_handle: CbtWorldHandle, position: [*c]const f32, radius: f32, color: [*c]const f32) void;
pub extern fn cbtShapeAllocate(shape_type: c_int) CbtShapeHandle;
pub extern fn cbtShapeDeallocate(shape_handle: CbtShapeHandle) void;
pub extern fn cbtShapeDestroy(shape_handle: CbtShapeHandle) void;
pub extern fn cbtShapeIsCreated(shape_handle: CbtShapeHandle) bool;
pub extern fn cbtShapeGetType(shape_handle: CbtShapeHandle) c_int;
pub extern fn cbtShapeSetMargin(shape_handle: CbtShapeHandle, margin: f32) void;
pub extern fn cbtShapeGetMargin(shape_handle: CbtShapeHandle) f32;
pub extern fn cbtShapeBoxCreate(shape_handle: CbtShapeHandle, half_extents: [*c]const f32) void;
pub extern fn cbtShapeBoxGetHalfExtentsWithoutMargin(shape_handle: CbtShapeHandle, half_extents: [*c]f32) void;
pub extern fn cbtShapeBoxGetHalfExtentsWithMargin(shape_handle: CbtShapeHandle, half_extents: [*c]f32) void;
pub extern fn cbtShapeSphereCreate(shape_handle: CbtShapeHandle, radius: f32) void;
pub extern fn cbtShapeSphereSetUnscaledRadius(shape_handle: CbtShapeHandle, radius: f32) void;
pub extern fn cbtShapeSphereGetRadius(shape_handle: CbtShapeHandle) f32;
pub extern fn cbtShapeCapsuleCreate(shape_handle: CbtShapeHandle, radius: f32, height: f32, up_axis: c_int) void;
pub extern fn cbtShapeCapsuleGetUpAxis(shape_handle: CbtShapeHandle) c_int;
pub extern fn cbtShapeCapsuleGetHalfHeight(shape_handle: CbtShapeHandle) f32;
pub extern fn cbtShapeCapsuleGetRadius(shape_handle: CbtShapeHandle) f32;
pub extern fn cbtShapeCylinderCreate(shape_handle: CbtShapeHandle, half_extents: [*c]const f32, up_axis: c_int) void;
pub extern fn cbtShapeCylinderGetHalfExtentsWithoutMargin(shape_handle: CbtShapeHandle, half_extents: [*c]f32) void;
pub extern fn cbtShapeCylinderGetHalfExtentsWithMargin(shape_handle: CbtShapeHandle, half_extents: [*c]f32) void;
pub extern fn cbtShapeCylinderGetUpAxis(shape_handle: CbtShapeHandle) c_int;
pub extern fn cbtShapeConeCreate(shape_handle: CbtShapeHandle, radius: f32, height: f32, up_axis: c_int) void;
pub extern fn cbtShapeConeGetRadius(shape_handle: CbtShapeHandle) f32;
pub extern fn cbtShapeConeGetHeight(shape_handle: CbtShapeHandle) f32;
pub extern fn cbtShapeConeGetUpAxis(shape_handle: CbtShapeHandle) c_int;
pub extern fn cbtShapeCompoundCreate(shape_handle: CbtShapeHandle, enable_dynamic_aabb_tree: bool, initial_child_capacity: c_int) void;
pub extern fn cbtShapeCompoundAddChild(shape_handle: CbtShapeHandle, local_transform: [*c]const CbtVector3, child_shape_handle: CbtShapeHandle) void;
pub extern fn cbtShapeCompoundRemoveChild(shape_handle: CbtShapeHandle, child_shape_handle: CbtShapeHandle) void;
pub extern fn cbtShapeCompoundRemoveChildByIndex(shape_handle: CbtShapeHandle, child_shape_index: c_int) void;
pub extern fn cbtShapeCompoundGetNumChilds(shape_handle: CbtShapeHandle) c_int;
pub extern fn cbtShapeCompoundGetChild(shape_handle: CbtShapeHandle, child_shape_index: c_int) CbtShapeHandle;
pub extern fn cbtShapeCompoundGetChildTransform(shape_handle: CbtShapeHandle, child_shape_index: c_int, transform: [*c]CbtVector3) void;
pub extern fn cbtShapeTriMeshCreateBegin(shape_handle: CbtShapeHandle) void;
pub extern fn cbtShapeTriMeshCreateEnd(shape_handle: CbtShapeHandle) void;
pub extern fn cbtShapeTriMeshDestroy(shape_handle: CbtShapeHandle) void;
pub extern fn cbtShapeTriMeshAddIndexVertexArray(shape_handle: CbtShapeHandle, num_triangles: c_int, triangle_base: ?*const anyopaque, triangle_stride: c_int, num_vertices: c_int, vertex_base: ?*const anyopaque, vertex_stride: c_int) void;
pub extern fn cbtShapeIsPolyhedral(shape_handle: CbtShapeHandle) bool;
pub extern fn cbtShapeIsConvex2d(shape_handle: CbtShapeHandle) bool;
pub extern fn cbtShapeIsConvex(shape_handle: CbtShapeHandle) bool;
pub extern fn cbtShapeIsNonMoving(shape_handle: CbtShapeHandle) bool;
pub extern fn cbtShapeIsConcave(shape_handle: CbtShapeHandle) bool;
pub extern fn cbtShapeIsCompound(shape_handle: CbtShapeHandle) bool;
pub extern fn cbtShapeCalculateLocalInertia(shape_handle: CbtShapeHandle, mass: f32, inertia: [*c]f32) void;
pub extern fn cbtShapeSetUserPointer(shape_handle: CbtShapeHandle, user_pointer: ?*anyopaque) void;
pub extern fn cbtShapeGetUserPointer(shape_handle: CbtShapeHandle) ?*anyopaque;
pub extern fn cbtShapeSetUserIndex(shape_handle: CbtShapeHandle, slot: c_int, user_index: c_int) void;
pub extern fn cbtShapeGetUserIndex(shape_handle: CbtShapeHandle, slot: c_int) c_int;
pub extern fn cbtBodyAllocate() CbtBodyHandle;
pub extern fn cbtBodyAllocateBatch(num: c_uint, body_handles: [*c]CbtBodyHandle) void;
pub extern fn cbtBodyDeallocate(body_handle: CbtBodyHandle) void;
pub extern fn cbtBodyDeallocateBatch(num: c_uint, body_handles: [*c]CbtBodyHandle) void;
pub extern fn cbtBodyCreate(body_handle: CbtBodyHandle, mass: f32, transform: [*c]const CbtVector3, shape_handle: CbtShapeHandle) void;
pub extern fn cbtBodyDestroy(body_handle: CbtBodyHandle) void;
pub extern fn cbtBodyIsCreated(body_handle: CbtBodyHandle) bool;
pub extern fn cbtBodySetShape(body_handle: CbtBodyHandle, shape_handle: CbtShapeHandle) void;
pub extern fn cbtBodyGetShape(body_handle: CbtBodyHandle) CbtShapeHandle;
pub extern fn cbtBodySetRestitution(body_handle: CbtBodyHandle, restitution: f32) void;
pub extern fn cbtBodySetFriction(body_handle: CbtBodyHandle, friction: f32) void;
pub extern fn cbtBodySetRollingFriction(body_handle: CbtBodyHandle, friction: f32) void;
pub extern fn cbtBodySetSpinningFriction(body_handle: CbtBodyHandle, friction: f32) void;
pub extern fn cbtBodySetAnisotropicFriction(body_handle: CbtBodyHandle, friction: [*c]const f32, mode: c_int) void;
pub extern fn cbtBodySetContactStiffnessAndDamping(body_handle: CbtBodyHandle, stiffness: f32, damping: f32) void;
pub extern fn cbtBodySetMassProps(body_handle: CbtBodyHandle, mass: f32, inertia: [*c]const f32) void;
pub extern fn cbtBodySetDamping(body_handle: CbtBodyHandle, linear: f32, angular: f32) void;
pub extern fn cbtBodySetLinearVelocity(body_handle: CbtBodyHandle, velocity: [*c]const f32) void;
pub extern fn cbtBodySetAngularVelocity(body_handle: CbtBodyHandle, velocity: [*c]const f32) void;
pub extern fn cbtBodySetLinearFactor(body_handle: CbtBodyHandle, factor: [*c]const f32) void;
pub extern fn cbtBodySetAngularFactor(body_handle: CbtBodyHandle, factor: [*c]const f32) void;
pub extern fn cbtBodySetGravity(body_handle: CbtBodyHandle, gravity: [*c]const f32) void;
pub extern fn cbtBodyGetGravity(body_handle: CbtBodyHandle, gravity: [*c]f32) void;
pub extern fn cbtBodyGetNumConstraints(body_handle: CbtBodyHandle) c_int;
pub extern fn cbtBodyGetConstraint(body_handle: CbtBodyHandle, index: c_int) CbtConstraintHandle;
pub extern fn cbtBodyApplyCentralForce(body_handle: CbtBodyHandle, force: [*c]const f32) void;
pub extern fn cbtBodyApplyCentralImpulse(body_handle: CbtBodyHandle, impulse: [*c]const f32) void;
pub extern fn cbtBodyApplyForce(body_handle: CbtBodyHandle, force: [*c]const f32, rel_pos: [*c]const f32) void;
pub extern fn cbtBodyApplyImpulse(body_handle: CbtBodyHandle, impulse: [*c]const f32, rel_pos: [*c]const f32) void;
pub extern fn cbtBodyApplyTorque(body_handle: CbtBodyHandle, torque: [*c]const f32) void;
pub extern fn cbtBodyApplyTorqueImpulse(body_handle: CbtBodyHandle, impulse: [*c]const f32) void;
pub extern fn cbtBodyGetRestitution(body_handle: CbtBodyHandle) f32;
pub extern fn cbtBodyGetFriction(body_handle: CbtBodyHandle) f32;
pub extern fn cbtBodyGetRollingFriction(body_handle: CbtBodyHandle) f32;
pub extern fn cbtBodyGetSpinningFriction(body_handle: CbtBodyHandle) f32;
pub extern fn cbtBodyGetAnisotropicFriction(body_handle: CbtBodyHandle, friction: [*c]f32) void;
pub extern fn cbtBodyGetContactStiffness(body_handle: CbtBodyHandle) f32;
pub extern fn cbtBodyGetContactDamping(body_handle: CbtBodyHandle) f32;
pub extern fn cbtBodyGetMass(body_handle: CbtBodyHandle) f32;
pub extern fn cbtBodyGetLinearDamping(body_handle: CbtBodyHandle) f32;
pub extern fn cbtBodyGetAngularDamping(body_handle: CbtBodyHandle) f32;
pub extern fn cbtBodyGetLinearVelocity(body_handle: CbtBodyHandle, velocity: [*c]f32) void;
pub extern fn cbtBodyGetAngularVelocity(body_handle: CbtBodyHandle, velocity: [*c]f32) void;
pub extern fn cbtBodyGetTotalForce(body_handle: CbtBodyHandle, force: [*c]f32) void;
pub extern fn cbtBodyGetTotalTorque(body_handle: CbtBodyHandle, torque: [*c]f32) void;
pub extern fn cbtBodyIsStatic(body_handle: CbtBodyHandle) bool;
pub extern fn cbtBodyIsKinematic(body_handle: CbtBodyHandle) bool;
pub extern fn cbtBodyIsStaticOrKinematic(body_handle: CbtBodyHandle) bool;
pub extern fn cbtBodyGetDeactivationTime(body_handle: CbtBodyHandle) f32;
pub extern fn cbtBodySetDeactivationTime(body_handle: CbtBodyHandle, time: f32) void;
pub extern fn cbtBodyGetActivationState(body_handle: CbtBodyHandle) c_int;
pub extern fn cbtBodySetActivationState(body_handle: CbtBodyHandle, state: c_int) void;
pub extern fn cbtBodyForceActivationState(body_handle: CbtBodyHandle, state: c_int) void;
pub extern fn cbtBodyIsActive(body_handle: CbtBodyHandle) bool;
pub extern fn cbtBodyIsInWorld(body_handle: CbtBodyHandle) bool;
pub extern fn cbtBodySetUserPointer(body_handle: CbtBodyHandle, user_pointer: ?*anyopaque) void;
pub extern fn cbtBodyGetUserPointer(body_handle: CbtBodyHandle) ?*anyopaque;
pub extern fn cbtBodySetUserIndex(body_handle: CbtBodyHandle, slot: c_int, user_index: c_int) void;
pub extern fn cbtBodyGetUserIndex(body_handle: CbtBodyHandle, slot: c_int) c_int;
pub extern fn cbtBodySetCenterOfMassTransform(body_handle: CbtBodyHandle, transform: [*c]const CbtVector3) void;
pub extern fn cbtBodyGetCenterOfMassTransform(body_handle: CbtBodyHandle, transform: [*c]CbtVector3) void;
pub extern fn cbtBodyGetCenterOfMassPosition(body_handle: CbtBodyHandle, position: [*c]f32) void;
pub extern fn cbtBodyGetInvCenterOfMassTransform(body_handle: CbtBodyHandle, transform: [*c]CbtVector3) void;
pub extern fn cbtBodyGetGraphicsWorldTransform(body_handle: CbtBodyHandle, transform: [*c]CbtVector3) void;
pub extern fn cbtConGetFixedBody() CbtBodyHandle;
pub extern fn cbtConAllocate(con_type: c_int) CbtConstraintHandle;
pub extern fn cbtConDeallocate(con_handle: CbtConstraintHandle) void;
pub extern fn cbtConDestroy(con_handle: CbtConstraintHandle) void;
pub extern fn cbtConIsCreated(con_handle: CbtConstraintHandle) bool;
pub extern fn cbtConGetType(con_handle: CbtConstraintHandle) c_int;
pub extern fn cbtConSetParam(con_handle: CbtConstraintHandle, param: c_int, value: f32, axis: c_int) void;
pub extern fn cbtConGetParam(con_handle: CbtConstraintHandle, param: c_int, axis: c_int) f32;
pub extern fn cbtConSetEnabled(con_handle: CbtConstraintHandle, enabled: bool) void;
pub extern fn cbtConIsEnabled(con_handle: CbtConstraintHandle) bool;
pub extern fn cbtConGetBodyA(con_handle: CbtConstraintHandle) CbtBodyHandle;
pub extern fn cbtConGetBodyB(con_handle: CbtConstraintHandle) CbtBodyHandle;
pub extern fn cbtConSetBreakingImpulseThreshold(con_handle: CbtConstraintHandle, threshold: f32) void;
pub extern fn cbtConGetBreakingImpulseThreshold(con_handle: CbtConstraintHandle) f32;
pub extern fn cbtConSetDebugDrawSize(con_handle: CbtConstraintHandle, size: f32) void;
pub extern fn cbtConGetDebugDrawSize(con_handle: CbtConstraintHandle) f32;
pub extern fn cbtConPoint2PointCreate1(con_handle: CbtConstraintHandle, body_handle_a: CbtBodyHandle, pivot_a: [*c]const f32) void;
pub extern fn cbtConPoint2PointCreate2(con_handle: CbtConstraintHandle, body_handle_a: CbtBodyHandle, body_handle_b: CbtBodyHandle, pivot_a: [*c]const f32, pivot_b: [*c]const f32) void;
pub extern fn cbtConPoint2PointSetPivotA(con_handle: CbtConstraintHandle, pivot: [*c]const f32) void;
pub extern fn cbtConPoint2PointSetPivotB(con_handle: CbtConstraintHandle, pivot: [*c]const f32) void;
pub extern fn cbtConPoint2PointSetTau(con_handle: CbtConstraintHandle, tau: f32) void;
pub extern fn cbtConPoint2PointSetDamping(con_handle: CbtConstraintHandle, damping: f32) void;
pub extern fn cbtConPoint2PointSetImpulseClamp(con_handle: CbtConstraintHandle, impulse_clamp: f32) void;
pub extern fn cbtConPoint2PointGetPivotA(con_handle: CbtConstraintHandle, pivot: [*c]f32) void;
pub extern fn cbtConPoint2PointGetPivotB(con_handle: CbtConstraintHandle, pivot: [*c]f32) void;
pub extern fn cbtConHingeCreate1(con_handle: CbtConstraintHandle, body_handle_a: CbtBodyHandle, pivot_a: [*c]const f32, axis_a: [*c]const f32, use_reference_frame_a: bool) void;
pub extern fn cbtConHingeCreate2(con_handle: CbtConstraintHandle, body_handle_a: CbtBodyHandle, body_handle_b: CbtBodyHandle, pivot_a: [*c]const f32, pivot_b: [*c]const f32, axis_a: [*c]const f32, axis_b: [*c]const f32, use_reference_frame_a: bool) void;
pub extern fn cbtConHingeCreate3(con_handle: CbtConstraintHandle, body_handle_a: CbtBodyHandle, frame_a: [*c]const CbtVector3, use_reference_frame_a: bool) void;
pub extern fn cbtConHingeSetAngularOnly(con_handle: CbtConstraintHandle, angular_only: bool) void;
pub extern fn cbtConHingeEnableAngularMotor(con_handle: CbtConstraintHandle, enable: bool, target_velocity: f32, max_motor_impulse: f32) void;
pub extern fn cbtConHingeSetLimit(con_handle: CbtConstraintHandle, low: f32, high: f32, softness: f32, bias_factor: f32, relaxation_factor: f32) void;
pub extern fn cbtConGearCreate(con_handle: CbtConstraintHandle, body_handle_a: CbtBodyHandle, body_handle_b: CbtBodyHandle, axis_a: [*c]const f32, axis_b: [*c]const f32, ratio: f32) void;
pub extern fn cbtConGearSetAxisA(con_handle: CbtConstraintHandle, axis: [*c]const f32) void;
pub extern fn cbtConGearSetAxisB(con_handle: CbtConstraintHandle, axis: [*c]const f32) void;
pub extern fn cbtConGearSetRatio(con_handle: CbtConstraintHandle, ratio: f32) void;
pub extern fn cbtConGearGetAxisA(con_handle: CbtConstraintHandle, axis: [*c]f32) void;
pub extern fn cbtConGearGetAxisB(con_handle: CbtConstraintHandle, axis: [*c]f32) void;
pub extern fn cbtConGearGetRatio(con_handle: CbtConstraintHandle) f32;
pub extern fn cbtConSliderCreate1(con_handle: CbtConstraintHandle, body_handle_b: CbtBodyHandle, frame_b: [*c]const CbtVector3, use_reference_frame_a: bool) void;
pub extern fn cbtConSliderCreate2(con_handle: CbtConstraintHandle, body_handle_a: CbtBodyHandle, body_handle_b: CbtBodyHandle, frame_a: [*c]const CbtVector3, frame_b: [*c]const CbtVector3, use_reference_frame_a: bool) void;
pub extern fn cbtConSliderSetLinearLowerLimit(con_handle: CbtConstraintHandle, limit: f32) void;
pub extern fn cbtConSliderSetLinearUpperLimit(con_handle: CbtConstraintHandle, limit: f32) void;
pub extern fn cbtConSliderGetLinearLowerLimit(con_handle: CbtConstraintHandle) f32;
pub extern fn cbtConSliderGetLinearUpperLimit(con_handle: CbtConstraintHandle) f32;
pub extern fn cbtConSliderSetAngularLowerLimit(con_handle: CbtConstraintHandle, limit: f32) void;
pub extern fn cbtConSliderSetAngularUpperLimit(con_handle: CbtConstraintHandle, limit: f32) void;
pub extern fn cbtConSliderGetAngularLowerLimit(con_handle: CbtConstraintHandle) f32;
pub extern fn cbtConSliderGetAngularUpperLimit(con_handle: CbtConstraintHandle) f32;
pub extern fn cbtConSliderEnableLinearMotor(con_handle: CbtConstraintHandle, enable: bool, target_velocity: f32, max_motor_force: f32) void;
pub extern fn cbtConSliderEnableAngularMotor(con_handle: CbtConstraintHandle, enable: bool, target_velocity: f32, max_force: f32) void;
pub extern fn cbtConSliderIsLinearMotorEnabled(con_handle: CbtConstraintHandle) bool;
pub extern fn cbtConSliderIsAngularMotorEnabled(con_handle: CbtConstraintHandle) bool;
pub extern fn cbtConSliderGetAngularMotor(con_handle: CbtConstraintHandle, target_velocity: [*c]f32, max_force: [*c]f32) void;
pub extern fn cbtConSliderGetLinearPosition(con_handle: CbtConstraintHandle) f32;
pub extern fn cbtConSliderGetAngularPosition(con_handle: CbtConstraintHandle) f32;
pub extern fn cbtConD6Spring2Create1(con_handle: CbtConstraintHandle, body_handle_b: CbtBodyHandle, frame_b: [*c]const CbtVector3, rotate_order: c_int) void;
pub extern fn cbtConD6Spring2Create2(con_handle: CbtConstraintHandle, body_handle_a: CbtBodyHandle, body_handle_b: CbtBodyHandle, frame_a: [*c]const CbtVector3, frame_b: [*c]const CbtVector3, rotate_order: c_int) void;
pub extern fn cbtConD6Spring2SetLinearLowerLimit(con_handle: CbtConstraintHandle, limit: [*c]const f32) void;
pub extern fn cbtConD6Spring2SetLinearUpperLimit(con_handle: CbtConstraintHandle, limit: [*c]const f32) void;
pub extern fn cbtConD6Spring2GetLinearLowerLimit(con_handle: CbtConstraintHandle, limit: [*c]f32) void;
pub extern fn cbtConD6Spring2GetLinearUpperLimit(con_handle: CbtConstraintHandle, limit: [*c]f32) void;
pub extern fn cbtConD6Spring2SetAngularLowerLimit(con_handle: CbtConstraintHandle, limit: [*c]const f32) void;
pub extern fn cbtConD6Spring2SetAngularUpperLimit(con_handle: CbtConstraintHandle, limit: [*c]const f32) void;
pub extern fn cbtConD6Spring2GetAngularLowerLimit(con_handle: CbtConstraintHandle, limit: [*c]f32) void;
pub extern fn cbtConD6Spring2GetAngularUpperLimit(con_handle: CbtConstraintHandle, limit: [*c]f32) void;
pub extern fn cbtConConeTwistCreate1(con_handle: CbtConstraintHandle, body_handle_a: CbtBodyHandle, frame_a: [*c]const CbtVector3) void;
pub extern fn cbtConConeTwistCreate2(con_handle: CbtConstraintHandle, body_handle_a: CbtBodyHandle, body_handle_b: CbtBodyHandle, frame_a: [*c]const CbtVector3, frame_b: [*c]const CbtVector3) void;
pub extern fn cbtConConeTwistSetLimit(con_handle: CbtConstraintHandle, swing_span1: f32, swing_span2: f32, twist_span: f32, softness: f32, bias_factor: f32, relaxation_factor: f32) void; | src/deps/bullet/c.zig |
const std = @import("std");
const mem = std.mem;
const math = std.math;
const ArrayList = std.ArrayList;
const Function = @import("function.zig").Function;
const Memory = @import("memory.zig").Memory;
const Table = @import("table.zig").Table;
const Global = @import("global.zig").Global;
const Import = @import("common.zig").Import;
const Tag = @import("common.zig").Tag;
const ValueType = @import("common.zig").ValueType;
const Instance = @import("instance.zig").Instance;
// - Stores provide the runtime memory shared between modules
// - For different applications you may want to use a store that
// that allocates individual items differently. For example,
// if you know ahead of time that you will only load a fixed
// number of modules during the lifetime of the program, then
// you might be quite happy with a store that uses ArrayLists
// with an arena allocator, i.e. you are going to deallocate
// everything at the same time.
pub const ImportExport = struct {
import: Import,
handle: usize,
};
pub const ArrayListStore = struct {
alloc: *mem.Allocator,
functions: ArrayList(Function),
memories: ArrayList(Memory),
tables: ArrayList(Table),
globals: ArrayList(Global),
imports: ArrayList(ImportExport),
instances: ArrayList(Instance),
pub fn init(alloc: *mem.Allocator) ArrayListStore {
var store = ArrayListStore{
.alloc = alloc,
.functions = ArrayList(Function).init(alloc),
.memories = ArrayList(Memory).init(alloc),
.tables = ArrayList(Table).init(alloc),
.globals = ArrayList(Global).init(alloc),
.imports = ArrayList(ImportExport).init(alloc),
.instances = ArrayList(Instance).init(alloc),
};
return store;
}
// import
//
// import attempts to find in the store, the given module.name pair
// for the given type
pub fn import(self: *ArrayListStore, module: []const u8, name: []const u8, tag: Tag) !usize {
for (self.imports.items) |importexport| {
if (tag != importexport.import.desc_tag) continue;
if (!mem.eql(u8, module, importexport.import.module)) continue;
if (!mem.eql(u8, name, importexport.import.name)) continue;
return importexport.handle;
}
std.log.err("Import not found: {s}.{s}\n", .{ module, name });
return error.ImportNotFound;
}
pub fn @"export"(self: *ArrayListStore, module: []const u8, name: []const u8, tag: Tag, handle: usize) !void {
try self.imports.append(ImportExport{
.import = Import{
.module = module,
.name = name,
.desc_tag = tag,
},
.handle = handle,
});
}
pub fn function(self: *ArrayListStore, handle: usize) !Function {
if (handle >= self.functions.items.len) return error.BadFunctionIndex;
return self.functions.items[handle];
}
pub fn addFunction(self: *ArrayListStore, func: Function) !usize {
const fun_ptr = try self.functions.addOne();
fun_ptr.* = func;
return self.functions.items.len - 1;
}
pub fn memory(self: *ArrayListStore, handle: usize) !*Memory {
if (handle >= self.memories.items.len) return error.BadMemoryIndex;
return &self.memories.items[handle];
}
pub fn addMemory(self: *ArrayListStore, min: u32, max: ?u32) !usize {
const mem_ptr = try self.memories.addOne();
mem_ptr.* = Memory.init(self.alloc, min, max);
_ = try mem_ptr.grow(min);
return self.memories.items.len - 1;
}
pub fn table(self: *ArrayListStore, handle: usize) !*Table {
if (handle >= self.tables.items.len) return error.BadTableIndex;
return &self.tables.items[handle];
}
pub fn addTable(self: *ArrayListStore, entries: u32, max: ?u32) !usize {
const tbl_ptr = try self.tables.addOne();
tbl_ptr.* = try Table.init(self.alloc, entries, max);
return self.tables.items.len - 1;
}
pub fn global(self: *ArrayListStore, handle: usize) !*Global {
if (handle >= self.globals.items.len) return error.BadGlobalIndex;
return &self.globals.items[handle];
}
pub fn addGlobal(self: *ArrayListStore, value: Global) !usize {
const glbl_ptr = try self.globals.addOne();
glbl_ptr.* = value;
return self.globals.items.len - 1;
}
pub fn instance(self: *ArrayListStore, handle: usize) !*Instance {
if (handle >= self.instances.items.len) return error.BadInstanceIndex;
return &self.instances.items[handle];
}
pub fn addInstance(self: *ArrayListStore, inst: Instance) !usize {
const instance_ptr = try self.instances.addOne();
instance_ptr.* = inst;
return self.instances.items.len - 1;
}
}; | src/store.zig |
const std = @import("std");
const Mat4 = @import("matrix.zig").Mat4;
const Vec4 = @import("vector.zig").Vec4;
const initPoint = @import("vector.zig").initPoint;
const initVector = @import("vector.zig").initVector;
const Color = @import("color.zig").Color;
const Shape = @import("shape.zig").Shape;
const Ray = @import("ray.zig").Ray;
const Material = @import("material.zig").Material;
const PointLight = @import("light.zig").PointLight;
pub const World = struct {
const Self = @This();
allocator: std.mem.Allocator,
objects: std.ArrayList(Shape),
light: PointLight,
pub fn init(allocator: std.mem.Allocator) Self {
return Self{
.allocator = allocator,
.objects = std.ArrayList(Shape).init(allocator),
.light = .{},
};
}
pub fn initDefault(allocator: std.mem.Allocator) !Self {
var world = init(allocator);
world.light = PointLight{
.position = initPoint(-10, 10, -10),
.intensity = Color.White,
};
const s1 = Shape{
.geo = .{ .sphere = .{} },
.material = .{
.color = Color.init(0.8, 1.0, 0.6),
.diffuse = 0.7,
.specular = 0.2,
},
};
try world.objects.append(s1);
const s2 = Shape{
.geo = .{ .sphere = .{} },
.transform = Mat4.identity().scale(0.5, 0.5, 0.5),
};
try world.objects.append(s2);
return world;
}
pub fn deinit(self: *Self) void {
self.objects.deinit();
}
};
const alloc = std.testing.allocator;
test "The default world" {
var w = try World.initDefault(alloc);
defer w.deinit();
try std.testing.expectEqual(w.objects.items[0].material.color, Color.init(0.8, 1.0, 0.6));
try std.testing.expectEqual(w.objects.items[1].transform, Mat4.identity().scale(0.5, 0.5, 0.5));
try std.testing.expectEqual(w.light.position, initPoint(-10, 10, -10));
try std.testing.expectEqual(w.light.intensity, Color.White);
} | world.zig |
const std = @import("std");
const Compilation = @import("Compilation.zig");
const Tree = @import("Tree.zig");
const NodeIndex = Tree.NodeIndex;
const Object = @import("Object.zig");
const x86_64 = @import("codegen/x86_64.zig");
const Codegen = @This();
comp: *Compilation,
tree: Tree,
obj: *Object,
node_tag: []const Tree.Tag,
node_data: []const Tree.Node.Data,
pub const Error = Compilation.Error || error{CodegenFailed};
/// Generate tree to an object file.
/// Caller is responsible for flushing and freeing the returned object.
pub fn generateTree(comp: *Compilation, tree: Tree) Compilation.Error!*Object {
var c = Codegen{
.comp = comp,
.tree = tree,
.obj = try Object.create(comp),
.node_tag = tree.nodes.items(.tag),
.node_data = tree.nodes.items(.data),
};
errdefer c.obj.deinit();
const node_tags = tree.nodes.items(.tag);
for (tree.root_decls) |decl| {
switch (node_tags[@enumToInt(decl)]) {
// these produce no code
.static_assert,
.typedef,
.struct_decl_two,
.union_decl_two,
.enum_decl_two,
.struct_decl,
.union_decl,
.enum_decl,
=> {},
// define symbol
.fn_proto,
.static_fn_proto,
.inline_fn_proto,
.inline_static_fn_proto,
.noreturn_fn_proto,
.noreturn_static_fn_proto,
.noreturn_inline_fn_proto,
.noreturn_inline_static_fn_proto,
.extern_var,
.threadlocal_extern_var,
=> {
const name = c.tree.tokSlice(c.node_data[@enumToInt(decl)].decl.name);
_ = try c.obj.declareSymbol(.@"undefined", name, .Strong, .external, 0, 0);
},
// function definition
.fn_def,
.static_fn_def,
.inline_fn_def,
.inline_static_fn_def,
.noreturn_fn_def,
.noreturn_static_fn_def,
.noreturn_inline_fn_def,
.noreturn_inline_static_fn_def,
=> c.genFn(decl) catch |err| switch (err) {
error.FatalError => return error.FatalError,
error.OutOfMemory => return error.OutOfMemory,
error.CodegenFailed => continue,
},
.@"var",
.static_var,
.threadlocal_var,
.threadlocal_static_var,
=> c.genVar(decl) catch |err| switch (err) {
error.FatalError => return error.FatalError,
error.OutOfMemory => return error.OutOfMemory,
error.CodegenFailed => continue,
},
else => unreachable,
}
}
return c.obj;
}
fn genFn(c: *Codegen, decl: NodeIndex) Error!void {
const section: Object.Section = .func;
const data = try c.obj.getSection(section);
const start_len = data.items.len;
switch (c.comp.target.cpu.arch) {
.x86_64 => try x86_64.genFn(c, decl, data),
else => unreachable,
}
const name = c.tree.tokSlice(c.node_data[@enumToInt(decl)].decl.name);
_ = try c.obj.declareSymbol(section, name, .Strong, .func, start_len, data.items.len - start_len);
}
fn genVar(c: *Codegen, decl: NodeIndex) Error!void {
switch (c.comp.target.cpu.arch) {
.x86_64 => try x86_64.genVar(c, decl),
else => unreachable,
}
} | src/Codegen.zig |
const std = @import("../std.zig");
const CpuFeature = std.Target.Cpu.Feature;
const CpuModel = std.Target.Cpu.Model;
pub const Feature = enum {
@"3dnow",
@"3dnowa",
@"64bit",
adx,
aes,
amx_bf16,
amx_int8,
amx_tile,
avx,
avx2,
avx512bf16,
avx512bitalg,
avx512bw,
avx512cd,
avx512dq,
avx512er,
avx512f,
avx512ifma,
avx512pf,
avx512vbmi,
avx512vbmi2,
avx512vl,
avx512vnni,
avx512vp2intersect,
avx512vpopcntdq,
bmi,
bmi2,
branchfusion,
cldemote,
clflushopt,
clwb,
clzero,
cmov,
cx16,
cx8,
enqcmd,
ermsb,
f16c,
false_deps_lzcnt_tzcnt,
false_deps_popcnt,
fast_11bytenop,
fast_15bytenop,
fast_7bytenop,
fast_bextr,
fast_gather,
fast_hops,
fast_lzcnt,
fast_scalar_fsqrt,
fast_scalar_shift_masks,
fast_shld_rotate,
fast_variable_shuffle,
fast_vector_fsqrt,
fast_vector_shift_masks,
fma,
fma4,
fsgsbase,
fxsr,
gfni,
idivl_to_divb,
idivq_to_divl,
invpcid,
lea_sp,
lea_uses_ag,
lvi_cfi,
lvi_load_hardening,
lwp,
lzcnt,
macrofusion,
merge_to_threeway_branch,
mmx,
movbe,
movdir64b,
movdiri,
mpx,
mwaitx,
nopl,
pad_short_functions,
pclmul,
pconfig,
pku,
popcnt,
prefer_128_bit,
prefer_256_bit,
prefer_mask_registers,
prefetchwt1,
prfchw,
ptwrite,
rdpid,
rdrnd,
rdseed,
retpoline,
retpoline_external_thunk,
retpoline_indirect_branches,
retpoline_indirect_calls,
rtm,
sahf,
serialize,
seses,
sgx,
sha,
shstk,
slow_3ops_lea,
slow_incdec,
slow_lea,
slow_pmaddwd,
slow_pmulld,
slow_shld,
slow_two_mem_ops,
slow_unaligned_mem_16,
slow_unaligned_mem_32,
soft_float,
sse,
sse_unaligned_mem,
sse2,
sse3,
sse4_1,
sse4_2,
sse4a,
ssse3,
tbm,
tsxldtrk,
use_aa,
use_glm_div_sqrt_costs,
vaes,
vpclmulqdq,
vzeroupper,
waitpkg,
wbnoinvd,
x87,
xop,
xsave,
xsavec,
xsaveopt,
xsaves,
};
pub usingnamespace CpuFeature.feature_set_fns(Feature);
pub const all_features = blk: {
const len = @typeInfo(Feature).Enum.fields.len;
std.debug.assert(len <= CpuFeature.Set.needed_bit_count);
var result: [len]CpuFeature = undefined;
result[@enumToInt(Feature.@"3dnow")] = .{
.llvm_name = "3dnow",
.description = "Enable 3DNow! instructions",
.dependencies = featureSet(&[_]Feature{
.mmx,
}),
};
result[@enumToInt(Feature.@"3dnowa")] = .{
.llvm_name = "3dnowa",
.description = "Enable 3DNow! Athlon instructions",
.dependencies = featureSet(&[_]Feature{
.@"3dnow",
}),
};
result[@enumToInt(Feature.@"64bit")] = .{
.llvm_name = "64bit",
.description = "Support 64-bit instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.adx)] = .{
.llvm_name = "adx",
.description = "Support ADX instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.aes)] = .{
.llvm_name = "aes",
.description = "Enable AES instructions",
.dependencies = featureSet(&[_]Feature{
.sse2,
}),
};
result[@enumToInt(Feature.amx_bf16)] = .{
.llvm_name = "amx-bf16",
.description = "Support AMX-BF16 instructions",
.dependencies = featureSet(&[_]Feature{
.amx_tile,
}),
};
result[@enumToInt(Feature.amx_int8)] = .{
.llvm_name = "amx-int8",
.description = "Support AMX-INT8 instructions",
.dependencies = featureSet(&[_]Feature{
.amx_tile,
}),
};
result[@enumToInt(Feature.amx_tile)] = .{
.llvm_name = "amx-tile",
.description = "Support AMX-TILE instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.avx)] = .{
.llvm_name = "avx",
.description = "Enable AVX instructions",
.dependencies = featureSet(&[_]Feature{
.sse4_2,
}),
};
result[@enumToInt(Feature.avx2)] = .{
.llvm_name = "avx2",
.description = "Enable AVX2 instructions",
.dependencies = featureSet(&[_]Feature{
.avx,
}),
};
result[@enumToInt(Feature.avx512bf16)] = .{
.llvm_name = "avx512bf16",
.description = "Support bfloat16 floating point",
.dependencies = featureSet(&[_]Feature{
.avx512bw,
}),
};
result[@enumToInt(Feature.avx512bitalg)] = .{
.llvm_name = "avx512bitalg",
.description = "Enable AVX-512 Bit Algorithms",
.dependencies = featureSet(&[_]Feature{
.avx512bw,
}),
};
result[@enumToInt(Feature.avx512bw)] = .{
.llvm_name = "avx512bw",
.description = "Enable AVX-512 Byte and Word Instructions",
.dependencies = featureSet(&[_]Feature{
.avx512f,
}),
};
result[@enumToInt(Feature.avx512cd)] = .{
.llvm_name = "avx512cd",
.description = "Enable AVX-512 Conflict Detection Instructions",
.dependencies = featureSet(&[_]Feature{
.avx512f,
}),
};
result[@enumToInt(Feature.avx512dq)] = .{
.llvm_name = "avx512dq",
.description = "Enable AVX-512 Doubleword and Quadword Instructions",
.dependencies = featureSet(&[_]Feature{
.avx512f,
}),
};
result[@enumToInt(Feature.avx512er)] = .{
.llvm_name = "avx512er",
.description = "Enable AVX-512 Exponential and Reciprocal Instructions",
.dependencies = featureSet(&[_]Feature{
.avx512f,
}),
};
result[@enumToInt(Feature.avx512f)] = .{
.llvm_name = "avx512f",
.description = "Enable AVX-512 instructions",
.dependencies = featureSet(&[_]Feature{
.avx2,
.f16c,
.fma,
}),
};
result[@enumToInt(Feature.avx512ifma)] = .{
.llvm_name = "avx512ifma",
.description = "Enable AVX-512 Integer Fused Multiple-Add",
.dependencies = featureSet(&[_]Feature{
.avx512f,
}),
};
result[@enumToInt(Feature.avx512pf)] = .{
.llvm_name = "avx512pf",
.description = "Enable AVX-512 PreFetch Instructions",
.dependencies = featureSet(&[_]Feature{
.avx512f,
}),
};
result[@enumToInt(Feature.avx512vbmi)] = .{
.llvm_name = "avx512vbmi",
.description = "Enable AVX-512 Vector Byte Manipulation Instructions",
.dependencies = featureSet(&[_]Feature{
.avx512bw,
}),
};
result[@enumToInt(Feature.avx512vbmi2)] = .{
.llvm_name = "avx512vbmi2",
.description = "Enable AVX-512 further Vector Byte Manipulation Instructions",
.dependencies = featureSet(&[_]Feature{
.avx512bw,
}),
};
result[@enumToInt(Feature.avx512vl)] = .{
.llvm_name = "avx512vl",
.description = "Enable AVX-512 Vector Length eXtensions",
.dependencies = featureSet(&[_]Feature{
.avx512f,
}),
};
result[@enumToInt(Feature.avx512vnni)] = .{
.llvm_name = "avx512vnni",
.description = "Enable AVX-512 Vector Neural Network Instructions",
.dependencies = featureSet(&[_]Feature{
.avx512f,
}),
};
result[@enumToInt(Feature.avx512vp2intersect)] = .{
.llvm_name = "avx512vp2intersect",
.description = "Enable AVX-512 vp2intersect",
.dependencies = featureSet(&[_]Feature{
.avx512f,
}),
};
result[@enumToInt(Feature.avx512vpopcntdq)] = .{
.llvm_name = "avx512vpopcntdq",
.description = "Enable AVX-512 Population Count Instructions",
.dependencies = featureSet(&[_]Feature{
.avx512f,
}),
};
result[@enumToInt(Feature.bmi)] = .{
.llvm_name = "bmi",
.description = "Support BMI instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.bmi2)] = .{
.llvm_name = "bmi2",
.description = "Support BMI2 instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.branchfusion)] = .{
.llvm_name = "branchfusion",
.description = "CMP/TEST can be fused with conditional branches",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.cldemote)] = .{
.llvm_name = "cldemote",
.description = "Enable Cache Demote",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.clflushopt)] = .{
.llvm_name = "clflushopt",
.description = "Flush A Cache Line Optimized",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.clwb)] = .{
.llvm_name = "clwb",
.description = "Cache Line Write Back",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.clzero)] = .{
.llvm_name = "clzero",
.description = "Enable Cache Line Zero",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.cmov)] = .{
.llvm_name = "cmov",
.description = "Enable conditional move instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.cx16)] = .{
.llvm_name = "cx16",
.description = "64-bit with cmpxchg16b",
.dependencies = featureSet(&[_]Feature{
.cx8,
}),
};
result[@enumToInt(Feature.cx8)] = .{
.llvm_name = "cx8",
.description = "Support CMPXCHG8B instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.enqcmd)] = .{
.llvm_name = "enqcmd",
.description = "Has ENQCMD instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.ermsb)] = .{
.llvm_name = "ermsb",
.description = "REP MOVS/STOS are fast",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.f16c)] = .{
.llvm_name = "f16c",
.description = "Support 16-bit floating point conversion instructions",
.dependencies = featureSet(&[_]Feature{
.avx,
}),
};
result[@enumToInt(Feature.false_deps_lzcnt_tzcnt)] = .{
.llvm_name = "false-deps-lzcnt-tzcnt",
.description = "LZCNT/TZCNT have a false dependency on dest register",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.false_deps_popcnt)] = .{
.llvm_name = "false-deps-popcnt",
.description = "POPCNT has a false dependency on dest register",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.fast_11bytenop)] = .{
.llvm_name = "fast-11bytenop",
.description = "Target can quickly decode up to 11 byte NOPs",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.fast_15bytenop)] = .{
.llvm_name = "fast-15bytenop",
.description = "Target can quickly decode up to 15 byte NOPs",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.fast_7bytenop)] = .{
.llvm_name = "fast-7bytenop",
.description = "Target can quickly decode up to 7 byte NOPs",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.fast_bextr)] = .{
.llvm_name = "fast-bextr",
.description = "Indicates that the BEXTR instruction is implemented as a single uop with good throughput",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.fast_gather)] = .{
.llvm_name = "fast-gather",
.description = "Indicates if gather is reasonably fast",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.fast_hops)] = .{
.llvm_name = "fast-hops",
.description = "Prefer horizontal vector math instructions (haddp, phsub, etc.) over normal vector instructions with shuffles",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.fast_lzcnt)] = .{
.llvm_name = "fast-lzcnt",
.description = "LZCNT instructions are as fast as most simple integer ops",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.fast_scalar_fsqrt)] = .{
.llvm_name = "fast-scalar-fsqrt",
.description = "Scalar SQRT is fast (disable Newton-Raphson)",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.fast_scalar_shift_masks)] = .{
.llvm_name = "fast-scalar-shift-masks",
.description = "Prefer a left/right scalar logical shift pair over a shift+and pair",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.fast_shld_rotate)] = .{
.llvm_name = "fast-shld-rotate",
.description = "SHLD can be used as a faster rotate",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.fast_variable_shuffle)] = .{
.llvm_name = "fast-variable-shuffle",
.description = "Shuffles with variable masks are fast",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.fast_vector_fsqrt)] = .{
.llvm_name = "fast-vector-fsqrt",
.description = "Vector SQRT is fast (disable Newton-Raphson)",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.fast_vector_shift_masks)] = .{
.llvm_name = "fast-vector-shift-masks",
.description = "Prefer a left/right vector logical shift pair over a shift+and pair",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.fma)] = .{
.llvm_name = "fma",
.description = "Enable three-operand fused multiple-add",
.dependencies = featureSet(&[_]Feature{
.avx,
}),
};
result[@enumToInt(Feature.fma4)] = .{
.llvm_name = "fma4",
.description = "Enable four-operand fused multiple-add",
.dependencies = featureSet(&[_]Feature{
.avx,
.sse4a,
}),
};
result[@enumToInt(Feature.fsgsbase)] = .{
.llvm_name = "fsgsbase",
.description = "Support FS/GS Base instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.fxsr)] = .{
.llvm_name = "fxsr",
.description = "Support fxsave/fxrestore instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.gfni)] = .{
.llvm_name = "gfni",
.description = "Enable Galois Field Arithmetic Instructions",
.dependencies = featureSet(&[_]Feature{
.sse2,
}),
};
result[@enumToInt(Feature.idivl_to_divb)] = .{
.llvm_name = "idivl-to-divb",
.description = "Use 8-bit divide for positive values less than 256",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.idivq_to_divl)] = .{
.llvm_name = "idivq-to-divl",
.description = "Use 32-bit divide for positive values less than 2^32",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.invpcid)] = .{
.llvm_name = "invpcid",
.description = "Invalidate Process-Context Identifier",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.lea_sp)] = .{
.llvm_name = "lea-sp",
.description = "Use LEA for adjusting the stack pointer",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.lea_uses_ag)] = .{
.llvm_name = "lea-uses-ag",
.description = "LEA instruction needs inputs at AG stage",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.lvi_cfi)] = .{
.llvm_name = "lvi-cfi",
.description = "Prevent indirect calls/branches from using a memory operand, and precede all indirect calls/branches from a register with an LFENCE instruction to serialize control flow. Also decompose RET instructions into a POP+LFENCE+JMP sequence.",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.lvi_load_hardening)] = .{
.llvm_name = "lvi-load-hardening",
.description = "Insert LFENCE instructions to prevent data speculatively injected into loads from being used maliciously.",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.lwp)] = .{
.llvm_name = "lwp",
.description = "Enable LWP instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.lzcnt)] = .{
.llvm_name = "lzcnt",
.description = "Support LZCNT instruction",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.macrofusion)] = .{
.llvm_name = "macrofusion",
.description = "Various instructions can be fused with conditional branches",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.merge_to_threeway_branch)] = .{
.llvm_name = "merge-to-threeway-branch",
.description = "Merge branches to a three-way conditional branch",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.mmx)] = .{
.llvm_name = "mmx",
.description = "Enable MMX instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.movbe)] = .{
.llvm_name = "movbe",
.description = "Support MOVBE instruction",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.movdir64b)] = .{
.llvm_name = "movdir64b",
.description = "Support movdir64b instruction",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.movdiri)] = .{
.llvm_name = "movdiri",
.description = "Support movdiri instruction",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.mpx)] = .{
.llvm_name = "mpx",
.description = "Deprecated. Support MPX instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.mwaitx)] = .{
.llvm_name = "mwaitx",
.description = "Enable MONITORX/MWAITX timer functionality",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.nopl)] = .{
.llvm_name = "nopl",
.description = "Enable NOPL instruction",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.pad_short_functions)] = .{
.llvm_name = "pad-short-functions",
.description = "Pad short functions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.pclmul)] = .{
.llvm_name = "pclmul",
.description = "Enable packed carry-less multiplication instructions",
.dependencies = featureSet(&[_]Feature{
.sse2,
}),
};
result[@enumToInt(Feature.pconfig)] = .{
.llvm_name = "pconfig",
.description = "platform configuration instruction",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.pku)] = .{
.llvm_name = "pku",
.description = "Enable protection keys",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.popcnt)] = .{
.llvm_name = "popcnt",
.description = "Support POPCNT instruction",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.prefer_128_bit)] = .{
.llvm_name = "prefer-128-bit",
.description = "Prefer 128-bit AVX instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.prefer_256_bit)] = .{
.llvm_name = "prefer-256-bit",
.description = "Prefer 256-bit AVX instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.prefer_mask_registers)] = .{
.llvm_name = "prefer-mask-registers",
.description = "Prefer AVX512 mask registers over PTEST/MOVMSK",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.prefetchwt1)] = .{
.llvm_name = "prefetchwt1",
.description = "Prefetch with Intent to Write and T1 Hint",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.prfchw)] = .{
.llvm_name = "prfchw",
.description = "Support PRFCHW instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.ptwrite)] = .{
.llvm_name = "ptwrite",
.description = "Support ptwrite instruction",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.rdpid)] = .{
.llvm_name = "rdpid",
.description = "Support RDPID instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.rdrnd)] = .{
.llvm_name = "rdrnd",
.description = "Support RDRAND instruction",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.rdseed)] = .{
.llvm_name = "rdseed",
.description = "Support RDSEED instruction",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.retpoline)] = .{
.llvm_name = "retpoline",
.description = "Remove speculation of indirect branches from the generated code, either by avoiding them entirely or lowering them with a speculation blocking construct",
.dependencies = featureSet(&[_]Feature{
.retpoline_indirect_branches,
.retpoline_indirect_calls,
}),
};
result[@enumToInt(Feature.retpoline_external_thunk)] = .{
.llvm_name = "retpoline-external-thunk",
.description = "When lowering an indirect call or branch using a `retpoline`, rely on the specified user provided thunk rather than emitting one ourselves. Only has effect when combined with some other retpoline feature",
.dependencies = featureSet(&[_]Feature{
.retpoline_indirect_calls,
}),
};
result[@enumToInt(Feature.retpoline_indirect_branches)] = .{
.llvm_name = "retpoline-indirect-branches",
.description = "Remove speculation of indirect branches from the generated code",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.retpoline_indirect_calls)] = .{
.llvm_name = "retpoline-indirect-calls",
.description = "Remove speculation of indirect calls from the generated code",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.rtm)] = .{
.llvm_name = "rtm",
.description = "Support RTM instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.sahf)] = .{
.llvm_name = "sahf",
.description = "Support LAHF and SAHF instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.serialize)] = .{
.llvm_name = "serialize",
.description = "Has serialize instruction",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.seses)] = .{
.llvm_name = "seses",
.description = "Prevent speculative execution side channel timing attacks by inserting a speculation barrier before memory reads, memory writes, and conditional branches. Implies LVI Control Flow integrity.",
.dependencies = featureSet(&[_]Feature{
.lvi_cfi,
}),
};
result[@enumToInt(Feature.sgx)] = .{
.llvm_name = "sgx",
.description = "Enable Software Guard Extensions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.sha)] = .{
.llvm_name = "sha",
.description = "Enable SHA instructions",
.dependencies = featureSet(&[_]Feature{
.sse2,
}),
};
result[@enumToInt(Feature.shstk)] = .{
.llvm_name = "shstk",
.description = "Support CET Shadow-Stack instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.slow_3ops_lea)] = .{
.llvm_name = "slow-3ops-lea",
.description = "LEA instruction with 3 ops or certain registers is slow",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.slow_incdec)] = .{
.llvm_name = "slow-incdec",
.description = "INC and DEC instructions are slower than ADD and SUB",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.slow_lea)] = .{
.llvm_name = "slow-lea",
.description = "LEA instruction with certain arguments is slow",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.slow_pmaddwd)] = .{
.llvm_name = "slow-pmaddwd",
.description = "PMADDWD is slower than PMULLD",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.slow_pmulld)] = .{
.llvm_name = "slow-pmulld",
.description = "PMULLD instruction is slow",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.slow_shld)] = .{
.llvm_name = "slow-shld",
.description = "SHLD instruction is slow",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.slow_two_mem_ops)] = .{
.llvm_name = "slow-two-mem-ops",
.description = "Two memory operand instructions are slow",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.slow_unaligned_mem_16)] = .{
.llvm_name = "slow-unaligned-mem-16",
.description = "Slow unaligned 16-byte memory access",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.slow_unaligned_mem_32)] = .{
.llvm_name = "slow-unaligned-mem-32",
.description = "Slow unaligned 32-byte memory access",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.soft_float)] = .{
.llvm_name = "soft-float",
.description = "Use software floating point features",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.sse)] = .{
.llvm_name = "sse",
.description = "Enable SSE instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.sse_unaligned_mem)] = .{
.llvm_name = "sse-unaligned-mem",
.description = "Allow unaligned memory operands with SSE instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.sse2)] = .{
.llvm_name = "sse2",
.description = "Enable SSE2 instructions",
.dependencies = featureSet(&[_]Feature{
.sse,
}),
};
result[@enumToInt(Feature.sse3)] = .{
.llvm_name = "sse3",
.description = "Enable SSE3 instructions",
.dependencies = featureSet(&[_]Feature{
.sse2,
}),
};
result[@enumToInt(Feature.sse4_1)] = .{
.llvm_name = "sse4.1",
.description = "Enable SSE 4.1 instructions",
.dependencies = featureSet(&[_]Feature{
.ssse3,
}),
};
result[@enumToInt(Feature.sse4_2)] = .{
.llvm_name = "sse4.2",
.description = "Enable SSE 4.2 instructions",
.dependencies = featureSet(&[_]Feature{
.sse4_1,
}),
};
result[@enumToInt(Feature.sse4a)] = .{
.llvm_name = "sse4a",
.description = "Support SSE 4a instructions",
.dependencies = featureSet(&[_]Feature{
.sse3,
}),
};
result[@enumToInt(Feature.ssse3)] = .{
.llvm_name = "ssse3",
.description = "Enable SSSE3 instructions",
.dependencies = featureSet(&[_]Feature{
.sse3,
}),
};
result[@enumToInt(Feature.tbm)] = .{
.llvm_name = "tbm",
.description = "Enable TBM instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.tsxldtrk)] = .{
.llvm_name = "tsxldtrk",
.description = "Support TSXLDTRK instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.use_aa)] = .{
.llvm_name = "use-aa",
.description = "Use alias analysis during codegen",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.use_glm_div_sqrt_costs)] = .{
.llvm_name = "use-glm-div-sqrt-costs",
.description = "Use Goldmont specific floating point div/sqrt costs",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.vaes)] = .{
.llvm_name = "vaes",
.description = "Promote selected AES instructions to AVX512/AVX registers",
.dependencies = featureSet(&[_]Feature{
.aes,
.avx,
}),
};
result[@enumToInt(Feature.vpclmulqdq)] = .{
.llvm_name = "vpclmulqdq",
.description = "Enable vpclmulqdq instructions",
.dependencies = featureSet(&[_]Feature{
.avx,
.pclmul,
}),
};
result[@enumToInt(Feature.vzeroupper)] = .{
.llvm_name = "vzeroupper",
.description = "Should insert vzeroupper instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.waitpkg)] = .{
.llvm_name = "waitpkg",
.description = "Wait and pause enhancements",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.wbnoinvd)] = .{
.llvm_name = "wbnoinvd",
.description = "Write Back No Invalidate",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.x87)] = .{
.llvm_name = "x87",
.description = "Enable X87 float instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.xop)] = .{
.llvm_name = "xop",
.description = "Enable XOP instructions",
.dependencies = featureSet(&[_]Feature{
.fma4,
}),
};
result[@enumToInt(Feature.xsave)] = .{
.llvm_name = "xsave",
.description = "Support xsave instructions",
.dependencies = featureSet(&[_]Feature{}),
};
result[@enumToInt(Feature.xsavec)] = .{
.llvm_name = "xsavec",
.description = "Support xsavec instructions",
.dependencies = featureSet(&[_]Feature{
.xsave,
}),
};
result[@enumToInt(Feature.xsaveopt)] = .{
.llvm_name = "xsaveopt",
.description = "Support xsaveopt instructions",
.dependencies = featureSet(&[_]Feature{
.xsave,
}),
};
result[@enumToInt(Feature.xsaves)] = .{
.llvm_name = "xsaves",
.description = "Support xsaves instructions",
.dependencies = featureSet(&[_]Feature{
.xsave,
}),
};
const ti = @typeInfo(Feature);
for (result) |*elem, i| {
elem.index = i;
elem.name = ti.Enum.fields[i].name;
}
break :blk result;
};
pub const cpu = struct {
pub const amdfam10 = CpuModel{
.name = "amdfam10",
.llvm_name = "amdfam10",
.features = featureSet(&[_]Feature{
.@"3dnowa",
.@"64bit",
.cmov,
.cx16,
.cx8,
.fast_scalar_shift_masks,
.fxsr,
.lzcnt,
.nopl,
.popcnt,
.prfchw,
.sahf,
.slow_shld,
.sse4a,
.vzeroupper,
.x87,
}),
};
pub const athlon = CpuModel{
.name = "athlon",
.llvm_name = "athlon",
.features = featureSet(&[_]Feature{
.@"3dnowa",
.cmov,
.cx8,
.nopl,
.slow_shld,
.slow_unaligned_mem_16,
.vzeroupper,
.x87,
}),
};
pub const athlon_4 = CpuModel{
.name = "athlon_4",
.llvm_name = "athlon-4",
.features = featureSet(&[_]Feature{
.@"3dnowa",
.cmov,
.cx8,
.fxsr,
.nopl,
.slow_shld,
.slow_unaligned_mem_16,
.sse,
.vzeroupper,
.x87,
}),
};
pub const athlon_fx = CpuModel{
.name = "athlon_fx",
.llvm_name = "athlon-fx",
.features = featureSet(&[_]Feature{
.@"3dnowa",
.@"64bit",
.cmov,
.cx8,
.fast_scalar_shift_masks,
.fxsr,
.nopl,
.slow_shld,
.slow_unaligned_mem_16,
.sse2,
.vzeroupper,
.x87,
}),
};
pub const athlon_mp = CpuModel{
.name = "athlon_mp",
.llvm_name = "athlon-mp",
.features = featureSet(&[_]Feature{
.@"3dnowa",
.cmov,
.cx8,
.fxsr,
.nopl,
.slow_shld,
.slow_unaligned_mem_16,
.sse,
.vzeroupper,
.x87,
}),
};
pub const athlon_tbird = CpuModel{
.name = "athlon_tbird",
.llvm_name = "athlon-tbird",
.features = featureSet(&[_]Feature{
.@"3dnowa",
.cmov,
.cx8,
.nopl,
.slow_shld,
.slow_unaligned_mem_16,
.vzeroupper,
.x87,
}),
};
pub const athlon_xp = CpuModel{
.name = "athlon_xp",
.llvm_name = "athlon-xp",
.features = featureSet(&[_]Feature{
.@"3dnowa",
.cmov,
.cx8,
.fxsr,
.nopl,
.slow_shld,
.slow_unaligned_mem_16,
.sse,
.vzeroupper,
.x87,
}),
};
pub const athlon64 = CpuModel{
.name = "athlon64",
.llvm_name = "athlon64",
.features = featureSet(&[_]Feature{
.@"3dnowa",
.@"64bit",
.cmov,
.cx8,
.fast_scalar_shift_masks,
.fxsr,
.nopl,
.slow_shld,
.slow_unaligned_mem_16,
.sse2,
.vzeroupper,
.x87,
}),
};
pub const athlon64_sse3 = CpuModel{
.name = "athlon64_sse3",
.llvm_name = "athlon64-sse3",
.features = featureSet(&[_]Feature{
.@"3dnowa",
.@"64bit",
.cmov,
.cx16,
.cx8,
.fast_scalar_shift_masks,
.fxsr,
.nopl,
.slow_shld,
.slow_unaligned_mem_16,
.sse3,
.vzeroupper,
.x87,
}),
};
pub const atom = CpuModel{
.name = "atom",
.llvm_name = "atom",
.features = featureSet(&[_]Feature{
.@"64bit",
.cmov,
.cx16,
.cx8,
.fxsr,
.idivl_to_divb,
.idivq_to_divl,
.lea_sp,
.lea_uses_ag,
.mmx,
.movbe,
.nopl,
.pad_short_functions,
.sahf,
.slow_two_mem_ops,
.slow_unaligned_mem_16,
.ssse3,
.vzeroupper,
.x87,
}),
};
pub const barcelona = CpuModel{
.name = "barcelona",
.llvm_name = "barcelona",
.features = featureSet(&[_]Feature{
.@"3dnowa",
.@"64bit",
.cmov,
.cx16,
.cx8,
.fast_scalar_shift_masks,
.fxsr,
.lzcnt,
.nopl,
.popcnt,
.prfchw,
.sahf,
.slow_shld,
.sse4a,
.vzeroupper,
.x87,
}),
};
pub const bdver1 = CpuModel{
.name = "bdver1",
.llvm_name = "bdver1",
.features = featureSet(&[_]Feature{
.@"64bit",
.aes,
.branchfusion,
.cmov,
.cx16,
.cx8,
.fast_11bytenop,
.fast_scalar_shift_masks,
.fxsr,
.lwp,
.lzcnt,
.mmx,
.nopl,
.pclmul,
.popcnt,
.prfchw,
.sahf,
.slow_shld,
.vzeroupper,
.x87,
.xop,
.xsave,
}),
};
pub const bdver2 = CpuModel{
.name = "bdver2",
.llvm_name = "bdver2",
.features = featureSet(&[_]Feature{
.@"64bit",
.aes,
.bmi,
.branchfusion,
.cmov,
.cx16,
.cx8,
.f16c,
.fast_11bytenop,
.fast_bextr,
.fast_scalar_shift_masks,
.fma,
.fxsr,
.lwp,
.lzcnt,
.mmx,
.nopl,
.pclmul,
.popcnt,
.prfchw,
.sahf,
.slow_shld,
.tbm,
.vzeroupper,
.x87,
.xop,
.xsave,
}),
};
pub const bdver3 = CpuModel{
.name = "bdver3",
.llvm_name = "bdver3",
.features = featureSet(&[_]Feature{
.@"64bit",
.aes,
.bmi,
.branchfusion,
.cmov,
.cx16,
.cx8,
.f16c,
.fast_11bytenop,
.fast_bextr,
.fast_scalar_shift_masks,
.fma,
.fsgsbase,
.fxsr,
.lwp,
.lzcnt,
.mmx,
.nopl,
.pclmul,
.popcnt,
.prfchw,
.sahf,
.slow_shld,
.tbm,
.vzeroupper,
.x87,
.xop,
.xsave,
.xsaveopt,
}),
};
pub const bdver4 = CpuModel{
.name = "bdver4",
.llvm_name = "bdver4",
.features = featureSet(&[_]Feature{
.@"64bit",
.aes,
.avx2,
.bmi,
.bmi2,
.branchfusion,
.cmov,
.cx16,
.cx8,
.f16c,
.fast_11bytenop,
.fast_bextr,
.fast_scalar_shift_masks,
.fma,
.fsgsbase,
.fxsr,
.lwp,
.lzcnt,
.mmx,
.movbe,
.mwaitx,
.nopl,
.pclmul,
.popcnt,
.prfchw,
.rdrnd,
.sahf,
.slow_shld,
.tbm,
.vzeroupper,
.x87,
.xop,
.xsave,
.xsaveopt,
}),
};
pub const bonnell = CpuModel{
.name = "bonnell",
.llvm_name = "bonnell",
.features = featureSet(&[_]Feature{
.@"64bit",
.cmov,
.cx16,
.cx8,
.fxsr,
.idivl_to_divb,
.idivq_to_divl,
.lea_sp,
.lea_uses_ag,
.mmx,
.movbe,
.nopl,
.pad_short_functions,
.sahf,
.slow_two_mem_ops,
.slow_unaligned_mem_16,
.ssse3,
.vzeroupper,
.x87,
}),
};
pub const broadwell = CpuModel{
.name = "broadwell",
.llvm_name = "broadwell",
.features = featureSet(&[_]Feature{
.@"64bit",
.adx,
.avx,
.avx2,
.bmi,
.bmi2,
.cmov,
.cx16,
.cx8,
.ermsb,
.f16c,
.false_deps_lzcnt_tzcnt,
.false_deps_popcnt,
.fast_15bytenop,
.fast_scalar_fsqrt,
.fast_shld_rotate,
.fast_variable_shuffle,
.fma,
.fsgsbase,
.fxsr,
.idivq_to_divl,
.invpcid,
.lzcnt,
.macrofusion,
.merge_to_threeway_branch,
.mmx,
.movbe,
.nopl,
.pclmul,
.popcnt,
.prfchw,
.rdrnd,
.rdseed,
.sahf,
.slow_3ops_lea,
.sse4_2,
.vzeroupper,
.x87,
.xsave,
.xsaveopt,
}),
};
pub const btver1 = CpuModel{
.name = "btver1",
.llvm_name = "btver1",
.features = featureSet(&[_]Feature{
.@"64bit",
.cmov,
.cx16,
.cx8,
.fast_15bytenop,
.fast_scalar_shift_masks,
.fast_vector_shift_masks,
.fxsr,
.lzcnt,
.mmx,
.nopl,
.popcnt,
.prfchw,
.sahf,
.slow_shld,
.sse4a,
.ssse3,
.vzeroupper,
.x87,
}),
};
pub const btver2 = CpuModel{
.name = "btver2",
.llvm_name = "btver2",
.features = featureSet(&[_]Feature{
.@"64bit",
.aes,
.avx,
.bmi,
.cmov,
.cx16,
.cx8,
.f16c,
.fast_15bytenop,
.fast_bextr,
.fast_hops,
.fast_lzcnt,
.fast_scalar_shift_masks,
.fast_vector_shift_masks,
.fxsr,
.lzcnt,
.mmx,
.movbe,
.nopl,
.pclmul,
.popcnt,
.prfchw,
.sahf,
.slow_shld,
.sse4a,
.ssse3,
.x87,
.xsave,
.xsaveopt,
}),
};
pub const c3 = CpuModel{
.name = "c3",
.llvm_name = "c3",
.features = featureSet(&[_]Feature{
.@"3dnow",
.slow_unaligned_mem_16,
.vzeroupper,
.x87,
}),
};
pub const c3_2 = CpuModel{
.name = "c3_2",
.llvm_name = "c3-2",
.features = featureSet(&[_]Feature{
.cmov,
.cx8,
.fxsr,
.mmx,
.slow_unaligned_mem_16,
.sse,
.vzeroupper,
.x87,
}),
};
pub const cannonlake = CpuModel{
.name = "cannonlake",
.llvm_name = "cannonlake",
.features = featureSet(&[_]Feature{
.@"64bit",
.adx,
.aes,
.avx,
.avx2,
.avx512bw,
.avx512cd,
.avx512dq,
.avx512f,
.avx512ifma,
.avx512vbmi,
.avx512vl,
.bmi,
.bmi2,
.clflushopt,
.cmov,
.cx16,
.cx8,
.ermsb,
.f16c,
.fast_15bytenop,
.fast_gather,
.fast_scalar_fsqrt,
.fast_shld_rotate,
.fast_variable_shuffle,
.fast_vector_fsqrt,
.fma,
.fsgsbase,
.fxsr,
.idivq_to_divl,
.invpcid,
.lzcnt,
.macrofusion,
.merge_to_threeway_branch,
.mmx,
.movbe,
.nopl,
.pclmul,
.pku,
.popcnt,
.prefer_256_bit,
.prfchw,
.rdrnd,
.rdseed,
.sahf,
.sgx,
.sha,
.slow_3ops_lea,
.sse4_2,
.vzeroupper,
.x87,
.xsave,
.xsavec,
.xsaveopt,
.xsaves,
}),
};
pub const cascadelake = CpuModel{
.name = "cascadelake",
.llvm_name = "cascadelake",
.features = featureSet(&[_]Feature{
.@"64bit",
.adx,
.aes,
.avx,
.avx2,
.avx512bw,
.avx512cd,
.avx512dq,
.avx512f,
.avx512vl,
.avx512vnni,
.bmi,
.bmi2,
.clflushopt,
.clwb,
.cmov,
.cx16,
.cx8,
.ermsb,
.f16c,
.false_deps_popcnt,
.fast_15bytenop,
.fast_gather,
.fast_scalar_fsqrt,
.fast_shld_rotate,
.fast_variable_shuffle,
.fast_vector_fsqrt,
.fma,
.fsgsbase,
.fxsr,
.idivq_to_divl,
.invpcid,
.lzcnt,
.macrofusion,
.merge_to_threeway_branch,
.mmx,
.movbe,
.nopl,
.pclmul,
.pku,
.popcnt,
.prefer_256_bit,
.prfchw,
.rdrnd,
.rdseed,
.sahf,
.slow_3ops_lea,
.sse4_2,
.vzeroupper,
.x87,
.xsave,
.xsavec,
.xsaveopt,
.xsaves,
}),
};
pub const cooperlake = CpuModel{
.name = "cooperlake",
.llvm_name = "cooperlake",
.features = featureSet(&[_]Feature{
.@"64bit",
.adx,
.aes,
.avx,
.avx2,
.avx512bf16,
.avx512bw,
.avx512cd,
.avx512dq,
.avx512f,
.avx512vl,
.avx512vnni,
.bmi,
.bmi2,
.clflushopt,
.clwb,
.cmov,
.cx16,
.cx8,
.ermsb,
.f16c,
.false_deps_popcnt,
.fast_15bytenop,
.fast_gather,
.fast_scalar_fsqrt,
.fast_shld_rotate,
.fast_variable_shuffle,
.fast_vector_fsqrt,
.fma,
.fsgsbase,
.fxsr,
.idivq_to_divl,
.invpcid,
.lzcnt,
.macrofusion,
.merge_to_threeway_branch,
.mmx,
.movbe,
.nopl,
.pclmul,
.pku,
.popcnt,
.prefer_256_bit,
.prfchw,
.rdrnd,
.rdseed,
.sahf,
.slow_3ops_lea,
.sse4_2,
.vzeroupper,
.x87,
.xsave,
.xsavec,
.xsaveopt,
.xsaves,
}),
};
pub const core_avx_i = CpuModel{
.name = "core_avx_i",
.llvm_name = "core-avx-i",
.features = featureSet(&[_]Feature{
.@"64bit",
.avx,
.cmov,
.cx16,
.cx8,
.f16c,
.false_deps_popcnt,
.fast_15bytenop,
.fast_scalar_fsqrt,
.fast_shld_rotate,
.fsgsbase,
.fxsr,
.idivq_to_divl,
.macrofusion,
.merge_to_threeway_branch,
.mmx,
.nopl,
.pclmul,
.popcnt,
.rdrnd,
.sahf,
.slow_3ops_lea,
.slow_unaligned_mem_32,
.sse4_2,
.vzeroupper,
.x87,
.xsave,
.xsaveopt,
}),
};
pub const core_avx2 = CpuModel{
.name = "core_avx2",
.llvm_name = "core-avx2",
.features = featureSet(&[_]Feature{
.@"64bit",
.avx,
.avx2,
.bmi,
.bmi2,
.cmov,
.cx16,
.cx8,
.ermsb,
.f16c,
.false_deps_lzcnt_tzcnt,
.false_deps_popcnt,
.fast_15bytenop,
.fast_scalar_fsqrt,
.fast_shld_rotate,
.fast_variable_shuffle,
.fma,
.fsgsbase,
.fxsr,
.idivq_to_divl,
.invpcid,
.lzcnt,
.macrofusion,
.merge_to_threeway_branch,
.mmx,
.movbe,
.nopl,
.pclmul,
.popcnt,
.rdrnd,
.sahf,
.slow_3ops_lea,
.sse4_2,
.vzeroupper,
.x87,
.xsave,
.xsaveopt,
}),
};
pub const core2 = CpuModel{
.name = "core2",
.llvm_name = "core2",
.features = featureSet(&[_]Feature{
.@"64bit",
.cmov,
.cx16,
.cx8,
.fxsr,
.macrofusion,
.mmx,
.nopl,
.sahf,
.slow_unaligned_mem_16,
.ssse3,
.vzeroupper,
.x87,
}),
};
pub const corei7 = CpuModel{
.name = "corei7",
.llvm_name = "corei7",
.features = featureSet(&[_]Feature{
.@"64bit",
.cmov,
.cx16,
.cx8,
.fxsr,
.macrofusion,
.mmx,
.nopl,
.popcnt,
.sahf,
.sse4_2,
.vzeroupper,
.x87,
}),
};
pub const corei7_avx = CpuModel{
.name = "corei7_avx",
.llvm_name = "corei7-avx",
.features = featureSet(&[_]Feature{
.@"64bit",
.avx,
.cmov,
.cx16,
.cx8,
.false_deps_popcnt,
.fast_15bytenop,
.fast_scalar_fsqrt,
.fast_shld_rotate,
.fxsr,
.idivq_to_divl,
.macrofusion,
.merge_to_threeway_branch,
.mmx,
.nopl,
.pclmul,
.popcnt,
.sahf,
.slow_3ops_lea,
.slow_unaligned_mem_32,
.sse4_2,
.vzeroupper,
.x87,
.xsave,
.xsaveopt,
}),
};
pub const generic = CpuModel{
.name = "generic",
.llvm_name = "generic",
.features = featureSet(&[_]Feature{
.cx8,
.slow_unaligned_mem_16,
.vzeroupper,
.x87,
}),
};
pub const geode = CpuModel{
.name = "geode",
.llvm_name = "geode",
.features = featureSet(&[_]Feature{
.@"3dnowa",
.cx8,
.slow_unaligned_mem_16,
.vzeroupper,
.x87,
}),
};
pub const goldmont = CpuModel{
.name = "goldmont",
.llvm_name = "goldmont",
.features = featureSet(&[_]Feature{
.@"64bit",
.aes,
.clflushopt,
.cmov,
.cx16,
.cx8,
.false_deps_popcnt,
.fsgsbase,
.fxsr,
.mmx,
.movbe,
.nopl,
.pclmul,
.popcnt,
.prfchw,
.rdrnd,
.rdseed,
.sahf,
.sha,
.slow_incdec,
.slow_lea,
.slow_two_mem_ops,
.sse4_2,
.ssse3,
.use_glm_div_sqrt_costs,
.vzeroupper,
.x87,
.xsave,
.xsavec,
.xsaveopt,
.xsaves,
}),
};
pub const goldmont_plus = CpuModel{
.name = "goldmont_plus",
.llvm_name = "goldmont-plus",
.features = featureSet(&[_]Feature{
.@"64bit",
.aes,
.clflushopt,
.cmov,
.cx16,
.cx8,
.fsgsbase,
.fxsr,
.mmx,
.movbe,
.nopl,
.pclmul,
.popcnt,
.prfchw,
.ptwrite,
.rdpid,
.rdrnd,
.rdseed,
.sahf,
.sgx,
.sha,
.slow_incdec,
.slow_lea,
.slow_two_mem_ops,
.sse4_2,
.ssse3,
.use_glm_div_sqrt_costs,
.vzeroupper,
.x87,
.xsave,
.xsavec,
.xsaveopt,
.xsaves,
}),
};
pub const haswell = CpuModel{
.name = "haswell",
.llvm_name = "haswell",
.features = featureSet(&[_]Feature{
.@"64bit",
.avx,
.avx2,
.bmi,
.bmi2,
.cmov,
.cx16,
.cx8,
.ermsb,
.f16c,
.false_deps_lzcnt_tzcnt,
.false_deps_popcnt,
.fast_15bytenop,
.fast_scalar_fsqrt,
.fast_shld_rotate,
.fast_variable_shuffle,
.fma,
.fsgsbase,
.fxsr,
.idivq_to_divl,
.invpcid,
.lzcnt,
.macrofusion,
.merge_to_threeway_branch,
.mmx,
.movbe,
.nopl,
.pclmul,
.popcnt,
.rdrnd,
.sahf,
.slow_3ops_lea,
.sse4_2,
.vzeroupper,
.x87,
.xsave,
.xsaveopt,
}),
};
pub const _i386 = CpuModel{
.name = "_i386",
.llvm_name = "i386",
.features = featureSet(&[_]Feature{
.slow_unaligned_mem_16,
.vzeroupper,
.x87,
}),
};
pub const _i486 = CpuModel{
.name = "_i486",
.llvm_name = "i486",
.features = featureSet(&[_]Feature{
.slow_unaligned_mem_16,
.vzeroupper,
.x87,
}),
};
pub const _i586 = CpuModel{
.name = "_i586",
.llvm_name = "i586",
.features = featureSet(&[_]Feature{
.cx8,
.slow_unaligned_mem_16,
.vzeroupper,
.x87,
}),
};
pub const _i686 = CpuModel{
.name = "_i686",
.llvm_name = "i686",
.features = featureSet(&[_]Feature{
.cmov,
.cx8,
.slow_unaligned_mem_16,
.vzeroupper,
.x87,
}),
};
pub const icelake_client = CpuModel{
.name = "icelake_client",
.llvm_name = "icelake-client",
.features = featureSet(&[_]Feature{
.@"64bit",
.adx,
.aes,
.avx,
.avx2,
.avx512bitalg,
.avx512bw,
.avx512cd,
.avx512dq,
.avx512f,
.avx512ifma,
.avx512vbmi,
.avx512vbmi2,
.avx512vl,
.avx512vnni,
.avx512vpopcntdq,
.bmi,
.bmi2,
.clflushopt,
.clwb,
.cmov,
.cx16,
.cx8,
.ermsb,
.f16c,
.fast_15bytenop,
.fast_gather,
.fast_scalar_fsqrt,
.fast_shld_rotate,
.fast_variable_shuffle,
.fast_vector_fsqrt,
.fma,
.fsgsbase,
.fxsr,
.gfni,
.idivq_to_divl,
.invpcid,
.lzcnt,
.macrofusion,
.merge_to_threeway_branch,
.mmx,
.movbe,
.nopl,
.pclmul,
.pku,
.popcnt,
.prefer_256_bit,
.prfchw,
.rdpid,
.rdrnd,
.rdseed,
.sahf,
.sgx,
.sha,
.slow_3ops_lea,
.sse4_2,
.vaes,
.vpclmulqdq,
.vzeroupper,
.x87,
.xsave,
.xsavec,
.xsaveopt,
.xsaves,
}),
};
pub const icelake_server = CpuModel{
.name = "icelake_server",
.llvm_name = "icelake-server",
.features = featureSet(&[_]Feature{
.@"64bit",
.adx,
.aes,
.avx,
.avx2,
.avx512bitalg,
.avx512bw,
.avx512cd,
.avx512dq,
.avx512f,
.avx512ifma,
.avx512vbmi,
.avx512vbmi2,
.avx512vl,
.avx512vnni,
.avx512vpopcntdq,
.bmi,
.bmi2,
.clflushopt,
.clwb,
.cmov,
.cx16,
.cx8,
.ermsb,
.f16c,
.fast_15bytenop,
.fast_gather,
.fast_scalar_fsqrt,
.fast_shld_rotate,
.fast_variable_shuffle,
.fast_vector_fsqrt,
.fma,
.fsgsbase,
.fxsr,
.gfni,
.idivq_to_divl,
.invpcid,
.lzcnt,
.macrofusion,
.merge_to_threeway_branch,
.mmx,
.movbe,
.nopl,
.pclmul,
.pconfig,
.pku,
.popcnt,
.prefer_256_bit,
.prfchw,
.rdpid,
.rdrnd,
.rdseed,
.sahf,
.sgx,
.sha,
.slow_3ops_lea,
.sse4_2,
.vaes,
.vpclmulqdq,
.vzeroupper,
.wbnoinvd,
.x87,
.xsave,
.xsavec,
.xsaveopt,
.xsaves,
}),
};
pub const ivybridge = CpuModel{
.name = "ivybridge",
.llvm_name = "ivybridge",
.features = featureSet(&[_]Feature{
.@"64bit",
.avx,
.cmov,
.cx16,
.cx8,
.f16c,
.false_deps_popcnt,
.fast_15bytenop,
.fast_scalar_fsqrt,
.fast_shld_rotate,
.fsgsbase,
.fxsr,
.idivq_to_divl,
.macrofusion,
.merge_to_threeway_branch,
.mmx,
.nopl,
.pclmul,
.popcnt,
.rdrnd,
.sahf,
.slow_3ops_lea,
.slow_unaligned_mem_32,
.sse4_2,
.vzeroupper,
.x87,
.xsave,
.xsaveopt,
}),
};
pub const k6 = CpuModel{
.name = "k6",
.llvm_name = "k6",
.features = featureSet(&[_]Feature{
.cx8,
.mmx,
.slow_unaligned_mem_16,
.vzeroupper,
.x87,
}),
};
pub const k6_2 = CpuModel{
.name = "k6_2",
.llvm_name = "k6-2",
.features = featureSet(&[_]Feature{
.@"3dnow",
.cx8,
.slow_unaligned_mem_16,
.vzeroupper,
.x87,
}),
};
pub const k6_3 = CpuModel{
.name = "k6_3",
.llvm_name = "k6-3",
.features = featureSet(&[_]Feature{
.@"3dnow",
.cx8,
.slow_unaligned_mem_16,
.vzeroupper,
.x87,
}),
};
pub const k8 = CpuModel{
.name = "k8",
.llvm_name = "k8",
.features = featureSet(&[_]Feature{
.@"3dnowa",
.@"64bit",
.cmov,
.cx8,
.fast_scalar_shift_masks,
.fxsr,
.nopl,
.slow_shld,
.slow_unaligned_mem_16,
.sse2,
.vzeroupper,
.x87,
}),
};
pub const k8_sse3 = CpuModel{
.name = "k8_sse3",
.llvm_name = "k8-sse3",
.features = featureSet(&[_]Feature{
.@"3dnowa",
.@"64bit",
.cmov,
.cx16,
.cx8,
.fast_scalar_shift_masks,
.fxsr,
.nopl,
.slow_shld,
.slow_unaligned_mem_16,
.sse3,
.vzeroupper,
.x87,
}),
};
pub const knl = CpuModel{
.name = "knl",
.llvm_name = "knl",
.features = featureSet(&[_]Feature{
.@"64bit",
.adx,
.aes,
.avx512cd,
.avx512er,
.avx512f,
.avx512pf,
.bmi,
.bmi2,
.cmov,
.cx16,
.cx8,
.f16c,
.fast_gather,
.fma,
.fsgsbase,
.fxsr,
.idivq_to_divl,
.lzcnt,
.mmx,
.movbe,
.nopl,
.pclmul,
.popcnt,
.prefer_mask_registers,
.prefetchwt1,
.prfchw,
.rdrnd,
.rdseed,
.sahf,
.slow_3ops_lea,
.slow_incdec,
.slow_pmaddwd,
.slow_two_mem_ops,
.x87,
.xsave,
.xsaveopt,
}),
};
pub const knm = CpuModel{
.name = "knm",
.llvm_name = "knm",
.features = featureSet(&[_]Feature{
.@"64bit",
.adx,
.aes,
.avx512cd,
.avx512er,
.avx512f,
.avx512pf,
.avx512vpopcntdq,
.bmi,
.bmi2,
.cmov,
.cx16,
.cx8,
.f16c,
.fast_gather,
.fma,
.fsgsbase,
.fxsr,
.idivq_to_divl,
.lzcnt,
.mmx,
.movbe,
.nopl,
.pclmul,
.popcnt,
.prefer_mask_registers,
.prefetchwt1,
.prfchw,
.rdrnd,
.rdseed,
.sahf,
.slow_3ops_lea,
.slow_incdec,
.slow_pmaddwd,
.slow_two_mem_ops,
.x87,
.xsave,
.xsaveopt,
}),
};
pub const lakemont = CpuModel{
.name = "lakemont",
.llvm_name = "lakemont",
.features = featureSet(&[_]Feature{
.vzeroupper,
}),
};
pub const nehalem = CpuModel{
.name = "nehalem",
.llvm_name = "nehalem",
.features = featureSet(&[_]Feature{
.@"64bit",
.cmov,
.cx16,
.cx8,
.fxsr,
.macrofusion,
.mmx,
.nopl,
.popcnt,
.sahf,
.sse4_2,
.vzeroupper,
.x87,
}),
};
pub const nocona = CpuModel{
.name = "nocona",
.llvm_name = "nocona",
.features = featureSet(&[_]Feature{
.@"64bit",
.cmov,
.cx16,
.cx8,
.fxsr,
.mmx,
.nopl,
.slow_unaligned_mem_16,
.sse3,
.vzeroupper,
.x87,
}),
};
pub const opteron = CpuModel{
.name = "opteron",
.llvm_name = "opteron",
.features = featureSet(&[_]Feature{
.@"3dnowa",
.@"64bit",
.cmov,
.cx8,
.fast_scalar_shift_masks,
.fxsr,
.nopl,
.slow_shld,
.slow_unaligned_mem_16,
.sse2,
.vzeroupper,
.x87,
}),
};
pub const opteron_sse3 = CpuModel{
.name = "opteron_sse3",
.llvm_name = "opteron-sse3",
.features = featureSet(&[_]Feature{
.@"3dnowa",
.@"64bit",
.cmov,
.cx16,
.cx8,
.fast_scalar_shift_masks,
.fxsr,
.nopl,
.slow_shld,
.slow_unaligned_mem_16,
.sse3,
.vzeroupper,
.x87,
}),
};
pub const penryn = CpuModel{
.name = "penryn",
.llvm_name = "penryn",
.features = featureSet(&[_]Feature{
.@"64bit",
.cmov,
.cx16,
.cx8,
.fxsr,
.macrofusion,
.mmx,
.nopl,
.sahf,
.slow_unaligned_mem_16,
.sse4_1,
.vzeroupper,
.x87,
}),
};
pub const pentium = CpuModel{
.name = "pentium",
.llvm_name = "pentium",
.features = featureSet(&[_]Feature{
.cx8,
.slow_unaligned_mem_16,
.vzeroupper,
.x87,
}),
};
pub const pentium_m = CpuModel{
.name = "pentium_m",
.llvm_name = "pentium-m",
.features = featureSet(&[_]Feature{
.cmov,
.cx8,
.fxsr,
.mmx,
.nopl,
.slow_unaligned_mem_16,
.sse2,
.vzeroupper,
.x87,
}),
};
pub const pentium_mmx = CpuModel{
.name = "pentium_mmx",
.llvm_name = "pentium-mmx",
.features = featureSet(&[_]Feature{
.cx8,
.mmx,
.slow_unaligned_mem_16,
.vzeroupper,
.x87,
}),
};
pub const pentium2 = CpuModel{
.name = "pentium2",
.llvm_name = "pentium2",
.features = featureSet(&[_]Feature{
.cmov,
.cx8,
.fxsr,
.mmx,
.nopl,
.slow_unaligned_mem_16,
.vzeroupper,
.x87,
}),
};
pub const pentium3 = CpuModel{
.name = "pentium3",
.llvm_name = "pentium3",
.features = featureSet(&[_]Feature{
.cmov,
.cx8,
.fxsr,
.mmx,
.nopl,
.slow_unaligned_mem_16,
.sse,
.vzeroupper,
.x87,
}),
};
pub const pentium3m = CpuModel{
.name = "pentium3m",
.llvm_name = "pentium3m",
.features = featureSet(&[_]Feature{
.cmov,
.cx8,
.fxsr,
.mmx,
.nopl,
.slow_unaligned_mem_16,
.sse,
.vzeroupper,
.x87,
}),
};
pub const pentium4 = CpuModel{
.name = "pentium4",
.llvm_name = "pentium4",
.features = featureSet(&[_]Feature{
.cmov,
.cx8,
.fxsr,
.mmx,
.nopl,
.slow_unaligned_mem_16,
.sse2,
.vzeroupper,
.x87,
}),
};
pub const pentium4m = CpuModel{
.name = "pentium4m",
.llvm_name = "pentium4m",
.features = featureSet(&[_]Feature{
.cmov,
.cx8,
.fxsr,
.mmx,
.nopl,
.slow_unaligned_mem_16,
.sse2,
.vzeroupper,
.x87,
}),
};
pub const pentiumpro = CpuModel{
.name = "pentiumpro",
.llvm_name = "pentiumpro",
.features = featureSet(&[_]Feature{
.cmov,
.cx8,
.nopl,
.slow_unaligned_mem_16,
.vzeroupper,
.x87,
}),
};
pub const prescott = CpuModel{
.name = "prescott",
.llvm_name = "prescott",
.features = featureSet(&[_]Feature{
.cmov,
.cx8,
.fxsr,
.mmx,
.nopl,
.slow_unaligned_mem_16,
.sse3,
.vzeroupper,
.x87,
}),
};
pub const sandybridge = CpuModel{
.name = "sandybridge",
.llvm_name = "sandybridge",
.features = featureSet(&[_]Feature{
.@"64bit",
.avx,
.cmov,
.cx16,
.cx8,
.false_deps_popcnt,
.fast_15bytenop,
.fast_scalar_fsqrt,
.fast_shld_rotate,
.fxsr,
.idivq_to_divl,
.macrofusion,
.merge_to_threeway_branch,
.mmx,
.nopl,
.pclmul,
.popcnt,
.sahf,
.slow_3ops_lea,
.slow_unaligned_mem_32,
.sse4_2,
.vzeroupper,
.x87,
.xsave,
.xsaveopt,
}),
};
pub const silvermont = CpuModel{
.name = "silvermont",
.llvm_name = "silvermont",
.features = featureSet(&[_]Feature{
.@"64bit",
.cmov,
.cx16,
.cx8,
.false_deps_popcnt,
.fast_7bytenop,
.fxsr,
.idivq_to_divl,
.mmx,
.movbe,
.nopl,
.pclmul,
.popcnt,
.prfchw,
.rdrnd,
.sahf,
.slow_incdec,
.slow_lea,
.slow_pmulld,
.slow_two_mem_ops,
.sse4_2,
.ssse3,
.vzeroupper,
.x87,
}),
};
pub const skx = CpuModel{
.name = "skx",
.llvm_name = "skx",
.features = featureSet(&[_]Feature{
.@"64bit",
.adx,
.aes,
.avx,
.avx2,
.avx512bw,
.avx512cd,
.avx512dq,
.avx512f,
.avx512vl,
.bmi,
.bmi2,
.clflushopt,
.clwb,
.cmov,
.cx16,
.cx8,
.ermsb,
.f16c,
.false_deps_popcnt,
.fast_15bytenop,
.fast_gather,
.fast_scalar_fsqrt,
.fast_shld_rotate,
.fast_variable_shuffle,
.fast_vector_fsqrt,
.fma,
.fsgsbase,
.fxsr,
.idivq_to_divl,
.invpcid,
.lzcnt,
.macrofusion,
.merge_to_threeway_branch,
.mmx,
.movbe,
.nopl,
.pclmul,
.pku,
.popcnt,
.prefer_256_bit,
.prfchw,
.rdrnd,
.rdseed,
.sahf,
.slow_3ops_lea,
.sse4_2,
.vzeroupper,
.x87,
.xsave,
.xsavec,
.xsaveopt,
.xsaves,
}),
};
pub const skylake = CpuModel{
.name = "skylake",
.llvm_name = "skylake",
.features = featureSet(&[_]Feature{
.@"64bit",
.adx,
.aes,
.avx,
.avx2,
.bmi,
.bmi2,
.clflushopt,
.cmov,
.cx16,
.cx8,
.ermsb,
.f16c,
.false_deps_popcnt,
.fast_15bytenop,
.fast_gather,
.fast_scalar_fsqrt,
.fast_shld_rotate,
.fast_variable_shuffle,
.fast_vector_fsqrt,
.fma,
.fsgsbase,
.fxsr,
.idivq_to_divl,
.invpcid,
.lzcnt,
.macrofusion,
.merge_to_threeway_branch,
.mmx,
.movbe,
.nopl,
.pclmul,
.popcnt,
.prfchw,
.rdrnd,
.rdseed,
.sahf,
.sgx,
.slow_3ops_lea,
.sse4_2,
.vzeroupper,
.x87,
.xsave,
.xsavec,
.xsaveopt,
.xsaves,
}),
};
pub const skylake_avx512 = CpuModel{
.name = "skylake_avx512",
.llvm_name = "skylake-avx512",
.features = featureSet(&[_]Feature{
.@"64bit",
.adx,
.aes,
.avx,
.avx2,
.avx512bw,
.avx512cd,
.avx512dq,
.avx512f,
.avx512vl,
.bmi,
.bmi2,
.clflushopt,
.clwb,
.cmov,
.cx16,
.cx8,
.ermsb,
.f16c,
.false_deps_popcnt,
.fast_15bytenop,
.fast_gather,
.fast_scalar_fsqrt,
.fast_shld_rotate,
.fast_variable_shuffle,
.fast_vector_fsqrt,
.fma,
.fsgsbase,
.fxsr,
.idivq_to_divl,
.invpcid,
.lzcnt,
.macrofusion,
.merge_to_threeway_branch,
.mmx,
.movbe,
.nopl,
.pclmul,
.pku,
.popcnt,
.prefer_256_bit,
.prfchw,
.rdrnd,
.rdseed,
.sahf,
.slow_3ops_lea,
.sse4_2,
.vzeroupper,
.x87,
.xsave,
.xsavec,
.xsaveopt,
.xsaves,
}),
};
pub const slm = CpuModel{
.name = "slm",
.llvm_name = "slm",
.features = featureSet(&[_]Feature{
.@"64bit",
.cmov,
.cx16,
.cx8,
.false_deps_popcnt,
.fast_7bytenop,
.fxsr,
.idivq_to_divl,
.mmx,
.movbe,
.nopl,
.pclmul,
.popcnt,
.prfchw,
.rdrnd,
.sahf,
.slow_incdec,
.slow_lea,
.slow_pmulld,
.slow_two_mem_ops,
.sse4_2,
.ssse3,
.vzeroupper,
.x87,
}),
};
pub const tigerlake = CpuModel{
.name = "tigerlake",
.llvm_name = "tigerlake",
.features = featureSet(&[_]Feature{
.@"64bit",
.adx,
.aes,
.avx,
.avx2,
.avx512bitalg,
.avx512bw,
.avx512cd,
.avx512dq,
.avx512f,
.avx512ifma,
.avx512vbmi,
.avx512vbmi2,
.avx512vl,
.avx512vnni,
.avx512vp2intersect,
.avx512vpopcntdq,
.bmi,
.bmi2,
.clflushopt,
.clwb,
.cmov,
.cx16,
.cx8,
.ermsb,
.f16c,
.fast_15bytenop,
.fast_gather,
.fast_scalar_fsqrt,
.fast_shld_rotate,
.fast_variable_shuffle,
.fast_vector_fsqrt,
.fma,
.fsgsbase,
.fxsr,
.gfni,
.idivq_to_divl,
.invpcid,
.lzcnt,
.macrofusion,
.merge_to_threeway_branch,
.mmx,
.movbe,
.movdir64b,
.movdiri,
.nopl,
.pclmul,
.pku,
.popcnt,
.prefer_256_bit,
.prfchw,
.rdpid,
.rdrnd,
.rdseed,
.sahf,
.sgx,
.sha,
.shstk,
.slow_3ops_lea,
.sse4_2,
.vaes,
.vpclmulqdq,
.vzeroupper,
.x87,
.xsave,
.xsavec,
.xsaveopt,
.xsaves,
}),
};
pub const tremont = CpuModel{
.name = "tremont",
.llvm_name = "tremont",
.features = featureSet(&[_]Feature{
.@"64bit",
.aes,
.clflushopt,
.clwb,
.cmov,
.cx16,
.cx8,
.fsgsbase,
.fxsr,
.gfni,
.mmx,
.movbe,
.nopl,
.pclmul,
.popcnt,
.prfchw,
.ptwrite,
.rdpid,
.rdrnd,
.rdseed,
.sahf,
.sgx,
.sha,
.slow_incdec,
.slow_lea,
.slow_two_mem_ops,
.sse4_2,
.ssse3,
.use_glm_div_sqrt_costs,
.vzeroupper,
.x87,
.xsave,
.xsavec,
.xsaveopt,
.xsaves,
}),
};
pub const westmere = CpuModel{
.name = "westmere",
.llvm_name = "westmere",
.features = featureSet(&[_]Feature{
.@"64bit",
.cmov,
.cx16,
.cx8,
.fxsr,
.macrofusion,
.mmx,
.nopl,
.pclmul,
.popcnt,
.sahf,
.sse4_2,
.vzeroupper,
.x87,
}),
};
pub const winchip_c6 = CpuModel{
.name = "winchip_c6",
.llvm_name = "winchip-c6",
.features = featureSet(&[_]Feature{
.mmx,
.slow_unaligned_mem_16,
.vzeroupper,
.x87,
}),
};
pub const winchip2 = CpuModel{
.name = "winchip2",
.llvm_name = "winchip2",
.features = featureSet(&[_]Feature{
.@"3dnow",
.slow_unaligned_mem_16,
.vzeroupper,
.x87,
}),
};
pub const x86_64 = CpuModel{
.name = "x86_64",
.llvm_name = "x86-64",
.features = featureSet(&[_]Feature{
.@"64bit",
.cmov,
.cx8,
.fxsr,
.idivq_to_divl,
.macrofusion,
.mmx,
.nopl,
.slow_3ops_lea,
.slow_incdec,
.sse2,
.vzeroupper,
.x87,
}),
};
pub const yonah = CpuModel{
.name = "yonah",
.llvm_name = "yonah",
.features = featureSet(&[_]Feature{
.cmov,
.cx8,
.fxsr,
.mmx,
.nopl,
.slow_unaligned_mem_16,
.sse3,
.vzeroupper,
.x87,
}),
};
pub const znver1 = CpuModel{
.name = "znver1",
.llvm_name = "znver1",
.features = featureSet(&[_]Feature{
.@"64bit",
.adx,
.aes,
.avx2,
.bmi,
.bmi2,
.branchfusion,
.clflushopt,
.clzero,
.cmov,
.cx16,
.f16c,
.fast_15bytenop,
.fast_bextr,
.fast_lzcnt,
.fast_scalar_shift_masks,
.fma,
.fsgsbase,
.fxsr,
.lzcnt,
.mmx,
.movbe,
.mwaitx,
.nopl,
.pclmul,
.popcnt,
.prfchw,
.rdrnd,
.rdseed,
.sahf,
.sha,
.slow_shld,
.sse4a,
.vzeroupper,
.x87,
.xsave,
.xsavec,
.xsaveopt,
.xsaves,
}),
};
pub const znver2 = CpuModel{
.name = "znver2",
.llvm_name = "znver2",
.features = featureSet(&[_]Feature{
.@"64bit",
.adx,
.aes,
.avx2,
.bmi,
.bmi2,
.branchfusion,
.clflushopt,
.clwb,
.clzero,
.cmov,
.cx16,
.f16c,
.fast_15bytenop,
.fast_bextr,
.fast_lzcnt,
.fast_scalar_shift_masks,
.fma,
.fsgsbase,
.fxsr,
.lzcnt,
.mmx,
.movbe,
.mwaitx,
.nopl,
.pclmul,
.popcnt,
.prfchw,
.rdpid,
.rdrnd,
.rdseed,
.sahf,
.sha,
.slow_shld,
.sse4a,
.vzeroupper,
.wbnoinvd,
.x87,
.xsave,
.xsavec,
.xsaveopt,
.xsaves,
}),
};
}; | lib/std/target/x86.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const Target = std.Target;
const log = std.log.scoped(.codegen);
const spec = @import("spirv/spec.zig");
const Opcode = spec.Opcode;
const Module = @import("../Module.zig");
const Decl = Module.Decl;
const Type = @import("../type.zig").Type;
const Value = @import("../value.zig").Value;
const LazySrcLoc = Module.LazySrcLoc;
const ir = @import("../ir.zig");
const Inst = ir.Inst;
pub const TypeMap = std.HashMap(Type, u32, Type.hash, Type.eql, std.hash_map.default_max_load_percentage);
pub const ValueMap = std.AutoHashMap(*Inst, u32);
pub fn writeOpcode(code: *std.ArrayList(u32), opcode: Opcode, arg_count: u32) !void {
const word_count = arg_count + 1;
try code.append((word_count << 16) | @enumToInt(opcode));
}
pub fn writeInstruction(code: *std.ArrayList(u32), opcode: Opcode, args: []const u32) !void {
try writeOpcode(code, opcode, @intCast(u32, args.len));
try code.appendSlice(args);
}
/// This structure represents a SPIR-V binary module being compiled, and keeps track of relevant information
/// such as code for the different logical sections, and the next result-id.
pub const SPIRVModule = struct {
next_result_id: u32,
types_globals_constants: std.ArrayList(u32),
fn_decls: std.ArrayList(u32),
pub fn init(allocator: *Allocator) SPIRVModule {
return .{
.next_result_id = 1, // 0 is an invalid SPIR-V result ID.
.types_globals_constants = std.ArrayList(u32).init(allocator),
.fn_decls = std.ArrayList(u32).init(allocator),
};
}
pub fn deinit(self: *SPIRVModule) void {
self.types_globals_constants.deinit();
self.fn_decls.deinit();
}
pub fn allocResultId(self: *SPIRVModule) u32 {
defer self.next_result_id += 1;
return self.next_result_id;
}
pub fn resultIdBound(self: *SPIRVModule) u32 {
return self.next_result_id;
}
};
/// This structure is used to compile a declaration, and contains all relevant meta-information to deal with that.
pub const DeclGen = struct {
module: *Module,
spv: *SPIRVModule,
args: std.ArrayList(u32),
next_arg_index: u32,
types: TypeMap,
values: ValueMap,
decl: *Decl,
error_msg: ?*Module.ErrorMsg,
const Error = error{ AnalysisFail, OutOfMemory };
/// This structure is used to return information about a type typically used for arithmetic operations.
/// These types may either be integers, floats, or a vector of these. Most scalar operations also work on vectors,
/// so we can easily represent those as arithmetic types.
/// If the type is a scalar, 'inner type' refers to the scalar type. Otherwise, if its a vector, it refers
/// to the vector's element type.
const ArithmeticTypeInfo = struct {
/// A classification of the inner type.
const Class = enum {
/// A boolean.
bool,
/// A regular, **native**, integer.
/// This is only returned when the backend supports this int as a native type (when
/// the relevant capability is enabled).
integer,
/// A regular float. These are all required to be natively supported. Floating points for
/// which the relevant capability is not enabled are not emulated.
float,
/// An integer of a 'strange' size (which' bit size is not the same as its backing type. **Note**: this
/// may **also** include power-of-2 integers for which the relevant capability is not enabled), but still
/// within the limits of the largest natively supported integer type.
strange_integer,
/// An integer with more bits than the largest natively supported integer type.
composite_integer,
};
/// The number of bits in the inner type.
/// Note: this is the actual number of bits of the type, not the size of the backing integer.
bits: u16,
/// Whether the type is a vector.
is_vector: bool,
/// Whether the inner type is signed. Only relevant for integers.
signedness: std.builtin.Signedness,
/// A classification of the inner type. These scenarios
/// will all have to be handled slightly different.
class: Class,
};
fn fail(self: *DeclGen, src: LazySrcLoc, comptime format: []const u8, args: anytype) Error {
@setCold(true);
const src_loc = src.toSrcLocWithDecl(self.decl);
self.error_msg = try Module.ErrorMsg.create(self.module.gpa, src_loc, format, args);
return error.AnalysisFail;
}
fn resolve(self: *DeclGen, inst: *Inst) !u32 {
if (inst.value()) |val| {
return self.genConstant(inst.ty, val);
}
return self.values.get(inst).?; // Instruction does not dominate all uses!
}
/// SPIR-V requires enabling specific integer sizes through capabilities, and so if they are not enabled, we need
/// to emulate them in other instructions/types. This function returns, given an integer bit width (signed or unsigned, sign
/// included), the width of the underlying type which represents it, given the enabled features for the current target.
/// If the result is `null`, the largest type the target platform supports natively is not able to perform computations using
/// that size. In this case, multiple elements of the largest type should be used.
/// The backing type will be chosen as the smallest supported integer larger or equal to it in number of bits.
/// The result is valid to be used with OpTypeInt.
/// TODO: The extension SPV_INTEL_arbitrary_precision_integers allows any integer size (at least up to 32 bits).
/// TODO: This probably needs an ABI-version as well (especially in combination with SPV_INTEL_arbitrary_precision_integers).
/// TODO: Should the result of this function be cached?
fn backingIntBits(self: *DeclGen, bits: u16) ?u16 {
const target = self.module.getTarget();
// TODO: Figure out what to do with u0/i0.
std.debug.assert(bits != 0);
// 8, 16 and 64-bit integers require the Int8, Int16 and Inr64 capabilities respectively.
// 32-bit integers are always supported (see spec, 2.16.1, Data rules).
const ints = [_]struct { bits: u16, feature: ?Target.spirv.Feature }{
.{ .bits = 8, .feature = .Int8 },
.{ .bits = 16, .feature = .Int16 },
.{ .bits = 32, .feature = null },
.{ .bits = 64, .feature = .Int64 },
};
for (ints) |int| {
const has_feature = if (int.feature) |feature|
Target.spirv.featureSetHas(target.cpu.features, feature)
else
true;
if (bits <= int.bits and has_feature) {
return int.bits;
}
}
return null;
}
/// Return the amount of bits in the largest supported integer type. This is either 32 (always supported), or 64 (if
/// the Int64 capability is enabled).
/// Note: The extension SPV_INTEL_arbitrary_precision_integers allows any integer size (at least up to 32 bits).
/// In theory that could also be used, but since the spec says that it only guarantees support up to 32-bit ints there
/// is no way of knowing whether those are actually supported.
/// TODO: Maybe this should be cached?
fn largestSupportedIntBits(self: *DeclGen) u16 {
const target = self.module.getTarget();
return if (Target.spirv.featureSetHas(target.cpu.features, .Int64))
64
else
32;
}
/// Checks whether the type is "composite int", an integer consisting of multiple native integers. These are represented by
/// arrays of largestSupportedIntBits().
/// Asserts `ty` is an integer.
fn isCompositeInt(self: *DeclGen, ty: Type) bool {
return self.backingIntBits(ty) == null;
}
fn arithmeticTypeInfo(self: *DeclGen, ty: Type) !ArithmeticTypeInfo {
const target = self.module.getTarget();
return switch (ty.zigTypeTag()) {
.Bool => ArithmeticTypeInfo{
.bits = 1, // Doesn't matter for this class.
.is_vector = false,
.signedness = .unsigned, // Technically, but doesn't matter for this class.
.class = .bool,
},
.Float => ArithmeticTypeInfo{
.bits = ty.floatBits(target),
.is_vector = false,
.signedness = .signed, // Technically, but doesn't matter for this class.
.class = .float,
},
.Int => blk: {
const int_info = ty.intInfo(target);
// TODO: Maybe it's useful to also return this value.
const maybe_backing_bits = self.backingIntBits(int_info.bits);
break :blk ArithmeticTypeInfo{ .bits = int_info.bits, .is_vector = false, .signedness = int_info.signedness, .class = if (maybe_backing_bits) |backing_bits|
if (backing_bits == int_info.bits)
ArithmeticTypeInfo.Class.integer
else
ArithmeticTypeInfo.Class.strange_integer
else
.composite_integer };
},
// As of yet, there is no vector support in the self-hosted compiler.
.Vector => self.fail(.{ .node_offset = 0 }, "TODO: SPIR-V backend: implement arithmeticTypeInfo for Vector", .{}),
// TODO: For which types is this the case?
else => self.fail(.{ .node_offset = 0 }, "TODO: SPIR-V backend: implement arithmeticTypeInfo for {}", .{ty}),
};
}
/// Generate a constant representing `val`.
/// TODO: Deduplication?
fn genConstant(self: *DeclGen, ty: Type, val: Value) Error!u32 {
const code = &self.spv.types_globals_constants;
const result_id = self.spv.allocResultId();
const result_type_id = try self.getOrGenType(ty);
if (val.isUndef()) {
try writeInstruction(code, .OpUndef, &[_]u32{ result_type_id, result_id });
return result_id;
}
switch (ty.zigTypeTag()) {
.Bool => {
const opcode: Opcode = if (val.toBool()) .OpConstantTrue else .OpConstantFalse;
try writeInstruction(code, opcode, &[_]u32{ result_type_id, result_id });
},
.Float => {
// At this point we are guaranteed that the target floating point type is supported, otherwise the function
// would have exited at getOrGenType(ty).
// f16 and f32 require one word of storage. f64 requires 2, low-order first.
switch (val.tag()) {
.float_16 => try writeInstruction(code, .OpConstant, &[_]u32{ result_type_id, result_id, @bitCast(u16, val.castTag(.float_16).?.data) }),
.float_32 => try writeInstruction(code, .OpConstant, &[_]u32{ result_type_id, result_id, @bitCast(u32, val.castTag(.float_32).?.data) }),
.float_64 => {
const float_bits = @bitCast(u64, val.castTag(.float_64).?.data);
try writeInstruction(code, .OpConstant, &[_]u32{
result_type_id,
result_id,
@truncate(u32, float_bits),
@truncate(u32, float_bits >> 32),
});
},
.float_128 => unreachable, // Filtered out in the call to getOrGenType.
// TODO: What tags do we need to handle here anyway?
else => return self.fail(.{ .node_offset = 0 }, "TODO: SPIR-V backend: float constant generation of value {s}\n", .{val.tag()}),
}
},
else => return self.fail(.{ .node_offset = 0 }, "TODO: SPIR-V backend: constant generation of type {s}\n", .{ty.zigTypeTag()}),
}
return result_id;
}
fn getOrGenType(self: *DeclGen, ty: Type) Error!u32 {
// We can't use getOrPut here so we can recursively generate types.
if (self.types.get(ty)) |already_generated| {
return already_generated;
}
const target = self.module.getTarget();
const code = &self.spv.types_globals_constants;
const result_id = self.spv.allocResultId();
switch (ty.zigTypeTag()) {
.Void => try writeInstruction(code, .OpTypeVoid, &[_]u32{result_id}),
.Bool => try writeInstruction(code, .OpTypeBool, &[_]u32{result_id}),
.Int => {
const int_info = ty.intInfo(target);
const backing_bits = self.backingIntBits(int_info.bits) orelse {
// Integers too big for any native type are represented as "composite integers": An array of largestSupportedIntBits.
return self.fail(.{ .node_offset = 0 }, "TODO: SPIR-V backend: implement composite ints {}", .{ty});
};
// TODO: If backing_bits != int_info.bits, a duplicate type might be generated here.
try writeInstruction(code, .OpTypeInt, &[_]u32{
result_id,
backing_bits,
switch (int_info.signedness) {
.unsigned => 0,
.signed => 1,
},
});
},
.Float => {
// We can (and want) not really emulate floating points with other floating point types like with the integer types,
// so if the float is not supported, just return an error.
const bits = ty.floatBits(target);
const supported = switch (bits) {
16 => Target.spirv.featureSetHas(target.cpu.features, .Float16),
// 32-bit floats are always supported (see spec, 2.16.1, Data rules).
32 => true,
64 => Target.spirv.featureSetHas(target.cpu.features, .Float64),
else => false,
};
if (!supported) {
return self.fail(.{ .node_offset = 0 }, "Floating point width of {} bits is not supported for the current SPIR-V feature set", .{bits});
}
try writeInstruction(code, .OpTypeFloat, &[_]u32{ result_id, bits });
},
.Fn => {
// We only support zig-calling-convention functions, no varargs.
if (ty.fnCallingConvention() != .Unspecified)
return self.fail(.{ .node_offset = 0 }, "Unsupported calling convention for SPIR-V", .{});
if (ty.fnIsVarArgs())
return self.fail(.{ .node_offset = 0 }, "VarArgs unsupported for SPIR-V", .{});
// In order to avoid a temporary here, first generate all the required types and then simply look them up
// when generating the function type.
const params = ty.fnParamLen();
var i: usize = 0;
while (i < params) : (i += 1) {
_ = try self.getOrGenType(ty.fnParamType(i));
}
const return_type_id = try self.getOrGenType(ty.fnReturnType());
// result id + result type id + parameter type ids.
try writeOpcode(code, .OpTypeFunction, 2 + @intCast(u32, ty.fnParamLen()));
try code.appendSlice(&.{ result_id, return_type_id });
i = 0;
while (i < params) : (i += 1) {
const param_type_id = self.types.get(ty.fnParamType(i)).?;
try code.append(param_type_id);
}
},
.Vector => {
// Although not 100% the same, Zig vectors map quite neatly to SPIR-V vectors (including many integer and float operations
// which work on them), so simply use those.
// Note: SPIR-V vectors only support bools, ints and floats, so pointer vectors need to be supported another way.
// "composite integers" (larger than the largest supported native type) can probably be represented by an array of vectors.
// TODO: The SPIR-V spec mentions that vector sizes may be quite restricted! look into which we can use, and whether OpTypeVector
// is adequate at all for this.
// TODO: Vectors are not yet supported by the self-hosted compiler itself it seems.
return self.fail(.{ .node_offset = 0 }, "TODO: SPIR-V backend: implement type Vector", .{});
},
.Null,
.Undefined,
.EnumLiteral,
.ComptimeFloat,
.ComptimeInt,
.Type,
=> unreachable, // Must be const or comptime.
.BoundFn => unreachable, // this type will be deleted from the language.
else => |tag| return self.fail(.{ .node_offset = 0 }, "TODO: SPIR-V backend: implement type {}s", .{tag}),
}
try self.types.putNoClobber(ty, result_id);
return result_id;
}
pub fn gen(self: *DeclGen) !void {
const decl = self.decl;
const result_id = decl.fn_link.spirv.id;
if (decl.val.castTag(.function)) |func_payload| {
std.debug.assert(decl.ty.zigTypeTag() == .Fn);
const prototype_id = try self.getOrGenType(decl.ty);
try writeInstruction(&self.spv.fn_decls, .OpFunction, &[_]u32{
self.types.get(decl.ty.fnReturnType()).?, // This type should be generated along with the prototype.
result_id,
@bitCast(u32, spec.FunctionControl{}), // TODO: We can set inline here if the type requires it.
prototype_id,
});
const params = decl.ty.fnParamLen();
var i: usize = 0;
try self.args.ensureCapacity(params);
while (i < params) : (i += 1) {
const param_type_id = self.types.get(decl.ty.fnParamType(i)).?;
const arg_result_id = self.spv.allocResultId();
try writeInstruction(&self.spv.fn_decls, .OpFunctionParameter, &[_]u32{ param_type_id, arg_result_id });
self.args.appendAssumeCapacity(arg_result_id);
}
// TODO: This could probably be done in a better way...
const root_block_id = self.spv.allocResultId();
_ = try writeInstruction(&self.spv.fn_decls, .OpLabel, &[_]u32{root_block_id});
try self.genBody(func_payload.data.body);
try writeInstruction(&self.spv.fn_decls, .OpFunctionEnd, &[_]u32{});
} else {
return self.fail(.{ .node_offset = 0 }, "TODO: SPIR-V backend: generate decl type {}", .{decl.ty.zigTypeTag()});
}
}
fn genBody(self: *DeclGen, body: ir.Body) !void {
for (body.instructions) |inst| {
const maybe_result_id = try self.genInst(inst);
if (maybe_result_id) |result_id|
try self.values.putNoClobber(inst, result_id);
}
}
fn genInst(self: *DeclGen, inst: *Inst) !?u32 {
return switch (inst.tag) {
.add, .addwrap => try self.genBinOp(inst.castTag(.add).?),
.sub, .subwrap => try self.genBinOp(inst.castTag(.sub).?),
.mul, .mulwrap => try self.genBinOp(inst.castTag(.mul).?),
.div => try self.genBinOp(inst.castTag(.div).?),
.bit_and => try self.genBinOp(inst.castTag(.bit_and).?),
.bit_or => try self.genBinOp(inst.castTag(.bit_or).?),
.xor => try self.genBinOp(inst.castTag(.xor).?),
.cmp_eq => try self.genBinOp(inst.castTag(.cmp_eq).?),
.cmp_neq => try self.genBinOp(inst.castTag(.cmp_neq).?),
.cmp_gt => try self.genBinOp(inst.castTag(.cmp_gt).?),
.cmp_gte => try self.genBinOp(inst.castTag(.cmp_gte).?),
.cmp_lt => try self.genBinOp(inst.castTag(.cmp_lt).?),
.cmp_lte => try self.genBinOp(inst.castTag(.cmp_lte).?),
.bool_and => try self.genBinOp(inst.castTag(.bool_and).?),
.bool_or => try self.genBinOp(inst.castTag(.bool_or).?),
.not => try self.genUnOp(inst.castTag(.not).?),
.arg => self.genArg(),
// TODO: Breakpoints won't be supported in SPIR-V, but the compiler seems to insert them
// throughout the IR.
.breakpoint => null,
.dbg_stmt => null,
.ret => self.genRet(inst.castTag(.ret).?),
.retvoid => self.genRetVoid(),
.unreach => self.genUnreach(),
else => self.fail(.{ .node_offset = 0 }, "TODO: SPIR-V backend: implement inst {}", .{inst.tag}),
};
}
fn genBinOp(self: *DeclGen, inst: *Inst.BinOp) !u32 {
// TODO: Will lhs and rhs have the same type?
const lhs_id = try self.resolve(inst.lhs);
const rhs_id = try self.resolve(inst.rhs);
const result_id = self.spv.allocResultId();
const result_type_id = try self.getOrGenType(inst.base.ty);
// TODO: Is the result the same as the argument types?
// This is supposed to be the case for SPIR-V.
std.debug.assert(inst.rhs.ty.eql(inst.lhs.ty));
std.debug.assert(inst.base.ty.tag() == .bool or inst.base.ty.eql(inst.lhs.ty));
// Binary operations are generally applicable to both scalar and vector operations in SPIR-V, but int and float
// versions of operations require different opcodes.
// For operations which produce bools, the information of inst.base.ty is not useful, so just pick either operand
// instead.
const info = try self.arithmeticTypeInfo(inst.lhs.ty);
if (info.class == .composite_integer)
return self.fail(.{ .node_offset = 0 }, "TODO: SPIR-V backend: binary operations for composite integers", .{});
const is_bool = info.class == .bool;
const is_float = info.class == .float;
const is_signed = info.signedness == .signed;
// **Note**: All these operations must be valid for vectors of floats, integers and bools as well!
// For floating points, we generally want ordered operations (which return false if either operand is nan).
const opcode = switch (inst.base.tag) {
// The regular integer operations are all defined for wrapping. Since theyre only relevant for integers,
// we can just switch on both cases here.
.add, .addwrap => if (is_float) Opcode.OpFAdd else Opcode.OpIAdd,
.sub, .subwrap => if (is_float) Opcode.OpFSub else Opcode.OpISub,
.mul, .mulwrap => if (is_float) Opcode.OpFMul else Opcode.OpIMul,
// TODO: Trap if divisor is 0?
// TODO: Figure out of OpSDiv for unsigned/OpUDiv for signed does anything useful.
// => Those are probably for divTrunc and divFloor, though the compiler does not yet generate those.
// => TODO: Figure out how those work on the SPIR-V side.
// => TODO: Test these.
.div => if (is_float) Opcode.OpFDiv else if (is_signed) Opcode.OpSDiv else Opcode.OpUDiv,
// Only integer versions for these.
.bit_and => Opcode.OpBitwiseAnd,
.bit_or => Opcode.OpBitwiseOr,
.xor => Opcode.OpBitwiseXor,
// Int/bool/float -> bool operations.
.cmp_eq => if (is_float) Opcode.OpFOrdEqual else if (is_bool) Opcode.OpLogicalEqual else Opcode.OpIEqual,
.cmp_neq => if (is_float) Opcode.OpFOrdNotEqual else if (is_bool) Opcode.OpLogicalNotEqual else Opcode.OpINotEqual,
// Int/float -> bool operations.
// TODO: Verify that these OpFOrd type operations produce the right value.
// TODO: Is there a more fundamental difference between OpU and OpS operations here than just the type?
.cmp_gt => if (is_float) Opcode.OpFOrdGreaterThan else if (is_signed) Opcode.OpSGreaterThan else Opcode.OpUGreaterThan,
.cmp_gte => if (is_float) Opcode.OpFOrdGreaterThanEqual else if (is_signed) Opcode.OpSGreaterThanEqual else Opcode.OpUGreaterThanEqual,
.cmp_lt => if (is_float) Opcode.OpFOrdLessThan else if (is_signed) Opcode.OpSLessThan else Opcode.OpULessThan,
.cmp_lte => if (is_float) Opcode.OpFOrdLessThanEqual else if (is_signed) Opcode.OpSLessThanEqual else Opcode.OpULessThanEqual,
// Bool -> bool operations.
.bool_and => Opcode.OpLogicalAnd,
.bool_or => Opcode.OpLogicalOr,
else => unreachable,
};
try writeInstruction(&self.spv.fn_decls, opcode, &[_]u32{ result_type_id, result_id, lhs_id, rhs_id });
// TODO: Trap on overflow? Probably going to be annoying.
// TODO: Look into SPV_KHR_no_integer_wrap_decoration which provides NoSignedWrap/NoUnsignedWrap.
if (info.class != .strange_integer)
return result_id;
return self.fail(.{ .node_offset = 0 }, "TODO: SPIR-V backend: strange integer operation mask", .{});
}
fn genUnOp(self: *DeclGen, inst: *Inst.UnOp) !u32 {
const operand_id = try self.resolve(inst.operand);
const result_id = self.spv.allocResultId();
const result_type_id = try self.getOrGenType(inst.base.ty);
const info = try self.arithmeticTypeInfo(inst.operand.ty);
const opcode = switch (inst.base.tag) {
// Bool -> bool
.not => Opcode.OpLogicalNot,
else => unreachable,
};
try writeInstruction(&self.spv.fn_decls, opcode, &[_]u32{ result_type_id, result_id, operand_id });
return result_id;
}
fn genArg(self: *DeclGen) u32 {
defer self.next_arg_index += 1;
return self.args.items[self.next_arg_index];
}
fn genRet(self: *DeclGen, inst: *Inst.UnOp) !?u32 {
const operand_id = try self.resolve(inst.operand);
// TODO: This instruction needs to be the last in a block. Is that guaranteed?
try writeInstruction(&self.spv.fn_decls, .OpReturnValue, &[_]u32{operand_id});
return null;
}
fn genRetVoid(self: *DeclGen) !?u32 {
// TODO: This instruction needs to be the last in a block. Is that guaranteed?
try writeInstruction(&self.spv.fn_decls, .OpReturn, &[_]u32{});
return null;
}
fn genUnreach(self: *DeclGen) !?u32 {
// TODO: This instruction needs to be the last in a block. Is that guaranteed?
try writeInstruction(&self.spv.fn_decls, .OpUnreachable, &[_]u32{});
return null;
}
}; | src/codegen/spirv.zig |
const Builtin = struct {
name: []const u8,
signature: []const u8,
snippet: []const u8,
documentation: []const u8,
arguments: []const []const u8,
};
pub const builtins = [_]Builtin{
.{
.name = "@addWithOverflow",
.signature = "@addWithOverflow(comptime T: type, a: T, b: T, result: *T) bool",
.snippet = "@addWithOverflow(${1:comptime T: type}, ${2:a: T}, ${3:b: T}, ${4:result: *T})",
.documentation =
\\ Performs `result.* = a + b`. If overflow or underflow occurs, stores the overflowed bits in `result` and returns `true`. If no overflow or underflow occurs, returns `false`.
,
.arguments = &.{
"comptime T: type",
"a: T",
"b: T",
"result: *T",
},
},
.{
.name = "@alignCast",
.signature = "@alignCast(comptime alignment: u29, ptr: anytype) anytype",
.snippet = "@alignCast(${1:comptime alignment: u29}, ${2:ptr: anytype})",
.documentation =
\\ `ptr` can be `*T`, `fn()`, `?*T`, `?fn()`, or `[]T`. It returns the same type as `ptr` except with the alignment adjusted to the new value.
\\A pointer alignment safety check is added to the generated code to make sure the pointer is aligned as promised.
,
.arguments = &.{
"comptime alignment: u29",
"ptr: anytype",
},
},
.{
.name = "@alignOf",
.signature = "@alignOf(comptime T: type) comptime_int",
.snippet = "@alignOf(${1:comptime T: type})",
.documentation =
\\ This function returns the number of bytes that this type should be aligned to for the current target to match the C ABI. When the child type of a pointer has this alignment, the alignment can be omitted from the type.
\\```zig
\\const expect = @import("std").debug.assert;
\\comptime {
\\ assert(*u32 == *align(@alignOf(u32)) u32);
\\}
\\```
\\ The result is a target-specific compile time constant. It is guaranteed to be less than or equal to @sizeOf(T).
,
.arguments = &.{
"comptime T: type",
},
},
.{
.name = "@as",
.signature = "@as(comptime T: type, expression) T",
.snippet = "@as(${1:comptime T: type}, ${2:expression})",
.documentation =
\\ Performs Type Coercion. This cast is allowed when the conversion is unambiguous and safe, and is the preferred way to convert between types, whenever possible.
,
.arguments = &.{
"comptime T: type",
"expression",
},
},
.{
.name = "@asyncCall",
.signature = "@asyncCall(frame_buffer: []align(@alignOf(@Frame(anyAsyncFunction))) u8, result_ptr, function_ptr, args: anytype) anyframe->T",
.snippet = "@asyncCall(${1:frame_buffer: []align(@alignOf(@Frame(anyAsyncFunction))) u8}, ${2:result_ptr}, ${3:function_ptr}, ${4:args: anytype})",
.documentation =
\\ `@asyncCall` performs an `async` call on a function pointer, which may or may not be an async function.
\\ The provided `frame_buffer` must be large enough to fit the entire function frame. This size can be determined with @frameSize. To provide a too-small buffer invokes safety-checked Undefined Behavior.
\\ `result_ptr` is optional (null may be provided). If provided, the function call will write its result directly to the result pointer, which will be available to read after await completes. Any result location provided to `await` will copy the result from `result_ptr`.
\\test.zig
\\```zig
\\const std = @import("std");
\\const expect = std.testing.expect;
\\
\\test "async fn pointer in a struct field" {
\\ var data: i32 = 1;
\\ const Foo = struct {
\\ bar: fn (*i32) callconv(.Async) void,
\\ };
\\ var foo = Foo{ .bar = func };
\\ var bytes: [64]u8 align(@alignOf(@Frame(func))) = undefined;
\\ const f = @asyncCall(&bytes, {}, foo.bar, .{&data});
\\ try expect(data == 2);
\\ resume f;
\\ try expect(data == 4);
\\}
\\
\\fn func(y: *i32) void {
\\ defer y.* += 2;
\\ y.* += 1;
\\ suspend {}
\\}
\\```
\\```zig
\\$ zig test test.zig
\\Test [1/1] test "async fn pointer in a struct field"...
\\All 1 tests passed.
\\
\\```
,
.arguments = &.{
"frame_buffer: []align(@alignOf(@Frame(anyAsyncFunction))) u8",
"result_ptr",
"function_ptr",
"args: anytype",
},
},
.{
.name = "@atomicLoad",
.signature = "@atomicLoad(comptime T: type, ptr: *const T, comptime ordering: builtin.AtomicOrder) T",
.snippet = "@atomicLoad(${1:comptime T: type}, ${2:ptr: *const T}, ${3:comptime ordering: builtin.AtomicOrder})",
.documentation =
\\ This builtin function atomically dereferences a pointer and returns the value.
\\ `T` must be a pointer, a `bool`, a float, an integer or an enum.
,
.arguments = &.{
"comptime T: type",
"ptr: *const T",
"comptime ordering: builtin.AtomicOrder",
},
},
.{
.name = "@atomicRmw",
.signature = "@atomicRmw(comptime T: type, ptr: *T, comptime op: builtin.AtomicRmwOp, operand: T, comptime ordering: builtin.AtomicOrder) T",
.snippet = "@atomicRmw(${1:comptime T: type}, ${2:ptr: *T}, ${3:comptime op: builtin.AtomicRmwOp}, ${4:operand: T}, ${5:comptime ordering: builtin.AtomicOrder})",
.documentation =
\\ This builtin function atomically modifies memory and then returns the previous value.
\\ `T` must be a pointer, a `bool`, a float, an integer or an enum.
\\ Supported operations:
,
.arguments = &.{
"comptime T: type",
"ptr: *T",
"comptime op: builtin.AtomicRmwOp",
"operand: T",
"comptime ordering: builtin.AtomicOrder",
},
},
.{
.name = "@atomicStore",
.signature = "@atomicStore(comptime T: type, ptr: *T, value: T, comptime ordering: builtin.AtomicOrder) void",
.snippet = "@atomicStore(${1:comptime T: type}, ${2:ptr: *T}, ${3:value: T}, ${4:comptime ordering: builtin.AtomicOrder})",
.documentation =
\\ This builtin function atomically stores a value.
\\ `T` must be a pointer, a `bool`, a float, an integer or an enum.
,
.arguments = &.{
"comptime T: type",
"ptr: *T",
"value: T",
"comptime ordering: builtin.AtomicOrder",
},
},
.{
.name = "@bitCast",
.signature = "@bitCast(comptime DestType: type, value: anytype) DestType",
.snippet = "@bitCast(${1:comptime DestType: type}, ${2:value: anytype})",
.documentation =
\\ Converts a value of one type to another type.
\\ Asserts that `@sizeOf(@TypeOf(value)) == @sizeOf(DestType)`.
\\ Asserts that `@typeInfo(DestType) != .Pointer`. Use `@ptrCast` or `@intToPtr` if you need this.
\\ Can be used for these things for example:
,
.arguments = &.{
"comptime DestType: type",
"value: anytype",
},
},
.{
.name = "@bitOffsetOf",
.signature = "@bitOffsetOf(comptime T: type, comptime field_name: []const u8) comptime_int",
.snippet = "@bitOffsetOf(${1:comptime T: type}, ${2:comptime field_name: []const u8})",
.documentation =
\\ Returns the bit offset of a field relative to its containing struct.
\\ For non packed structs, this will always be divisible by `8`. For packed structs, non-byte-aligned fields will share a byte offset, but they will have different bit offsets.
,
.arguments = &.{
"comptime T: type",
"comptime field_name: []const u8",
},
},
.{
.name = "@boolToInt",
.signature = "@boolToInt(value: bool) u1",
.snippet = "@boolToInt(${1:value: bool})",
.documentation =
\\ Converts `true` to `u1(1)` and `false` to `u1(0)`.
\\ If the value is known at compile-time, the return type is `comptime_int` instead of `u1`.
,
.arguments = &.{
"value: bool",
},
},
.{
.name = "@bitSizeOf",
.signature = "@bitSizeOf(comptime T: type) comptime_int",
.snippet = "@bitSizeOf(${1:comptime T: type})",
.documentation =
\\ This function returns the number of bits it takes to store `T` in memory if the type were a field in a packed struct/union. The result is a target-specific compile time constant.
\\ This function measures the size at runtime. For types that are disallowed at runtime, such as `comptime_int` and `type`, the result is `0`.
,
.arguments = &.{
"comptime T: type",
},
},
.{
.name = "@breakpoint",
.signature = "@breakpoint()",
.snippet = "@breakpoint()",
.documentation =
\\ This function inserts a platform-specific debug trap instruction which causes debuggers to break there.
\\ This function is only valid within function scope.
,
.arguments = &.{},
},
.{
.name = "@mulAdd",
.signature = "@mulAdd(comptime T: type, a: T, b: T, c: T) T",
.snippet = "@mulAdd(${1:comptime T: type}, ${2:a: T}, ${3:b: T}, ${4:c: T})",
.documentation =
\\ Fused multiply add, similar to `(a * b) + c`, except only rounds once, and is thus more accurate.
\\ Supports Floats and Vectors of floats.
,
.arguments = &.{
"comptime T: type",
"a: T",
"b: T",
"c: T",
},
},
.{
.name = "@byteSwap",
.signature = "@byteSwap(comptime T: type, operand: T) T",
.snippet = "@byteSwap(${1:comptime T: type}, ${2:operand: T})",
.documentation =
\\`T` must be an integer type with bit count evenly divisible by 8.
\\`operand` may be an integer or vector.
\\ Swaps the byte order of the integer. This converts a big endian integer to a little endian integer, and converts a little endian integer to a big endian integer.
\\ Note that for the purposes of memory layout with respect to endianness, the integer type should be related to the number of bytes reported by @sizeOf bytes. This is demonstrated with `u24`. `@sizeOf(u24) == 4`, which means that a `u24` stored in memory takes 4 bytes, and those 4 bytes are what are swapped on a little vs big endian system. On the other hand, if `T` is specified to be `u24`, then only 3 bytes are reversed.
,
.arguments = &.{
"comptime T: type",
"operand: T",
},
},
.{
.name = "@bitReverse",
.signature = "@bitReverse(comptime T: type, integer: T) T",
.snippet = "@bitReverse(${1:comptime T: type}, ${2:integer: T})",
.documentation =
\\`T` accepts any integer type.
\\ Reverses the bitpattern of an integer value, including the sign bit if applicable.
\\ For example 0b10110110 (`u8 = 182`, `i8 = -74`) becomes 0b01101101 (`u8 = 109`, `i8 = 109`).
,
.arguments = &.{
"comptime T: type",
"integer: T",
},
},
.{
.name = "@offsetOf",
.signature = "@offsetOf(comptime T: type, comptime field_name: []const u8) comptime_int",
.snippet = "@offsetOf(${1:comptime T: type}, ${2:comptime field_name: []const u8})",
.documentation =
\\ Returns the byte offset of a field relative to its containing struct.
,
.arguments = &.{
"comptime T: type",
"comptime field_name: []const u8",
},
},
.{
.name = "@call",
.signature = "@call(options: std.builtin.CallOptions, function: anytype, args: anytype) anytype",
.snippet = "@call(${1:options: std.builtin.CallOptions}, ${2:function: anytype}, ${3:args: anytype})",
.documentation =
\\ Calls a function, in the same way that invoking an expression with parentheses does:
\\call.zig
\\```zig
\\const expect = @import("std").testing.expect;
\\
\\test "noinline function call" {
\\ try expect(@call(.{}, add, .{3, 9}) == 12);
\\}
\\
\\fn add(a: i32, b: i32) i32 {
\\ return a + b;
\\}
\\```
\\```zig
\\$ zig test call.zig
\\Test [1/1] test "noinline function call"...
\\All 1 tests passed.
\\
\\```
\\ `@call` allows more flexibility than normal function call syntax does. The `CallOptions` struct is reproduced here:
\\```zig
\\pub const CallOptions = struct {
\\ modifier: Modifier = .auto,
\\ stack: ?[]align(std.Target.stack_align) u8 = null,
\\
\\ pub const Modifier = enum {
\\ /// Equivalent to function call syntax.
\\ auto,
\\
\\ /// Equivalent to async keyword used with function call syntax.
\\ async_kw,
\\
\\ /// Prevents tail call optimization. This guarantees that the return
\\ /// address will point to the callsite, as opposed to the callsite's
\\ /// callsite. If the call is otherwise required to be tail-called
\\ /// or inlined, a compile error is emitted instead.
\\ never_tail,
\\
\\ /// Guarantees that the call will not be inlined. If the call is
\\ /// otherwise required to be inlined, a compile error is emitted instead.
\\ never_inline,
\\
\\ /// Asserts that the function call will not suspend. This allows a
\\ /// non-async function to call an async function.
\\ no_async,
\\
\\ /// Guarantees that the call will be generated with tail call optimization.
\\ /// If this is not possible, a compile error is emitted instead.
\\ always_tail,
\\
\\ /// Guarantees that the call will inlined at the callsite.
\\ /// If this is not possible, a compile error is emitted instead.
\\ always_inline,
\\
\\ /// Evaluates the call at compile-time. If the call cannot be completed at
\\ /// compile-time, a compile error is emitted instead.
\\ compile_time,
\\ };
\\};
\\```
,
.arguments = &.{
"options: std.builtin.CallOptions",
"function: anytype",
"args: anytype",
},
},
.{
.name = "@cDefine",
.signature = "@cDefine(comptime name: []u8, value)",
.snippet = "@cDefine(${1:comptime name: []u8}, ${2:value})",
.documentation =
\\ This function can only occur inside `@cImport`.
\\ This appends `#define $name $value` to the `@cImport` temporary buffer.
\\ To define without a value, like this:
\\```zig
\\#define _GNU_SOURCE
\\```
\\ Use the void value, like this:
\\```zig
\\@cDefine("_GNU_SOURCE", {})
\\```
,
.arguments = &.{
"comptime name: []u8",
"value",
},
},
.{
.name = "@cImport",
.signature = "@cImport(expression) type",
.snippet = "@cImport(${1:expression})",
.documentation =
\\ This function parses C code and imports the functions, types, variables, and compatible macro definitions into a new empty struct type, and then returns that type.
\\ `expression` is interpreted at compile time. The builtin functions `@cInclude`, `@cDefine`, and `@cUndef` work within this expression, appending to a temporary buffer which is then parsed as C code.
\\ Usually you should only have one `@cImport` in your entire application, because it saves the compiler from invoking clang multiple times, and prevents inline functions from being duplicated.
\\ Reasons for having multiple `@cImport` expressions would be:
,
.arguments = &.{
"expression",
},
},
.{
.name = "@cInclude",
.signature = "@cInclude(comptime path: []u8)",
.snippet = "@cInclude(${1:comptime path: []u8})",
.documentation =
\\ This function can only occur inside `@cImport`.
\\ This appends `#include <$path>\n` to the `c_import` temporary buffer.
,
.arguments = &.{
"comptime path: []u8",
},
},
.{
.name = "@clz",
.signature = "@clz(comptime T: type, operand: T)",
.snippet = "@clz(${1:comptime T: type}, ${2:operand: T})",
.documentation =
\\`T` must be an integer type.
\\`operand` may be an integer or vector.
\\ This function counts the number of most-significant (leading in a big-Endian sense) zeroes in an integer.
\\ If `operand` is a comptime-known integer, the return type is `comptime_int`. Otherwise, the return type is an unsigned integer or vector of unsigned integers with the minimum number of bits that can represent the bit count of the integer type.
\\ If `operand` is zero, `@clz` returns the bit width of integer type `T`.
,
.arguments = &.{
"comptime T: type",
"operand: T",
},
},
.{
.name = "@cmpxchgStrong",
.signature = "@cmpxchgStrong(comptime T: type, ptr: *T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) ?T",
.snippet = "@cmpxchgStrong(${1:comptime T: type}, ${2:ptr: *T}, ${3:expected_value: T}, ${4:new_value: T}, ${5:success_order: AtomicOrder}, ${6:fail_order: AtomicOrder})",
.documentation =
\\ This function performs a strong atomic compare exchange operation. It's the equivalent of this code, except atomic:
\\```zig
\\fn cmpxchgStrongButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_value: T) ?T {
\\ const old_value = ptr.*;
\\ if (old_value == expected_value) {
\\ ptr.* = new_value;
\\ return null;
\\ } else {
\\ return old_value;
\\ }
\\}
\\```
\\ If you are using cmpxchg in a loop, @cmpxchgWeak is the better choice, because it can be implemented more efficiently in machine instructions.
\\ `T` must be a pointer, a `bool`, a float, an integer or an enum.
\\`@typeInfo(@TypeOf(ptr)).Pointer.alignment` must be `>= @sizeOf(T).`
,
.arguments = &.{
"comptime T: type",
"ptr: *T",
"expected_value: T",
"new_value: T",
"success_order: AtomicOrder",
"fail_order: AtomicOrder",
},
},
.{
.name = "@cmpxchgWeak",
.signature = "@cmpxchgWeak(comptime T: type, ptr: *T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) ?T",
.snippet = "@cmpxchgWeak(${1:comptime T: type}, ${2:ptr: *T}, ${3:expected_value: T}, ${4:new_value: T}, ${5:success_order: AtomicOrder}, ${6:fail_order: AtomicOrder})",
.documentation =
\\ This function performs a weak atomic compare exchange operation. It's the equivalent of this code, except atomic:
\\```zig
\\fn cmpxchgWeakButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_value: T) ?T {
\\ const old_value = ptr.*;
\\ if (old_value == expected_value and usuallyTrueButSometimesFalse()) {
\\ ptr.* = new_value;
\\ return null;
\\ } else {
\\ return old_value;
\\ }
\\}
\\```
\\ If you are using cmpxchg in a loop, the sporadic failure will be no problem, and `cmpxchgWeak` is the better choice, because it can be implemented more efficiently in machine instructions. However if you need a stronger guarantee, use @cmpxchgStrong.
\\ `T` must be a pointer, a `bool`, a float, an integer or an enum.
\\`@typeInfo(@TypeOf(ptr)).Pointer.alignment` must be `>= @sizeOf(T).`
,
.arguments = &.{
"comptime T: type",
"ptr: *T",
"expected_value: T",
"new_value: T",
"success_order: AtomicOrder",
"fail_order: AtomicOrder",
},
},
.{
.name = "@compileError",
.signature = "@compileError(comptime msg: []u8)",
.snippet = "@compileError(${1:comptime msg: []u8})",
.documentation =
\\ This function, when semantically analyzed, causes a compile error with the message `msg`.
\\ There are several ways that code avoids being semantically checked, such as using `if` or `switch` with compile time constants, and `comptime` functions.
,
.arguments = &.{
"comptime msg: []u8",
},
},
.{
.name = "@compileLog",
.signature = "@compileLog(args: ...)",
.snippet = "@compileLog(${1:args: ...})",
.documentation =
\\ This function prints the arguments passed to it at compile-time.
\\ To prevent accidentally leaving compile log statements in a codebase, a compilation error is added to the build, pointing to the compile log statement. This error prevents code from being generated, but does not otherwise interfere with analysis.
\\ This function can be used to do "printf debugging" on compile-time executing code.
\\test.zig
\\```zig
\\const print = @import("std").debug.print;
\\
\\const num1 = blk: {
\\ var val1: i32 = 99;
\\ @compileLog("comptime val1 = ", val1);
\\ val1 = val1 + 1;
\\ break :blk val1;
\\};
\\
\\test "main" {
\\ @compileLog("comptime in main");
\\
\\ print("Runtime in main, num1 = {}.\n", .{num1});
\\}
\\```
\\```zig
\\$ zig test test.zig
\\| *"comptime in main"
\\| *"comptime val1 = ", 99
\\./docgen_tmp/test.zig:11:5: error: found compile log statement
\\ @compileLog("comptime in main");
\\ ^
\\./docgen_tmp/test.zig:1:35: note: referenced here
\\const print = @import("std").debug.print;
\\ ^
\\./docgen_tmp/test.zig:13:5: note: referenced here
\\ print("Runtime in main, num1 = {}.\n", .{num1});
\\ ^
\\./docgen_tmp/test.zig:5:5: error: found compile log statement
\\ @compileLog("comptime val1 = ", val1);
\\ ^
\\./docgen_tmp/test.zig:13:46: note: referenced here
\\ print("Runtime in main, num1 = {}.\n", .{num1});
\\ ^
\\
\\```
\\ will ouput:
\\ If all `@compileLog` calls are removed or not encountered by analysis, the program compiles successfully and the generated executable prints:
\\test.zig
\\```zig
\\const print = @import("std").debug.print;
\\
\\const num1 = blk: {
\\ var val1: i32 = 99;
\\ val1 = val1 + 1;
\\ break :blk val1;
\\};
\\
\\test "main" {
\\ print("Runtime in main, num1 = {}.\n", .{num1});
\\}
\\```
\\```zig
\\$ zig test test.zig
\\Test [1/1] test "main"... Runtime in main, num1 = 100.
\\
\\All 1 tests passed.
\\
\\```
,
.arguments = &.{
"args: ...",
},
},
.{
.name = "@ctz",
.signature = "@ctz(comptime T: type, operand: T)",
.snippet = "@ctz(${1:comptime T: type}, ${2:operand: T})",
.documentation =
\\`T` must be an integer type.
\\`operand` may be an integer or vector.
\\ This function counts the number of least-significant (trailing in a big-Endian sense) zeroes in an integer.
\\ If `operand` is a comptime-known integer, the return type is `comptime_int`. Otherwise, the return type is an unsigned integer or vector of unsigned integers with the minimum number of bits that can represent the bit count of the integer type.
\\ If `operand` is zero, `@ctz` returns the bit width of integer type `T`.
,
.arguments = &.{
"comptime T: type",
"operand: T",
},
},
.{
.name = "@cUndef",
.signature = "@cUndef(comptime name: []u8)",
.snippet = "@cUndef(${1:comptime name: []u8})",
.documentation =
\\ This function can only occur inside `@cImport`.
\\ This appends `#undef $name` to the `@cImport` temporary buffer.
,
.arguments = &.{
"comptime name: []u8",
},
},
.{
.name = "@divExact",
.signature = "@divExact(numerator: T, denominator: T) T",
.snippet = "@divExact(${1:numerator: T}, ${2:denominator: T})",
.documentation =
\\ Exact division. Caller guarantees `denominator != 0` and `@divTrunc(numerator, denominator) * denominator == numerator`.
,
.arguments = &.{
"numerator: T",
"denominator: T",
},
},
.{
.name = "@divFloor",
.signature = "@divFloor(numerator: T, denominator: T) T",
.snippet = "@divFloor(${1:numerator: T}, ${2:denominator: T})",
.documentation =
\\ Floored division. Rounds toward negative infinity. For unsigned integers it is the same as `numerator / denominator`. Caller guarantees `denominator != 0` and `!(@typeInfo(T) == .Int and T.is_signed and numerator == std.math.minInt(T) and denominator == -1)`.
,
.arguments = &.{
"numerator: T",
"denominator: T",
},
},
.{
.name = "@divTrunc",
.signature = "@divTrunc(numerator: T, denominator: T) T",
.snippet = "@divTrunc(${1:numerator: T}, ${2:denominator: T})",
.documentation =
\\ Truncated division. Rounds toward zero. For unsigned integers it is the same as `numerator / denominator`. Caller guarantees `denominator != 0` and `!(@typeInfo(T) == .Int and T.is_signed and numerator == std.math.minInt(T) and denominator == -1)`.
,
.arguments = &.{
"numerator: T",
"denominator: T",
},
},
.{
.name = "@embedFile",
.signature = "@embedFile(comptime path: []const u8) *const [N:0]u8",
.snippet = "@embedFile(${1:comptime path: []const u8})",
.documentation =
\\ This function returns a compile time constant pointer to null-terminated, fixed-size array with length equal to the byte count of the file given by `path`. The contents of the array are the contents of the file. This is equivalent to a string literal with the file contents.
\\ `path` is absolute or relative to the current file, just like `@import`.
,
.arguments = &.{
"comptime path: []const u8",
},
},
.{
.name = "@enumToInt",
.signature = "@enumToInt(enum_or_tagged_union: anytype) anytype",
.snippet = "@enumToInt(${1:enum_or_tagged_union: anytype})",
.documentation =
\\ Converts an enumeration value into its integer tag type. When a tagged union is passed, the tag value is used as the enumeration value.
\\ If there is only one possible enum value, the resut is a `comptime_int` known at comptime.
,
.arguments = &.{
"enum_or_tagged_union: anytype",
},
},
.{
.name = "@errorName",
.signature = "@errorName(err: anyerror) [:0]const u8",
.snippet = "@errorName(${1:err: anyerror})",
.documentation =
\\ This function returns the string representation of an error. The string representation of `error.OutOfMem` is `"OutOfMem"`.
\\ If there are no calls to `@errorName` in an entire application, or all calls have a compile-time known value for `err`, then no error name table will be generated.
,
.arguments = &.{
"err: anyerror",
},
},
.{
.name = "@errorReturnTrace",
.signature = "@errorReturnTrace() ?*builtin.StackTrace",
.snippet = "@errorReturnTrace()",
.documentation =
\\ If the binary is built with error return tracing, and this function is invoked in a function that calls a function with an error or error union return type, returns a stack trace object. Otherwise returns null.
,
.arguments = &.{},
},
.{
.name = "@errorToInt",
.signature = "@errorToInt(err: anytype) std.meta.Int(.unsigned, @sizeOf(anyerror) * 8)",
.snippet = "@errorToInt(${1:err: anytype})",
.documentation =
\\ Supports the following types:
,
.arguments = &.{
"err: anytype",
},
},
.{
.name = "@errSetCast",
.signature = "@errSetCast(comptime T: DestType, value: anytype) DestType",
.snippet = "@errSetCast(${1:comptime T: DestType}, ${2:value: anytype})",
.documentation =
\\ Converts an error value from one error set to another error set. Attempting to convert an error which is not in the destination error set results in safety-protected Undefined Behavior.
,
.arguments = &.{
"comptime T: DestType",
"value: anytype",
},
},
.{
.name = "@export",
.signature = "@export(declaration, comptime options: std.builtin.ExportOptions) void",
.snippet = "@export(${1:declaration}, ${2:comptime options: std.builtin.ExportOptions})",
.documentation =
\\ Creates a symbol in the output object file.
\\ `declaration` must be one of two things:
,
.arguments = &.{
"declaration",
"comptime options: std.builtin.ExportOptions",
},
},
.{
.name = "@extern",
.signature = "@extern(T: type, comptime options: std.builtin.ExternOptions) *T",
.snippet = "@extern(${1:T: type}, ${2:comptime options: std.builtin.ExternOptions})",
.documentation =
\\ Creates a reference to an external symbol in the output object file.
,
.arguments = &.{
"T: type",
"comptime options: std.builtin.ExternOptions",
},
},
.{
.name = "@fence",
.signature = "@fence(order: AtomicOrder)",
.snippet = "@fence(${1:order: AtomicOrder})",
.documentation =
\\ The `fence` function is used to introduce happens-before edges between operations.
\\ `AtomicOrder` can be found with `@import("std").builtin.AtomicOrder`.
,
.arguments = &.{
"order: AtomicOrder",
},
},
.{
.name = "@field",
.signature = "@field(lhs: anytype, comptime field_name: []const u8) (field)",
.snippet = "@field(${1:lhs: anytype}, ${2:comptime field_name: []const u8})",
.documentation =
\\Performs field access by a compile-time string. Works on both fields and declarations.
\\test.zig
\\```zig
\\const std = @import("std");
\\
\\const Point = struct {
\\ x: u32,
\\ y: u32,
\\
\\ pub var z: u32 = 1;
\\};
\\
\\test "field access by string" {
\\ const expect = std.testing.expect;
\\ var p = Point{ .x = 0, .y = 0 };
\\
\\ @field(p, "x") = 4;
\\ @field(p, "y") = @field(p, "x") + 1;
\\
\\ try expect(@field(p, "x") == 4);
\\ try expect(@field(p, "y") == 5);
\\}
\\
\\test "decl access by string" {
\\ const expect = std.testing.expect;
\\
\\ try expect(@field(Point, "z") == 1);
\\
\\ @field(Point, "z") = 2;
\\ try expect(@field(Point, "z") == 2);
\\}
\\```
\\```zig
\\$ zig test test.zig
\\Test [1/2] test "field access by string"...
\\Test [2/2] test "decl access by string"...
\\All 2 tests passed.
\\
\\```
,
.arguments = &.{
"lhs: anytype",
"comptime field_name: []const u8",
},
},
.{
.name = "@fieldParentPtr",
.signature = "@fieldParentPtr(comptime ParentType: type, comptime field_name: []const u8, field_ptr: *T) *ParentType",
.snippet = "@fieldParentPtr(${1:comptime ParentType: type}, ${2:comptime field_name: []const u8}, ${3:field_ptr: *T})",
.documentation =
\\ Given a pointer to a field, returns the base pointer of a struct.
,
.arguments = &.{
"comptime ParentType: type",
"comptime field_name: []const u8",
"field_ptr: *T",
},
},
.{
.name = "@floatCast",
.signature = "@floatCast(comptime DestType: type, value: anytype) DestType",
.snippet = "@floatCast(${1:comptime DestType: type}, ${2:value: anytype})",
.documentation =
\\ Convert from one float type to another. This cast is safe, but may cause the numeric value to lose precision.
,
.arguments = &.{
"comptime DestType: type",
"value: anytype",
},
},
.{
.name = "@floatToInt",
.signature = "@floatToInt(comptime DestType: type, float: anytype) DestType",
.snippet = "@floatToInt(${1:comptime DestType: type}, ${2:float: anytype})",
.documentation =
\\ Converts the integer part of a floating point number to the destination type.
\\ If the integer part of the floating point number cannot fit in the destination type, it invokes safety-checked Undefined Behavior.
,
.arguments = &.{
"comptime DestType: type",
"float: anytype",
},
},
.{
.name = "@frame",
.signature = "@frame() *@Frame(func)",
.snippet = "@frame()",
.documentation =
\\ This function returns a pointer to the frame for a given function. This type can be coerced to `anyframe->T` and to `anyframe`, where `T` is the return type of the function in scope.
\\ This function does not mark a suspension point, but it does cause the function in scope to become an async function.
,
.arguments = &.{},
},
.{
.name = "@Frame",
.signature = "@Frame(func: anytype) type",
.snippet = "@Frame(${1:func: anytype})",
.documentation =
\\ This function returns the frame type of a function. This works for Async Functions as well as any function without a specific calling convention.
\\ This type is suitable to be used as the return type of async which allows one to, for example, heap-allocate an async function frame:
\\test.zig
\\```zig
\\const std = @import("std");
\\
\\test "heap allocated frame" {
\\ const frame = try std.heap.page_allocator.create(@Frame(func));
\\ frame.* = async func();
\\}
\\
\\fn func() void {
\\ suspend {}
\\}
\\```
\\```zig
\\$ zig test test.zig
\\Test [1/1] test "heap allocated frame"...
\\All 1 tests passed.
\\
\\```
,
.arguments = &.{
"func: anytype",
},
},
.{
.name = "@frameAddress",
.signature = "@frameAddress() usize",
.snippet = "@frameAddress()",
.documentation =
\\ This function returns the base pointer of the current stack frame.
\\ The implications of this are target specific and not consistent across all platforms. The frame address may not be available in release mode due to aggressive optimizations.
\\ This function is only valid within function scope.
,
.arguments = &.{},
},
.{
.name = "@frameSize",
.signature = "@frameSize() usize",
.snippet = "@frameSize()",
.documentation =
\\ This is the same as `@sizeOf(@Frame(func))`, where `func` may be runtime-known.
\\ This function is typically used in conjunction with @asyncCall.
,
.arguments = &.{},
},
.{
.name = "@hasDecl",
.signature = "@hasDecl(comptime Container: type, comptime name: []const u8) bool",
.snippet = "@hasDecl(${1:comptime Container: type}, ${2:comptime name: []const u8})",
.documentation =
\\ Returns whether or not a struct, enum, or union has a declaration matching `name`.
\\test.zig
\\```zig
\\const std = @import("std");
\\const expect = std.testing.expect;
\\
\\const Foo = struct {
\\ nope: i32,
\\
\\ pub var blah = "xxx";
\\ const hi = 1;
\\};
\\
\\test "@hasDecl" {
\\ try expect(@hasDecl(Foo, "blah"));
\\
\\ // Even though `hi` is private, @hasDecl returns true because this test is
\\ // in the same file scope as Foo. It would return false if Foo was declared
\\ // in a different file.
\\ try expect(@hasDecl(Foo, "hi"));
\\
\\ // @hasDecl is for declarations; not fields.
\\ try expect(!@hasDecl(Foo, "nope"));
\\ try expect(!@hasDecl(Foo, "nope1234"));
\\}
\\```
\\```zig
\\$ zig test test.zig
\\Test [1/1] test "@hasDecl"...
\\All 1 tests passed.
\\
\\```
,
.arguments = &.{
"comptime Container: type",
"comptime name: []const u8",
},
},
.{
.name = "@hasField",
.signature = "@hasField(comptime Container: type, comptime name: []const u8) bool",
.snippet = "@hasField(${1:comptime Container: type}, ${2:comptime name: []const u8})",
.documentation =
\\Returns whether the field name of a struct, union, or enum exists.
\\ The result is a compile time constant.
\\ It does not include functions, variables, or constants.
,
.arguments = &.{
"comptime Container: type",
"comptime name: []const u8",
},
},
.{
.name = "@import",
.signature = "@import(comptime path: []u8) type",
.snippet = "@import(${1:comptime path: []u8})",
.documentation =
\\ This function finds a zig file corresponding to `path` and adds it to the build, if it is not already added.
\\ Zig source files are implicitly structs, with a name equal to the file's basename with the extension truncated. `@import` returns the struct type corresponding to the file.
\\ Declarations which have the `pub` keyword may be referenced from a different source file than the one they are declared in.
\\ `path` can be a relative path or it can be the name of a package. If it is a relative path, it is relative to the file that contains the `@import` function call.
\\ The following packages are always available:
,
.arguments = &.{
"comptime path: []u8",
},
},
.{
.name = "@intCast",
.signature = "@intCast(comptime DestType: type, int: anytype) DestType",
.snippet = "@intCast(${1:comptime DestType: type}, ${2:int: anytype})",
.documentation =
\\ Converts an integer to another integer while keeping the same numerical value. Attempting to convert a number which is out of range of the destination type results in safety-protected Undefined Behavior.
\\ If `T` is `comptime_int`, then this is semantically equivalent to Type Coercion.
,
.arguments = &.{
"comptime DestType: type",
"int: anytype",
},
},
.{
.name = "@intToEnum",
.signature = "@intToEnum(comptime DestType: type, int_value: std.meta.Tag(DestType)) DestType",
.snippet = "@intToEnum(${1:comptime DestType: type}, ${2:int_value: std.meta.Tag(DestType)})",
.documentation =
\\ Converts an integer into an enum value.
\\ Attempting to convert an integer which represents no value in the chosen enum type invokes safety-checked Undefined Behavior.
,
.arguments = &.{
"comptime DestType: type",
"int_value: std.meta.Tag(DestType)",
},
},
.{
.name = "@intToError",
.signature = "@intToError(value: std.meta.Int(.unsigned, @sizeOf(anyerror) * 8)) anyerror",
.snippet = "@intToError(${1:value: std.meta.Int(.unsigned, @sizeOf(anyerror) * 8)})",
.documentation =
\\ Converts from the integer representation of an error into The Global Error Set type.
\\ It is generally recommended to avoid this cast, as the integer representation of an error is not stable across source code changes.
\\ Attempting to convert an integer that does not correspond to any error results in safety-protected Undefined Behavior.
,
.arguments = &.{
"value: std.meta.Int(.unsigned, @sizeOf(anyerror) * 8)",
},
},
.{
.name = "@intToFloat",
.signature = "@intToFloat(comptime DestType: type, int: anytype) DestType",
.snippet = "@intToFloat(${1:comptime DestType: type}, ${2:int: anytype})",
.documentation =
\\ Converts an integer to the closest floating point representation. To convert the other way, use @floatToInt. This cast is always safe.
,
.arguments = &.{
"comptime DestType: type",
"int: anytype",
},
},
.{
.name = "@intToPtr",
.signature = "@intToPtr(comptime DestType: type, address: usize) DestType",
.snippet = "@intToPtr(${1:comptime DestType: type}, ${2:address: usize})",
.documentation =
\\ Converts an integer to a pointer. To convert the other way, use @ptrToInt.
\\ If the destination pointer type does not allow address zero and `address` is zero, this invokes safety-checked Undefined Behavior.
,
.arguments = &.{
"comptime DestType: type",
"address: usize",
},
},
.{
.name = "@maximum",
.signature = "@maximum(a: T, b: T) T",
.snippet = "@maximum(${1:a: T}, ${2:b: T})",
.documentation =
\\ Returns the maximum value of `a` and `b`. This builtin accepts integers, floats, and vectors of either. In the latter case, the operation is performed element wise.
\\ NaNs are handled as follows: if one of the operands of a (pairwise) operation is NaN, the other operand is returned. If both operands are NaN, NaN is returned.
,
.arguments = &.{
"a: T",
"b: T",
},
},
.{
.name = "@memcpy",
.signature = "@memcpy(noalias dest: [*]u8, noalias source: [*]const u8, byte_count: usize)",
.snippet = "@memcpy(${1:noalias dest: [*]u8}, ${2:noalias source: [*]const u8}, ${3:byte_count: usize})",
.documentation =
\\ This function copies bytes from one region of memory to another. `dest` and `source` are both pointers and must not overlap.
\\ This function is a low level intrinsic with no safety mechanisms. Most code should not use this function, instead using something like this:
\\```zig
\\for (source[0..byte_count]) |b, i| dest[i] = b;
\\```
\\ The optimizer is intelligent enough to turn the above snippet into a memcpy.
\\There is also a standard library function for this:
\\```zig
\\const mem = @import("std").mem;
\\mem.copy(u8, dest[0..byte_count], source[0..byte_count]);
\\```
,
.arguments = &.{
"noalias dest: [*]u8",
"noalias source: [*]const u8",
"byte_count: usize",
},
},
.{
.name = "@memset",
.signature = "@memset(dest: [*]u8, c: u8, byte_count: usize)",
.snippet = "@memset(${1:dest: [*]u8}, ${2:c: u8}, ${3:byte_count: usize})",
.documentation =
\\ This function sets a region of memory to `c`. `dest` is a pointer.
\\ This function is a low level intrinsic with no safety mechanisms. Most code should not use this function, instead using something like this:
\\```zig
\\for (dest[0..byte_count]) |*b| b.* = c;
\\```
\\ The optimizer is intelligent enough to turn the above snippet into a memset.
\\There is also a standard library function for this:
\\```zig
\\const mem = @import("std").mem;
\\mem.set(u8, dest, c);
\\```
,
.arguments = &.{
"dest: [*]u8",
"c: u8",
"byte_count: usize",
},
},
.{
.name = "@minimum",
.signature = "@minimum(a: T, b: T) T",
.snippet = "@minimum(${1:a: T}, ${2:b: T})",
.documentation =
\\ Returns the minimum value of `a` and `b`. This builtin accepts integers, floats, and vectors of either. In the latter case, the operation is performed element wise.
\\ NaNs are handled as follows: if one of the operands of a (pairwise) operation is NaN, the other operand is returned. If both operands are NaN, NaN is returned.
,
.arguments = &.{
"a: T",
"b: T",
},
},
.{
.name = "@wasmMemorySize",
.signature = "@wasmMemorySize(index: u32) u32",
.snippet = "@wasmMemorySize(${1:index: u32})",
.documentation =
\\ This function returns the size of the Wasm memory identified by `index` as an unsigned value in units of Wasm pages. Note that each Wasm page is 64KB in size.
\\ This function is a low level intrinsic with no safety mechanisms usually useful for allocator designers targeting Wasm. So unless you are writing a new allocator from scratch, you should use something like `@import("std").heap.WasmPageAllocator`.
,
.arguments = &.{
"index: u32",
},
},
.{
.name = "@wasmMemoryGrow",
.signature = "@wasmMemoryGrow(index: u32, delta: u32) i32",
.snippet = "@wasmMemoryGrow(${1:index: u32}, ${2:delta: u32})",
.documentation =
\\ This function increases the size of the Wasm memory identified by `index` by `delta` in units of unsigned number of Wasm pages. Note that each Wasm page is 64KB in size. On success, returns previous memory size; on failure, if the allocation fails, returns -1.
\\ This function is a low level intrinsic with no safety mechanisms usually useful for allocator designers targeting Wasm. So unless you are writing a new allocator from scratch, you should use something like `@import("std").heap.WasmPageAllocator`.
\\test.zig
\\```zig
\\const std = @import("std");
\\const native_arch = @import("builtin").target.cpu.arch;
\\const expect = std.testing.expect;
\\
\\test "@wasmMemoryGrow" {
\\ if (native_arch != .wasm32) return error.SkipZigTest;
\\
\\ var prev = @wasmMemorySize(0);
\\ try expect(prev == @wasmMemoryGrow(0, 1));
\\ try expect(prev + 1 == @wasmMemorySize(0));
\\}
\\```
\\```zig
\\$ zig test test.zig
\\Test [1/1] test "@wasmMemoryGrow"...
\\Test [2/1] test "@wasmMemoryGrow"... SKIP
\\0 passed; 1 skipped; 0 failed.
\\
\\```
,
.arguments = &.{
"index: u32",
"delta: u32",
},
},
.{
.name = "@mod",
.signature = "@mod(numerator: T, denominator: T) T",
.snippet = "@mod(${1:numerator: T}, ${2:denominator: T})",
.documentation =
\\ Modulus division. For unsigned integers this is the same as `numerator % denominator`. Caller guarantees `denominator > 0`.
,
.arguments = &.{
"numerator: T",
"denominator: T",
},
},
.{
.name = "@mulWithOverflow",
.signature = "@mulWithOverflow(comptime T: type, a: T, b: T, result: *T) bool",
.snippet = "@mulWithOverflow(${1:comptime T: type}, ${2:a: T}, ${3:b: T}, ${4:result: *T})",
.documentation =
\\ Performs `result.* = a * b`. If overflow or underflow occurs, stores the overflowed bits in `result` and returns `true`. If no overflow or underflow occurs, returns `false`.
,
.arguments = &.{
"comptime T: type",
"a: T",
"b: T",
"result: *T",
},
},
.{
.name = "@panic",
.signature = "@panic(message: []const u8) noreturn",
.snippet = "@panic(${1:message: []const u8})",
.documentation =
\\ Invokes the panic handler function. By default the panic handler function calls the public `panic` function exposed in the root source file, or if there is not one specified, the `std.builtin.default_panic` function from `std/builtin.zig`.
\\Generally it is better to use `@import("std").debug.panic`. However, `@panic` can be useful for 2 scenarios:
,
.arguments = &.{
"message: []const u8",
},
},
.{
.name = "@popCount",
.signature = "@popCount(comptime T: type, operand: T)",
.snippet = "@popCount(${1:comptime T: type}, ${2:operand: T})",
.documentation =
\\`T` must be an integer type.
\\`operand` may be an integer or vector.
\\Counts the number of bits set in an integer.
\\ If `operand` is a comptime-known integer, the return type is `comptime_int`. Otherwise, the return type is an unsigned integer or vector of unsigned integers with the minimum number of bits that can represent the bit count of the integer type.
,
.arguments = &.{
"comptime T: type",
"operand: T",
},
},
.{
.name = "@ptrCast",
.signature = "@ptrCast(comptime DestType: type, value: anytype) DestType",
.snippet = "@ptrCast(${1:comptime DestType: type}, ${2:value: anytype})",
.documentation =
\\ Converts a pointer of one type to a pointer of another type.
\\ Optional Pointers are allowed. Casting an optional pointer which is null to a non-optional pointer invokes safety-checked Undefined Behavior.
,
.arguments = &.{
"comptime DestType: type",
"value: anytype",
},
},
.{
.name = "@ptrToInt",
.signature = "@ptrToInt(value: anytype) usize",
.snippet = "@ptrToInt(${1:value: anytype})",
.documentation =
\\ Converts `value` to a `usize` which is the address of the pointer. `value` can be one of these types:
,
.arguments = &.{
"value: anytype",
},
},
.{
.name = "@rem",
.signature = "@rem(numerator: T, denominator: T) T",
.snippet = "@rem(${1:numerator: T}, ${2:denominator: T})",
.documentation =
\\ Remainder division. For unsigned integers this is the same as `numerator % denominator`. Caller guarantees `denominator > 0`.
,
.arguments = &.{
"numerator: T",
"denominator: T",
},
},
.{
.name = "@returnAddress",
.signature = "@returnAddress() usize",
.snippet = "@returnAddress()",
.documentation =
\\ This function returns the address of the next machine code instruction that will be executed when the current function returns.
\\ The implications of this are target specific and not consistent across all platforms.
\\ This function is only valid within function scope. If the function gets inlined into a calling function, the returned address will apply to the calling function.
,
.arguments = &.{},
},
.{
.name = "@select",
.signature = "@select(comptime T: type, pred: std.meta.Vector(len, bool), a: std.meta.Vector(len, T), b: std.meta.Vector(len, T)) std.meta.Vector(len, T)",
.snippet = "@select(${1:comptime T: type}, ${2:pred: std.meta.Vector(len, bool)}, ${3:a: std.meta.Vector(len, T)}, ${4:b: std.meta.Vector(len, T)})",
.documentation =
\\ Selects values element-wise from `a` or `b` based on `pred`. If `pred[i]` is `true`, the corresponding element in the result will be `a[i]` and otherwise `b[i]`.
,
.arguments = &.{
"comptime T: type",
"pred: std.meta.Vector(len, bool)",
"a: std.meta.Vector(len, T)",
"b: std.meta.Vector(len, T)",
},
},
.{
.name = "@setAlignStack",
.signature = "@setAlignStack(comptime alignment: u29)",
.snippet = "@setAlignStack(${1:comptime alignment: u29})",
.documentation =
\\ Ensures that a function will have a stack alignment of at least `alignment` bytes.
,
.arguments = &.{
"comptime alignment: u29",
},
},
.{
.name = "@setCold",
.signature = "@setCold(is_cold: bool)",
.snippet = "@setCold(${1:is_cold: bool})",
.documentation =
\\ Tells the optimizer that a function is rarely called.
,
.arguments = &.{
"is_cold: bool",
},
},
.{
.name = "@setEvalBranchQuota",
.signature = "@setEvalBranchQuota(new_quota: u32)",
.snippet = "@setEvalBranchQuota(${1:new_quota: u32})",
.documentation =
\\ Changes the maximum number of backwards branches that compile-time code execution can use before giving up and making a compile error.
\\ If the `new_quota` is smaller than the default quota (`1000`) or a previously explicitly set quota, it is ignored.
\\ Example:
\\test.zig
\\```zig
\\test "foo" {
\\ comptime {
\\ var i = 0;
\\ while (i < 1001) : (i += 1) {}
\\ }
\\}
\\```
\\```zig
\\$ zig test test.zig
\\./docgen_tmp/test.zig:4:9: error: evaluation exceeded 1000 backwards branches
\\ while (i < 1001) : (i += 1) {}
\\ ^
\\./docgen_tmp/test.zig:1:12: note: referenced here
\\test "foo" {
\\ ^
\\
\\```
\\Now we use `@setEvalBranchQuota`:
\\test.zig
\\```zig
\\test "foo" {
\\ comptime {
\\ @setEvalBranchQuota(1001);
\\ var i = 0;
\\ while (i < 1001) : (i += 1) {}
\\ }
\\}
\\```
\\```zig
\\$ zig test test.zig
\\Test [1/1] test "foo"...
\\All 1 tests passed.
\\
\\```
,
.arguments = &.{
"new_quota: u32",
},
},
.{
.name = "@setFloatMode",
.signature = "@setFloatMode(mode: @import(\"std\").builtin.FloatMode)",
.snippet = "@setFloatMode(${1:mode: @import(\"std\").builtin.FloatMode})",
.documentation =
\\ Sets the floating point mode of the current scope. Possible values are:
\\```zig
\\pub const FloatMode = enum {
\\ Strict,
\\ Optimized,
\\};
\\```
,
.arguments = &.{
"mode: @import(\"std\").builtin.FloatMode",
},
},
.{
.name = "@setRuntimeSafety",
.signature = "@setRuntimeSafety(safety_on: bool) void",
.snippet = "@setRuntimeSafety(${1:safety_on: bool})",
.documentation =
\\ Sets whether runtime safety checks are enabled for the scope that contains the function call.
\\test.zig
\\```zig
\\test "@setRuntimeSafety" {
\\ // The builtin applies to the scope that it is called in. So here, integer overflow
\\ // will not be caught in ReleaseFast and ReleaseSmall modes:
\\ // var x: u8 = 255;
\\ // x += 1; // undefined behavior in ReleaseFast/ReleaseSmall modes.
\\ {
\\ // However this block has safety enabled, so safety checks happen here,
\\ // even in ReleaseFast and ReleaseSmall modes.
\\ @setRuntimeSafety(true);
\\ var x: u8 = 255;
\\ x += 1;
\\
\\ {
\\ // The value can be overridden at any scope. So here integer overflow
\\ // would not be caught in any build mode.
\\ @setRuntimeSafety(false);
\\ // var x: u8 = 255;
\\ // x += 1; // undefined behavior in all build modes.
\\ }
\\ }
\\}
\\```
\\```zig
\\$ zig test test.zig -OReleaseFast
\\Test [1/1] test "@setRuntimeSafety"... thread 3010 panic: integer overflow
\\error: the following test command crashed:
\\docgen_tmp/zig-cache/o/76db9f6227d3b8aabdf7427a0c0fbb3e/test /home/vsts/work/1/s/build/release/bin/zig
\\
\\```
\\Note: it is planned to replace `@setRuntimeSafety` with `@optimizeFor`
,
.arguments = &.{
"safety_on: bool",
},
},
.{
.name = "@shlExact",
.signature = "@shlExact(value: T, shift_amt: Log2T) T",
.snippet = "@shlExact(${1:value: T}, ${2:shift_amt: Log2T})",
.documentation =
\\ Performs the left shift operation (`<<`). Caller guarantees that the shift will not shift any 1 bits out.
\\ The type of `shift_amt` is an unsigned integer with `log2(T.bit_count)` bits. This is because `shift_amt >= T.bit_count` is undefined behavior.
,
.arguments = &.{
"value: T",
"shift_amt: Log2T",
},
},
.{
.name = "@shlWithOverflow",
.signature = "@shlWithOverflow(comptime T: type, a: T, shift_amt: Log2T, result: *T) bool",
.snippet = "@shlWithOverflow(${1:comptime T: type}, ${2:a: T}, ${3:shift_amt: Log2T}, ${4:result: *T})",
.documentation =
\\ Performs `result.* = a << b`. If overflow or underflow occurs, stores the overflowed bits in `result` and returns `true`. If no overflow or underflow occurs, returns `false`.
\\ The type of `shift_amt` is an unsigned integer with `log2(T.bit_count)` bits. This is because `shift_amt >= T.bit_count` is undefined behavior.
,
.arguments = &.{
"comptime T: type",
"a: T",
"shift_amt: Log2T",
"result: *T",
},
},
.{
.name = "@shrExact",
.signature = "@shrExact(value: T, shift_amt: Log2T) T",
.snippet = "@shrExact(${1:value: T}, ${2:shift_amt: Log2T})",
.documentation =
\\ Performs the right shift operation (`>>`). Caller guarantees that the shift will not shift any 1 bits out.
\\ The type of `shift_amt` is an unsigned integer with `log2(T.bit_count)` bits. This is because `shift_amt >= T.bit_count` is undefined behavior.
,
.arguments = &.{
"value: T",
"shift_amt: Log2T",
},
},
.{
.name = "@shuffle",
.signature = "@shuffle(comptime E: type, a: std.meta.Vector(a_len, E), b: std.meta.Vector(b_len, E), comptime mask: std.meta.Vector(mask_len, i32)) std.meta.Vector(mask_len, E)",
.snippet = "@shuffle(${1:comptime E: type}, ${2:a: std.meta.Vector(a_len, E)}, ${3:b: std.meta.Vector(b_len, E)}, ${4:comptime mask: std.meta.Vector(mask_len, i32)})",
.documentation =
\\ Constructs a new vector by selecting elements from `a` and `b` based on `mask`.
\\ Each element in `mask` selects an element from either `a` or `b`. Positive numbers select from `a` starting at 0. Negative values select from `b`, starting at `-1` and going down. It is recommended to use the `~` operator from indexes from `b` so that both indexes can start from `0` (i.e. `~@as(i32, 0)` is `-1`).
\\ For each element of `mask`, if it or the selected value from `a` or `b` is `undefined`, then the resulting element is `undefined`.
\\ `a_len` and `b_len` may differ in length. Out-of-bounds element indexes in `mask` result in compile errors.
\\ If `a` or `b` is `undefined`, it is equivalent to a vector of all `undefined` with the same length as the other vector. If both vectors are `undefined`, `@shuffle` returns a vector with all elements `undefined`.
\\ `E` must be an integer, float, pointer, or `bool`. The mask may be any vector length, and its length determines the result length.
,
.arguments = &.{
"comptime E: type",
"a: std.meta.Vector(a_len, E)",
"b: std.meta.Vector(b_len, E)",
"comptime mask: std.meta.Vector(mask_len, i32)",
},
},
.{
.name = "@sizeOf",
.signature = "@sizeOf(comptime T: type) comptime_int",
.snippet = "@sizeOf(${1:comptime T: type})",
.documentation =
\\ This function returns the number of bytes it takes to store `T` in memory. The result is a target-specific compile time constant.
\\ This size may contain padding bytes. If there were two consecutive T in memory, this would be the offset in bytes between element at index 0 and the element at index 1. For integer, consider whether you want to use `@sizeOf(T)` or `@typeInfo(T).Int.bits`.
\\ This function measures the size at runtime. For types that are disallowed at runtime, such as `comptime_int` and `type`, the result is `0`.
,
.arguments = &.{
"comptime T: type",
},
},
.{
.name = "@splat",
.signature = "@splat(comptime len: u32, scalar: anytype) std.meta.Vector(len, @TypeOf(scalar))",
.snippet = "@splat(${1:comptime len: u32}, ${2:scalar: anytype})",
.documentation =
\\ Produces a vector of length `len` where each element is the value `scalar`:
\\test.zig
\\```zig
\\const std = @import("std");
\\const expect = std.testing.expect;
\\
\\test "vector @splat" {
\\ const scalar: u32 = 5;
\\ const result = @splat(4, scalar);
\\ comptime try expect(@TypeOf(result) == std.meta.Vector(4, u32));
\\ try expect(std.mem.eql(u32, &@as([4]u32, result), &[_]u32{ 5, 5, 5, 5 }));
\\}
\\```
\\```zig
\\$ zig test test.zig
\\Test [1/1] test "vector @splat"...
\\All 1 tests passed.
\\
\\```
\\ `scalar` must be an integer, bool, float, or pointer.
,
.arguments = &.{
"comptime len: u32",
"scalar: anytype",
},
},
.{
.name = "@reduce",
.signature = "@reduce(comptime op: std.builtin.ReduceOp, value: anytype) std.meta.Child(value)",
.snippet = "@reduce(${1:comptime op: std.builtin.ReduceOp}, ${2:value: anytype})",
.documentation =
\\ Transforms a vector into a scalar value by performing a sequential horizontal reduction of its elements using the specified operator `op`.
\\ Not every operator is available for every vector element type:
,
.arguments = &.{
"comptime op: std.builtin.ReduceOp",
"value: anytype",
},
},
.{
.name = "@src",
.signature = "@src() std.builtin.SourceLocation",
.snippet = "@src()",
.documentation =
\\ Returns a `SourceLocation` struct representing the function's name and location in the source code. This must be called in a function.
\\test.zig
\\```zig
\\const std = @import("std");
\\const expect = std.testing.expect;
\\
\\test "@src" {
\\ try doTheTest();
\\}
\\
\\fn doTheTest() !void {
\\ const src = @src();
\\
\\ try expect(src.line == 9);
\\ try expect(src.column == 17);
\\ try expect(std.mem.endsWith(u8, src.fn_name, "doTheTest"));
\\ try expect(std.mem.endsWith(u8, src.file, "test.zig"));
\\}
\\```
\\```zig
\\$ zig test test.zig
\\Test [1/1] test "@src"...
\\All 1 tests passed.
\\
\\```
,
.arguments = &.{},
},
.{
.name = "@sqrt",
.signature = "@sqrt(value: anytype) @TypeOf(value)",
.snippet = "@sqrt(${1:value: anytype})",
.documentation =
\\ Performs the square root of a floating point number. Uses a dedicated hardware instruction when available.
\\ Supports Floats and Vectors of floats, with the caveat that some float operations are not yet implemented for all float types.
,
.arguments = &.{
"value: anytype",
},
},
.{
.name = "@sin",
.signature = "@sin(value: anytype) @TypeOf(value)",
.snippet = "@sin(${1:value: anytype})",
.documentation =
\\ Sine trigometric function on a floating point number. Uses a dedicated hardware instruction when available.
\\ Supports Floats and Vectors of floats, with the caveat that some float operations are not yet implemented for all float types.
,
.arguments = &.{
"value: anytype",
},
},
.{
.name = "@cos",
.signature = "@cos(value: anytype) @TypeOf(value)",
.snippet = "@cos(${1:value: anytype})",
.documentation =
\\ Cosine trigometric function on a floating point number. Uses a dedicated hardware instruction when available.
\\ Supports Floats and Vectors of floats, with the caveat that some float operations are not yet implemented for all float types.
,
.arguments = &.{
"value: anytype",
},
},
.{
.name = "@exp",
.signature = "@exp(value: anytype) @TypeOf(value)",
.snippet = "@exp(${1:value: anytype})",
.documentation =
\\ Base-e exponential function on a floating point number. Uses a dedicated hardware instruction when available.
\\ Supports Floats and Vectors of floats, with the caveat that some float operations are not yet implemented for all float types.
,
.arguments = &.{
"value: anytype",
},
},
.{
.name = "@exp2",
.signature = "@exp2(value: anytype) @TypeOf(value)",
.snippet = "@exp2(${1:value: anytype})",
.documentation =
\\ Base-2 exponential function on a floating point number. Uses a dedicated hardware instruction when available.
\\ Supports Floats and Vectors of floats, with the caveat that some float operations are not yet implemented for all float types.
,
.arguments = &.{
"value: anytype",
},
},
.{
.name = "@log",
.signature = "@log(value: anytype) @TypeOf(value)",
.snippet = "@log(${1:value: anytype})",
.documentation =
\\ Returns the natural logarithm of a floating point number. Uses a dedicated hardware instruction when available.
\\ Supports Floats and Vectors of floats, with the caveat that some float operations are not yet implemented for all float types.
,
.arguments = &.{
"value: anytype",
},
},
.{
.name = "@log2",
.signature = "@log2(value: anytype) @TypeOf(value)",
.snippet = "@log2(${1:value: anytype})",
.documentation =
\\ Returns the logarithm to the base 2 of a floating point number. Uses a dedicated hardware instruction when available.
\\ Supports Floats and Vectors of floats, with the caveat that some float operations are not yet implemented for all float types.
,
.arguments = &.{
"value: anytype",
},
},
.{
.name = "@log10",
.signature = "@log10(value: anytype) @TypeOf(value)",
.snippet = "@log10(${1:value: anytype})",
.documentation =
\\ Returns the logarithm to the base 10 of a floating point number. Uses a dedicated hardware instruction when available.
\\ Supports Floats and Vectors of floats, with the caveat that some float operations are not yet implemented for all float types.
,
.arguments = &.{
"value: anytype",
},
},
.{
.name = "@fabs",
.signature = "@fabs(value: anytype) @TypeOf(value)",
.snippet = "@fabs(${1:value: anytype})",
.documentation =
\\ Returns the absolute value of a floating point number. Uses a dedicated hardware instruction when available.
\\ Supports Floats and Vectors of floats, with the caveat that some float operations are not yet implemented for all float types.
,
.arguments = &.{
"value: anytype",
},
},
.{
.name = "@floor",
.signature = "@floor(value: anytype) @TypeOf(value)",
.snippet = "@floor(${1:value: anytype})",
.documentation =
\\ Returns the largest integral value not greater than the given floating point number. Uses a dedicated hardware instruction when available.
\\ Supports Floats and Vectors of floats, with the caveat that some float operations are not yet implemented for all float types.
,
.arguments = &.{
"value: anytype",
},
},
.{
.name = "@ceil",
.signature = "@ceil(value: anytype) @TypeOf(value)",
.snippet = "@ceil(${1:value: anytype})",
.documentation =
\\ Returns the largest integral value not less than the given floating point number. Uses a dedicated hardware instruction when available.
\\ Supports Floats and Vectors of floats, with the caveat that some float operations are not yet implemented for all float types.
,
.arguments = &.{
"value: anytype",
},
},
.{
.name = "@trunc",
.signature = "@trunc(value: anytype) @TypeOf(value)",
.snippet = "@trunc(${1:value: anytype})",
.documentation =
\\ Rounds the given floating point number to an integer, towards zero. Uses a dedicated hardware instruction when available.
\\ Supports Floats and Vectors of floats, with the caveat that some float operations are not yet implemented for all float types.
,
.arguments = &.{
"value: anytype",
},
},
.{
.name = "@round",
.signature = "@round(value: anytype) @TypeOf(value)",
.snippet = "@round(${1:value: anytype})",
.documentation =
\\ Rounds the given floating point number to an integer, away from zero. Uses a dedicated hardware instruction when available.
\\ Supports Floats and Vectors of floats, with the caveat that some float operations are not yet implemented for all float types.
,
.arguments = &.{
"value: anytype",
},
},
.{
.name = "@subWithOverflow",
.signature = "@subWithOverflow(comptime T: type, a: T, b: T, result: *T) bool",
.snippet = "@subWithOverflow(${1:comptime T: type}, ${2:a: T}, ${3:b: T}, ${4:result: *T})",
.documentation =
\\ Performs `result.* = a - b`. If overflow or underflow occurs, stores the overflowed bits in `result` and returns `true`. If no overflow or underflow occurs, returns `false`.
,
.arguments = &.{
"comptime T: type",
"a: T",
"b: T",
"result: *T",
},
},
.{
.name = "@tagName",
.signature = "@tagName(value: anytype) [:0]const u8",
.snippet = "@tagName(${1:value: anytype})",
.documentation =
\\ Converts an enum value or union value to a string literal representing the name.
\\If the enum is non-exhaustive and the tag value does not map to a name, it invokes safety-checked Undefined Behavior.
,
.arguments = &.{
"value: anytype",
},
},
.{
.name = "@This",
.signature = "@This() type",
.snippet = "@This()",
.documentation =
\\ Returns the innermost struct, enum, or union that this function call is inside. This can be useful for an anonymous struct that needs to refer to itself:
\\test.zig
\\```zig
\\const std = @import("std");
\\const expect = std.testing.expect;
\\
\\test "@This()" {
\\ var items = [_]i32{ 1, 2, 3, 4 };
\\ const list = List(i32){ .items = items[0..] };
\\ try expect(list.length() == 4);
\\}
\\
\\fn List(comptime T: type) type {
\\ return struct {
\\ const Self = @This();
\\
\\ items: []T,
\\
\\ fn length(self: Self) usize {
\\ return self.items.len;
\\ }
\\ };
\\}
\\```
\\```zig
\\$ zig test test.zig
\\Test [1/1] test "@This()"...
\\All 1 tests passed.
\\
\\```
\\ When `@This()` is used at file scope, it returns a reference to the struct that corresponds to the current file.
,
.arguments = &.{},
},
.{
.name = "@truncate",
.signature = "@truncate(comptime T: type, integer: anytype) T",
.snippet = "@truncate(${1:comptime T: type}, ${2:integer: anytype})",
.documentation =
\\ This function truncates bits from an integer type, resulting in a smaller or same-sized integer type.
\\ The following produces safety-checked Undefined Behavior:
\\test.zig
\\```zig
\\test "integer cast panic" {
\\ var a: u16 = 0xabcd;
\\ var b: u8 = @intCast(u8, a);
\\ _ = b;
\\}
\\```
\\```zig
\\$ zig test test.zig
\\Test [1/1] test "integer cast panic"... thread 3055 panic: integer cast truncated bits
\\/home/vsts/work/1/s/docgen_tmp/test.zig:3:17: 0x206675 in test "integer cast panic" (test)
\\ var b: u8 = @intCast(u8, a);
\\ ^
\\/home/vsts/work/1/s/build/release/lib/zig/std/special/test_runner.zig:76:28: 0x22cc72 in std.special.main (test)
\\ } else test_fn.func();
\\ ^
\\/home/vsts/work/1/s/build/release/lib/zig/std/start.zig:498:22: 0x22526c in std.start.callMain (test)
\\ root.main();
\\ ^
\\/home/vsts/work/1/s/build/release/lib/zig/std/start.zig:450:12: 0x20927e in std.start.callMainWithArgs (test)
\\ return @call(.{ .modifier = .always_inline }, callMain, .{});
\\ ^
\\/home/vsts/work/1/s/build/release/lib/zig/std/start.zig:369:17: 0x2082a6 in std.start.posixCallMainAndExit (test)
\\ std.os.exit(@call(.{ .modifier = .always_inline }, callMainWithArgs, .{ argc, argv, envp }));
\\ ^
\\/home/vsts/work/1/s/build/release/lib/zig/std/start.zig:282:5: 0x2080b2 in std.start._start (test)
\\ @call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
\\ ^
\\error: the following test command crashed:
\\docgen_tmp/zig-cache/o/25831564b3eeae3183c16227e0d27e30/test /home/vsts/work/1/s/build/release/bin/zig
\\
\\```
\\ However this is well defined and working code:
\\truncate.zig
\\```zig
\\const std = @import("std");
\\const expect = std.testing.expect;
\\
\\test "integer truncation" {
\\ var a: u16 = 0xabcd;
\\ var b: u8 = @truncate(u8, a);
\\ try expect(b == 0xcd);
\\}
\\```
\\```zig
\\$ zig test truncate.zig
\\Test [1/1] test "integer truncation"...
\\All 1 tests passed.
\\
\\```
\\ This function always truncates the significant bits of the integer, regardless of endianness on the target platform.
,
.arguments = &.{
"comptime T: type",
"integer: anytype",
},
},
.{
.name = "@Type",
.signature = "@Type(comptime info: std.builtin.TypeInfo) type",
.snippet = "@Type(${1:comptime info: std.builtin.TypeInfo})",
.documentation =
\\ This function is the inverse of @typeInfo. It reifies type information into a `type`.
\\ It is available for the following types:
,
.arguments = &.{
"comptime info: std.builtin.TypeInfo",
},
},
.{
.name = "@typeInfo",
.signature = "@typeInfo(comptime T: type) std.builtin.TypeInfo",
.snippet = "@typeInfo(${1:comptime T: type})",
.documentation =
\\ Provides type reflection.
\\ For structs, unions, enums, and error sets, the fields are guaranteed to be in the same order as declared. For declarations, the order is unspecified.
,
.arguments = &.{
"comptime T: type",
},
},
.{
.name = "@typeName",
.signature = "@typeName(T: type) *const [N:0]u8",
.snippet = "@typeName(${1:T: type})",
.documentation =
\\ This function returns the string representation of a type, as an array. It is equivalent to a string literal of the type name.
,
.arguments = &.{
"T: type",
},
},
.{
.name = "@TypeOf",
.signature = "@TypeOf(...) type",
.snippet = "@TypeOf(${1:...})",
.documentation =
\\ `@TypeOf` is a special builtin function that takes any (nonzero) number of expressions as parameters and returns the type of the result, using Peer Type Resolution.
\\ The expressions are evaluated, however they are guaranteed to have no runtime side-effects:
\\test.zig
\\```zig
\\const std = @import("std");
\\const expect = std.testing.expect;
\\
\\test "no runtime side effects" {
\\ var data: i32 = 0;
\\ const T = @TypeOf(foo(i32, &data));
\\ comptime try expect(T == i32);
\\ try expect(data == 0);
\\}
\\
\\fn foo(comptime T: type, ptr: *T) T {
\\ ptr.* += 1;
\\ return ptr.*;
\\}
\\```
\\```zig
\\$ zig test test.zig
\\Test [1/1] test "no runtime side effects"...
\\All 1 tests passed.
\\
\\```
,
.arguments = &.{
"...",
},
},
.{
.name = "@unionInit",
.signature = "@unionInit(comptime Union: type, comptime active_field_name: []const u8, init_expr) Union",
.snippet = "@unionInit(${1:comptime Union: type}, ${2:comptime active_field_name: []const u8}, ${3:init_expr})",
.documentation =
\\ This is the same thing as union initialization syntax, except that the field name is a comptime-known value rather than an identifier token.
\\ `@unionInit` forwards its result location to `init_expr`.
,
.arguments = &.{
"comptime Union: type",
"comptime active_field_name: []const u8",
"init_expr",
},
},
}; | src/data/master.zig |
const std = @import("../std.zig");
const math = std.math;
const expect = std.testing.expect;
const maxInt = std.math.maxInt;
/// Returns the absolute value of x.
///
/// Special Cases:
/// - fabs(+-inf) = +inf
/// - fabs(nan) = nan
pub fn fabs(x: var) @typeOf(x) {
const T = @typeOf(x);
return switch (T) {
f16 => fabs16(x),
f32 => fabs32(x),
f64 => fabs64(x),
f128 => fabs128(x),
else => @compileError("fabs not implemented for " ++ @typeName(T)),
};
}
fn fabs16(x: f16) f16 {
var u = @bitCast(u16, x);
u &= 0x7FFF;
return @bitCast(f16, u);
}
fn fabs32(x: f32) f32 {
var u = @bitCast(u32, x);
u &= 0x7FFFFFFF;
return @bitCast(f32, u);
}
fn fabs64(x: f64) f64 {
var u = @bitCast(u64, x);
u &= maxInt(u64) >> 1;
return @bitCast(f64, u);
}
fn fabs128(x: f128) f128 {
var u = @bitCast(u128, x);
u &= maxInt(u128) >> 1;
return @bitCast(f128, u);
}
test "math.fabs" {
expect(fabs(@as(f16, 1.0)) == fabs16(1.0));
expect(fabs(@as(f32, 1.0)) == fabs32(1.0));
expect(fabs(@as(f64, 1.0)) == fabs64(1.0));
expect(fabs(@as(f128, 1.0)) == fabs128(1.0));
}
test "math.fabs16" {
expect(fabs16(1.0) == 1.0);
expect(fabs16(-1.0) == 1.0);
}
test "math.fabs32" {
expect(fabs32(1.0) == 1.0);
expect(fabs32(-1.0) == 1.0);
}
test "math.fabs64" {
expect(fabs64(1.0) == 1.0);
expect(fabs64(-1.0) == 1.0);
}
test "math.fabs128" {
expect(fabs128(1.0) == 1.0);
expect(fabs128(-1.0) == 1.0);
}
test "math.fabs16.special" {
expect(math.isPositiveInf(fabs(math.inf(f16))));
expect(math.isPositiveInf(fabs(-math.inf(f16))));
expect(math.isNan(fabs(math.nan(f16))));
}
test "math.fabs32.special" {
expect(math.isPositiveInf(fabs(math.inf(f32))));
expect(math.isPositiveInf(fabs(-math.inf(f32))));
expect(math.isNan(fabs(math.nan(f32))));
}
test "math.fabs64.special" {
expect(math.isPositiveInf(fabs(math.inf(f64))));
expect(math.isPositiveInf(fabs(-math.inf(f64))));
expect(math.isNan(fabs(math.nan(f64))));
}
test "math.fabs128.special" {
expect(math.isPositiveInf(fabs(math.inf(f128))));
expect(math.isPositiveInf(fabs(-math.inf(f128))));
expect(math.isNan(fabs(math.nan(f128))));
} | lib/std/math/fabs.zig |
const std = @import("../std.zig");
const assert = std.debug.assert;
const math = std.math;
const mem = std.mem;
/// GHASH is a universal hash function that features multiplication
/// by a fixed parameter within a Galois field.
///
/// It is not a general purpose hash function - The key must be secret, unpredictable and never reused.
///
/// GHASH is typically used to compute the authentication tag in the AES-GCM construction.
pub const Ghash = struct {
pub const block_size: usize = 16;
pub const mac_length = 16;
pub const minimum_key_length = 16;
y0: u64 = 0,
y1: u64 = 0,
h0: u64,
h1: u64,
h2: u64,
h0r: u64,
h1r: u64,
h2r: u64,
hh0: u64 = undefined,
hh1: u64 = undefined,
hh2: u64 = undefined,
hh0r: u64 = undefined,
hh1r: u64 = undefined,
hh2r: u64 = undefined,
leftover: usize = 0,
buf: [block_size]u8 align(16) = undefined,
pub fn init(key: *const [minimum_key_length]u8) Ghash {
const h1 = mem.readIntBig(u64, key[0..8]);
const h0 = mem.readIntBig(u64, key[8..16]);
const h1r = @bitReverse(u64, h1);
const h0r = @bitReverse(u64, h0);
const h2 = h0 ^ h1;
const h2r = h0r ^ h1r;
if (std.builtin.mode == .ReleaseSmall) {
return Ghash{
.h0 = h0,
.h1 = h1,
.h2 = h2,
.h0r = h0r,
.h1r = h1r,
.h2r = h2r,
};
} else {
// Precompute H^2
var hh = Ghash{
.h0 = h0,
.h1 = h1,
.h2 = h2,
.h0r = h0r,
.h1r = h1r,
.h2r = h2r,
};
hh.update(key);
const hh1 = hh.y1;
const hh0 = hh.y0;
const hh1r = @bitReverse(u64, hh1);
const hh0r = @bitReverse(u64, hh0);
const hh2 = hh0 ^ hh1;
const hh2r = hh0r ^ hh1r;
return Ghash{
.h0 = h0,
.h1 = h1,
.h2 = h2,
.h0r = h0r,
.h1r = h1r,
.h2r = h2r,
.hh0 = hh0,
.hh1 = hh1,
.hh2 = hh2,
.hh0r = hh0r,
.hh1r = hh1r,
.hh2r = hh2r,
};
}
}
inline fn clmul_pclmul(x: u64, y: u64) u64 {
const Vector = std.meta.Vector;
const product = asm (
\\ vpclmulqdq $0x00, %[x], %[y], %[out]
: [out] "=x" (-> Vector(2, u64))
: [x] "x" (@bitCast(Vector(2, u64), @as(u128, x))),
[y] "x" (@bitCast(Vector(2, u64), @as(u128, y)))
);
return product[0];
}
fn clmul_soft(x: u64, y: u64) u64 {
const x0 = x & 0x1111111111111111;
const x1 = x & 0x2222222222222222;
const x2 = x & 0x4444444444444444;
const x3 = x & 0x8888888888888888;
const y0 = y & 0x1111111111111111;
const y1 = y & 0x2222222222222222;
const y2 = y & 0x4444444444444444;
const y3 = y & 0x8888888888888888;
var z0 = (x0 *% y0) ^ (x1 *% y3) ^ (x2 *% y2) ^ (x3 *% y1);
var z1 = (x0 *% y1) ^ (x1 *% y0) ^ (x2 *% y3) ^ (x3 *% y2);
var z2 = (x0 *% y2) ^ (x1 *% y1) ^ (x2 *% y0) ^ (x3 *% y3);
var z3 = (x0 *% y3) ^ (x1 *% y2) ^ (x2 *% y1) ^ (x3 *% y0);
z0 &= 0x1111111111111111;
z1 &= 0x2222222222222222;
z2 &= 0x4444444444444444;
z3 &= 0x8888888888888888;
return z0 | z1 | z2 | z3;
}
const has_pclmul = comptime std.Target.x86.featureSetHas(std.Target.current.cpu.features, .pclmul);
const has_avx = comptime std.Target.x86.featureSetHas(std.Target.current.cpu.features, .avx);
const clmul = if (std.Target.current.cpu.arch == .x86_64 and has_pclmul and has_avx) clmul_pclmul else clmul_soft;
fn blocks(st: *Ghash, msg: []const u8) void {
assert(msg.len % 16 == 0); // GHASH blocks() expects full blocks
var y1 = st.y1;
var y0 = st.y0;
var i: usize = 0;
// 2-blocks aggregated reduction
if (std.builtin.mode != .ReleaseSmall) {
while (i + 32 <= msg.len) : (i += 32) {
// B0 * H^2 unreduced
y1 ^= mem.readIntBig(u64, msg[i..][0..8]);
y0 ^= mem.readIntBig(u64, msg[i..][8..16]);
const y1r = @bitReverse(u64, y1);
const y0r = @bitReverse(u64, y0);
const y2 = y0 ^ y1;
const y2r = y0r ^ y1r;
var z0 = clmul(y0, st.hh0);
var z1 = clmul(y1, st.hh1);
var z2 = clmul(y2, st.hh2) ^ z0 ^ z1;
var z0h = clmul(y0r, st.hh0r);
var z1h = clmul(y1r, st.hh1r);
var z2h = clmul(y2r, st.hh2r) ^ z0h ^ z1h;
// B1 * H unreduced
const sy1 = mem.readIntBig(u64, msg[i..][16..24]);
const sy0 = mem.readIntBig(u64, msg[i..][24..32]);
const sy1r = @bitReverse(u64, sy1);
const sy0r = @bitReverse(u64, sy0);
const sy2 = sy0 ^ sy1;
const sy2r = sy0r ^ sy1r;
const sz0 = clmul(sy0, st.h0);
const sz1 = clmul(sy1, st.h1);
const sz2 = clmul(sy2, st.h2) ^ sz0 ^ sz1;
const sz0h = clmul(sy0r, st.h0r);
const sz1h = clmul(sy1r, st.h1r);
const sz2h = clmul(sy2r, st.h2r) ^ sz0h ^ sz1h;
// ((B0 * H^2) + B1 * H) (mod M)
z0 ^= sz0;
z1 ^= sz1;
z2 ^= sz2;
z0h ^= sz0h;
z1h ^= sz1h;
z2h ^= sz2h;
z0h = @bitReverse(u64, z0h) >> 1;
z1h = @bitReverse(u64, z1h) >> 1;
z2h = @bitReverse(u64, z2h) >> 1;
var v3 = z1h;
var v2 = z1 ^ z2h;
var v1 = z0h ^ z2;
var v0 = z0;
v3 = (v3 << 1) | (v2 >> 63);
v2 = (v2 << 1) | (v1 >> 63);
v1 = (v1 << 1) | (v0 >> 63);
v0 = (v0 << 1);
v2 ^= v0 ^ (v0 >> 1) ^ (v0 >> 2) ^ (v0 >> 7);
v1 ^= (v0 << 63) ^ (v0 << 62) ^ (v0 << 57);
y1 = v3 ^ v1 ^ (v1 >> 1) ^ (v1 >> 2) ^ (v1 >> 7);
y0 = v2 ^ (v1 << 63) ^ (v1 << 62) ^ (v1 << 57);
}
}
// single block
while (i + 16 <= msg.len) : (i += 16) {
y1 ^= mem.readIntBig(u64, msg[i..][0..8]);
y0 ^= mem.readIntBig(u64, msg[i..][8..16]);
const y1r = @bitReverse(u64, y1);
const y0r = @bitReverse(u64, y0);
const y2 = y0 ^ y1;
const y2r = y0r ^ y1r;
const z0 = clmul(y0, st.h0);
const z1 = clmul(y1, st.h1);
var z2 = clmul(y2, st.h2) ^ z0 ^ z1;
var z0h = clmul(y0r, st.h0r);
var z1h = clmul(y1r, st.h1r);
var z2h = clmul(y2r, st.h2r) ^ z0h ^ z1h;
z0h = @bitReverse(u64, z0h) >> 1;
z1h = @bitReverse(u64, z1h) >> 1;
z2h = @bitReverse(u64, z2h) >> 1;
// shift & reduce
var v3 = z1h;
var v2 = z1 ^ z2h;
var v1 = z0h ^ z2;
var v0 = z0;
v3 = (v3 << 1) | (v2 >> 63);
v2 = (v2 << 1) | (v1 >> 63);
v1 = (v1 << 1) | (v0 >> 63);
v0 = (v0 << 1);
v2 ^= v0 ^ (v0 >> 1) ^ (v0 >> 2) ^ (v0 >> 7);
v1 ^= (v0 << 63) ^ (v0 << 62) ^ (v0 << 57);
y1 = v3 ^ v1 ^ (v1 >> 1) ^ (v1 >> 2) ^ (v1 >> 7);
y0 = v2 ^ (v1 << 63) ^ (v1 << 62) ^ (v1 << 57);
}
st.y1 = y1;
st.y0 = y0;
}
pub fn update(st: *Ghash, m: []const u8) void {
var mb = m;
if (st.leftover > 0) {
const want = math.min(block_size - st.leftover, mb.len);
const mc = mb[0..want];
for (mc) |x, i| {
st.buf[st.leftover + i] = x;
}
mb = mb[want..];
st.leftover += want;
if (st.leftover > block_size) {
return;
}
st.blocks(&st.buf);
st.leftover = 0;
}
if (mb.len >= block_size) {
const want = mb.len & ~(block_size - 1);
st.blocks(mb[0..want]);
mb = mb[want..];
}
if (mb.len > 0) {
for (mb) |x, i| {
st.buf[st.leftover + i] = x;
}
st.leftover += mb.len;
}
}
pub fn final(st: *Ghash, out: *[mac_length]u8) void {
if (st.leftover > 0) {
var i = st.leftover;
while (i < block_size) : (i += 1) {
st.buf[i] = 0;
}
st.blocks(&st.buf);
}
mem.writeIntBig(u64, out[0..8], st.y1);
mem.writeIntBig(u64, out[8..16], st.y0);
mem.secureZero(u8, @ptrCast([*]u8, st)[0..@sizeOf(Ghash)]);
}
pub fn create(out: *[mac_length]u8, msg: []const u8, key: *const [minimum_key_length]u8) void {
var st = Ghash.init(key);
st.update(msg);
st.final(out);
}
};
const htest = @import("test.zig");
test "ghash" {
const key = [_]u8{0x42} ** 16;
const m = [_]u8{0x69} ** 256;
var st = Ghash.init(&key);
st.update(&m);
var out: [16]u8 = undefined;
st.final(&out);
htest.assertEqual("889295fa746e8b174bf4ec80a65dea41", &out);
st = Ghash.init(&key);
st.update(m[0..100]);
st.update(m[100..]);
st.final(&out);
htest.assertEqual("889295fa746e8b174bf4ec80a65dea41", &out);
} | lib/std/crypto/ghash.zig |
const std = @import("std");
const builtin = @import("builtin");
pub const gpu = @import("gpu/build.zig");
const gpu_dawn = @import("gpu-dawn/build.zig");
pub const glfw = @import("glfw/build.zig");
const freetype = @import("freetype/build.zig");
const Pkg = std.build.Pkg;
pub fn build(b: *std.build.Builder) void {
const mode = b.standardReleaseOptions();
const target = b.standardTargetOptions(.{});
const gpu_dawn_options = gpu_dawn.Options{
.from_source = b.option(bool, "dawn-from-source", "Build Dawn from source") orelse false,
};
const options = Options{ .gpu_dawn_options = gpu_dawn_options };
// TODO: re-enable tests
const main_tests = b.addTest("src/main.zig");
main_tests.setBuildMode(mode);
main_tests.setTarget(target);
main_tests.addPackage(pkg);
main_tests.addPackage(gpu.pkg);
main_tests.addPackage(glfw.pkg);
const test_step = b.step("test", "Run library tests");
test_step.dependOn(&main_tests.step);
// TODO(build-system): https://github.com/hexops/mach/issues/229#issuecomment-1100958939
ensureDependencySubmodule(b.allocator, "examples/libs/zmath") catch unreachable;
ensureDependencySubmodule(b.allocator, "examples/libs/zigimg") catch unreachable;
ensureDependencySubmodule(b.allocator, "examples/assets") catch unreachable;
inline for ([_]ExampleDefinition{
.{ .name = "triangle" },
.{ .name = "boids" },
.{ .name = "rotating-cube", .packages = &[_]Pkg{Packages.zmath} },
.{ .name = "two-cubes", .packages = &[_]Pkg{Packages.zmath} },
.{ .name = "instanced-cube", .packages = &[_]Pkg{Packages.zmath} },
.{ .name = "advanced-gen-texture-light", .packages = &[_]Pkg{Packages.zmath} },
.{ .name = "fractal-cube", .packages = &[_]Pkg{Packages.zmath} },
.{ .name = "gkurve", .packages = &[_]Pkg{ Packages.zmath, Packages.zigimg, freetype.pkg } },
.{ .name = "textured-cube", .packages = &[_]Pkg{ Packages.zmath, Packages.zigimg } },
}) |example| {
// FIXME: this is workaround for a problem that some examples (having the std_platform_only=true field) as
// well as zigimg uses IO which is not supported in freestanding environments. So break out of this loop
// as soon as any such examples is found. This does means that any example which works on wasm should be
// placed before those who dont.
if (example.std_platform_only)
if (target.toTarget().cpu.arch == .wasm32)
break;
const example_app = App.init(
b,
.{
.name = "example-" ++ example.name,
.src = "examples/" ++ example.name ++ "/main.zig",
.target = target,
.deps = example.packages,
},
);
example_app.setBuildMode(mode);
inline for (example.packages) |p| {
if (std.mem.eql(u8, p.name, freetype.pkg.name))
freetype.link(example_app.b, example_app.step, .{});
}
example_app.link(options);
example_app.install();
const example_compile_step = b.step("example-" ++ example.name, "Compile '" ++ example.name ++ "' example");
example_compile_step.dependOn(&example_app.getInstallStep().?.step);
const example_run_cmd = example_app.run();
example_run_cmd.step.dependOn(&example_app.getInstallStep().?.step);
const example_run_step = b.step("run-example-" ++ example.name, "Run '" ++ example.name ++ "' example");
example_run_step.dependOn(&example_run_cmd.step);
}
if (target.toTarget().cpu.arch != .wasm32) {
const shaderexp_app = App.init(
b,
.{
.name = "shaderexp",
.src = "shaderexp/main.zig",
.target = target,
},
);
shaderexp_app.setBuildMode(mode);
shaderexp_app.link(options);
shaderexp_app.install();
const shaderexp_compile_step = b.step("shaderexp", "Compile shaderexp");
shaderexp_compile_step.dependOn(&shaderexp_app.getInstallStep().?.step);
const shaderexp_run_cmd = shaderexp_app.run();
shaderexp_run_cmd.step.dependOn(&shaderexp_app.getInstallStep().?.step);
const shaderexp_run_step = b.step("run-shaderexp", "Run shaderexp");
shaderexp_run_step.dependOn(&shaderexp_run_cmd.step);
}
const compile_all = b.step("compile-all", "Compile all examples and applications");
compile_all.dependOn(b.getInstallStep());
}
pub const Options = struct {
glfw_options: glfw.Options = .{},
gpu_dawn_options: gpu_dawn.Options = .{},
};
const ExampleDefinition = struct {
name: []const u8,
packages: []const Pkg = &[_]Pkg{},
std_platform_only: bool = false,
};
const Packages = struct {
// Declared here because submodule may not be cloned at the time build.zig runs.
const zmath = std.build.Pkg{
.name = "zmath",
.path = .{ .path = "examples/libs/zmath/src/zmath.zig" },
};
const zigimg = std.build.Pkg{
.name = "zigimg",
.path = .{ .path = "examples/libs/zigimg/zigimg.zig" },
};
};
const web_install_dir = std.build.InstallDir{ .custom = "www" };
pub const App = struct {
b: *std.build.Builder,
name: []const u8,
step: *std.build.LibExeObjStep,
pub fn init(b: *std.build.Builder, options: struct {
name: []const u8,
src: []const u8,
target: std.zig.CrossTarget,
deps: ?[]const Pkg = null,
}) App {
const mach_deps: []const Pkg = &.{ glfw.pkg, gpu.pkg, pkg };
const deps = if (options.deps) |app_deps|
std.mem.concat(b.allocator, Pkg, &.{ mach_deps, app_deps }) catch unreachable
else
mach_deps;
const app_pkg = std.build.Pkg{
.name = "app",
.path = .{ .path = options.src },
.dependencies = deps,
};
const step = blk: {
if (options.target.toTarget().cpu.arch == .wasm32) {
const lib = b.addSharedLibrary(options.name, thisDir() ++ "/src/wasm.zig", .unversioned);
lib.addPackage(gpu.pkg);
break :blk lib;
} else {
const exe = b.addExecutable(options.name, thisDir() ++ "/src/native.zig");
exe.addPackage(gpu.pkg);
exe.addPackage(glfw.pkg);
break :blk exe;
}
};
step.addPackage(app_pkg);
step.setTarget(options.target);
return .{
.b = b,
.step = step,
.name = options.name,
};
}
pub fn install(app: *const App) void {
app.step.install();
// Install additional files (src/mach.js and template.html)
// in case of wasm
if (app.step.target.toTarget().cpu.arch == .wasm32) {
// Set install directory to '{prefix}/www'
app.getInstallStep().?.dest_dir = web_install_dir;
const install_mach_js = app.b.addInstallFileWithDir(
.{ .path = thisDir() ++ "/src/mach.js" },
web_install_dir,
"mach.js",
);
app.getInstallStep().?.step.dependOn(&install_mach_js.step);
const html_generator = app.b.addExecutable("html-generator", thisDir() ++ "/tools/html-generator.zig");
const run_html_generator = html_generator.run();
run_html_generator.addArgs(&.{ std.mem.concat(
app.b.allocator,
u8,
&.{ app.name, ".html" },
) catch unreachable, app.name });
run_html_generator.cwd = app.b.getInstallPath(web_install_dir, "");
app.getInstallStep().?.step.dependOn(&run_html_generator.step);
}
}
pub fn link(app: *const App, options: Options) void {
const gpu_options = gpu.Options{
.glfw_options = @bitCast(@import("gpu/libs/mach-glfw/build.zig").Options, options.glfw_options),
.gpu_dawn_options = @bitCast(@import("gpu/libs/mach-gpu-dawn/build.zig").Options, options.gpu_dawn_options),
};
if (app.step.target.toTarget().cpu.arch != .wasm32) {
glfw.link(app.b, app.step, options.glfw_options);
gpu.link(app.b, app.step, gpu_options);
}
}
pub fn setBuildMode(app: *const App, mode: std.builtin.Mode) void {
app.step.setBuildMode(mode);
}
pub fn getInstallStep(app: *const App) ?*std.build.InstallArtifactStep {
return app.step.install_step;
}
pub fn run(app: *const App) *std.build.RunStep {
if (app.step.target.toTarget().cpu.arch == .wasm32) {
ensureDependencySubmodule(app.b.allocator, "tools/libs/apple_pie") catch unreachable;
const http_server = app.b.addExecutable("http-server", thisDir() ++ "/tools/http-server.zig");
http_server.addPackage(.{
.name = "apple_pie",
.path = .{ .path = "tools/libs/apple_pie/src/apple_pie.zig" },
});
// NOTE: The launch actually takes place in reverse order. The browser is launched first
// and then the http-server.
// This is because running the server would block the process (a limitation of current
// RunStep). So we assume that (xdg-)open is a launcher and not a blocking process.
const address = std.process.getEnvVarOwned(app.b.allocator, "MACH_ADDRESS") catch "127.0.0.1";
const port = std.process.getEnvVarOwned(app.b.allocator, "MACH_PORT") catch "8000";
const launch = app.b.addSystemCommand(&.{
switch (builtin.os.tag) {
.macos, .windows => "open",
else => "xdg-open", // Assume linux-like
},
app.b.fmt("http://{s}:{s}/{s}.html", .{ address, port, app.name }),
});
launch.step.dependOn(&app.getInstallStep().?.step);
const serve = http_server.run();
serve.addArgs(&.{ app.name, address, port });
serve.step.dependOn(&launch.step);
serve.cwd = app.b.getInstallPath(web_install_dir, "");
return serve;
} else {
return app.step.run();
}
}
};
pub const pkg = std.build.Pkg{
.name = "mach",
.path = .{ .path = thisDir() ++ "/src/main.zig" },
.dependencies = &.{gpu.pkg},
};
fn thisDir() []const u8 {
return std.fs.path.dirname(@src().file) orelse ".";
}
fn ensureDependencySubmodule(allocator: std.mem.Allocator, path: []const u8) !void {
if (std.process.getEnvVarOwned(allocator, "NO_ENSURE_SUBMODULES")) |no_ensure_submodules| {
if (std.mem.eql(u8, no_ensure_submodules, "true")) return;
} else |_| {}
var child = std.ChildProcess.init(&.{ "git", "submodule", "update", "--init", path }, allocator);
child.cwd = thisDir();
child.stderr = std.io.getStdErr();
child.stdout = std.io.getStdOut();
_ = try child.spawnAndWait();
} | build.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const net = std.net;
const fs = std.fs;
const os = std.os;
const fmt = std.fmt;
pub const io_mode = .evented;
pub fn main() anyerror!void {
var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = &general_purpose_allocator.allocator;
var server = net.StreamServer.init(.{});
defer server.deinit();
var proxy = Proxy(1024).init(allocator);
try server.listen(net.Address.parseIp("127.0.0.1", 34329) catch unreachable);
std.debug.warn("listening at {}\n", .{server.listen_address});
while (true) {
const conn = try server.accept();
var client = try proxy.NewClient(allocator, conn);
std.debug.print("new client {}\n", .{proxy.n_clients});
}
}
fn Proxy(n: usize) type {
return struct {
clients: std.AutoHashMap(*Client, void),
n_clients: i32,
allocator: *Allocator,
const Self = @This();
fn init(allocator: *Allocator) Self {
const proxy = Self{
.clients = std.AutoHashMap(*Client, void).init(allocator),
.allocator = allocator,
.n_clients = 0,
};
return proxy;
}
fn deinit(proxy: *Self) void {
var it = proxy.clients.iterator();
while (it.next()) |client| {
_ = client.conn.file.close();
proxy.allocator.destroy(client);
}
}
fn broadcast(proxy: *Self, msg: []const u8, sender: *Client) void {
var it = proxy.clients.iterator();
while (it.next()) |entry| {
const client = entry.key;
if (client == sender) {
continue;
}
client.conn.file.writeAll(msg) catch |e| std.debug.warn("unable to send: {}\n", .{e});
}
}
const ProxyT = @This();
const Client = struct {
id: i32,
conn: net.StreamServer.Connection,
handle_frame: @Frame(handle),
proxy: *ProxyT,
fn handle(self: *Client) !void {
try fmt.format(self.conn.file.writer(), "client {}\n", .{self.id});
var buf: [n]u8 = undefined;
while (true) {
std.debug.print("loop iteration {}\n", .{self.id});
const amt = try self.conn.file.read(&buf);
const msg = buf[0..amt];
std.debug.print("broadcasting {}\n", .{self.id});
self.proxy.broadcast(msg, self);
}
}
};
fn NewClient(proxy: *Self, allocator: *Allocator, conn: net.StreamServer.Connection) !*Client {
const client = try allocator.create(Client);
client.conn = conn;
proxy.n_clients += 1;
client.id = proxy.n_clients;
std.debug.print("starting handler\n", .{});
client.handle_frame = async client.handle();
std.debug.print("registering\n", .{});
client.proxy = proxy;
try proxy.clients.putNoClobber(client, {});
return client;
}
};
} | src/main.zig |
const std = @import("std");
const mem = std.mem;
const ExtendedPictographic = @This();
allocator: *mem.Allocator,
array: []bool,
lo: u21 = 169,
hi: u21 = 131069,
pub fn init(allocator: *mem.Allocator) !ExtendedPictographic {
var instance = ExtendedPictographic{
.allocator = allocator,
.array = try allocator.alloc(bool, 130901),
};
mem.set(bool, instance.array, false);
var index: u21 = 0;
instance.array[0] = true;
instance.array[5] = true;
instance.array[8083] = true;
instance.array[8096] = true;
instance.array[8313] = true;
instance.array[8336] = true;
index = 8427;
while (index <= 8432) : (index += 1) {
instance.array[index] = true;
}
index = 8448;
while (index <= 8449) : (index += 1) {
instance.array[index] = true;
}
index = 8817;
while (index <= 8818) : (index += 1) {
instance.array[index] = true;
}
instance.array[8831] = true;
instance.array[8927] = true;
instance.array[8998] = true;
index = 9024;
while (index <= 9027) : (index += 1) {
instance.array[index] = true;
}
index = 9028;
while (index <= 9029) : (index += 1) {
instance.array[index] = true;
}
instance.array[9030] = true;
instance.array[9031] = true;
index = 9032;
while (index <= 9033) : (index += 1) {
instance.array[index] = true;
}
instance.array[9034] = true;
index = 9039;
while (index <= 9041) : (index += 1) {
instance.array[index] = true;
}
instance.array[9241] = true;
index = 9473;
while (index <= 9474) : (index += 1) {
instance.array[index] = true;
}
instance.array[9485] = true;
instance.array[9495] = true;
index = 9554;
while (index <= 9557) : (index += 1) {
instance.array[index] = true;
}
index = 9559;
while (index <= 9560) : (index += 1) {
instance.array[index] = true;
}
index = 9561;
while (index <= 9562) : (index += 1) {
instance.array[index] = true;
}
instance.array[9563] = true;
instance.array[9564] = true;
index = 9566;
while (index <= 9572) : (index += 1) {
instance.array[index] = true;
}
instance.array[9573] = true;
index = 9574;
while (index <= 9575) : (index += 1) {
instance.array[index] = true;
}
instance.array[9576] = true;
instance.array[9577] = true;
index = 9579;
while (index <= 9580) : (index += 1) {
instance.array[index] = true;
}
index = 9581;
while (index <= 9582) : (index += 1) {
instance.array[index] = true;
}
instance.array[9583] = true;
index = 9584;
while (index <= 9587) : (index += 1) {
instance.array[index] = true;
}
instance.array[9588] = true;
index = 9589;
while (index <= 9590) : (index += 1) {
instance.array[index] = true;
}
instance.array[9591] = true;
instance.array[9592] = true;
index = 9593;
while (index <= 9594) : (index += 1) {
instance.array[index] = true;
}
index = 9595;
while (index <= 9596) : (index += 1) {
instance.array[index] = true;
}
instance.array[9597] = true;
index = 9598;
while (index <= 9600) : (index += 1) {
instance.array[index] = true;
}
instance.array[9601] = true;
index = 9602;
while (index <= 9604) : (index += 1) {
instance.array[index] = true;
}
instance.array[9605] = true;
instance.array[9606] = true;
index = 9607;
while (index <= 9614) : (index += 1) {
instance.array[index] = true;
}
index = 9615;
while (index <= 9616) : (index += 1) {
instance.array[index] = true;
}
instance.array[9617] = true;
index = 9618;
while (index <= 9622) : (index += 1) {
instance.array[index] = true;
}
instance.array[9623] = true;
instance.array[9624] = true;
instance.array[9625] = true;
index = 9626;
while (index <= 9630) : (index += 1) {
instance.array[index] = true;
}
index = 9631;
while (index <= 9642) : (index += 1) {
instance.array[index] = true;
}
index = 9643;
while (index <= 9653) : (index += 1) {
instance.array[index] = true;
}
instance.array[9654] = true;
instance.array[9655] = true;
index = 9656;
while (index <= 9657) : (index += 1) {
instance.array[index] = true;
}
instance.array[9658] = true;
instance.array[9659] = true;
index = 9660;
while (index <= 9661) : (index += 1) {
instance.array[index] = true;
}
instance.array[9662] = true;
instance.array[9663] = true;
index = 9664;
while (index <= 9681) : (index += 1) {
instance.array[index] = true;
}
instance.array[9682] = true;
index = 9683;
while (index <= 9684) : (index += 1) {
instance.array[index] = true;
}
instance.array[9685] = true;
instance.array[9686] = true;
index = 9687;
while (index <= 9692) : (index += 1) {
instance.array[index] = true;
}
index = 9703;
while (index <= 9704) : (index += 1) {
instance.array[index] = true;
}
instance.array[9705] = true;
instance.array[9706] = true;
instance.array[9707] = true;
instance.array[9708] = true;
index = 9709;
while (index <= 9710) : (index += 1) {
instance.array[index] = true;
}
instance.array[9711] = true;
instance.array[9712] = true;
instance.array[9713] = true;
index = 9714;
while (index <= 9715) : (index += 1) {
instance.array[index] = true;
}
index = 9716;
while (index <= 9718) : (index += 1) {
instance.array[index] = true;
}
index = 9719;
while (index <= 9720) : (index += 1) {
instance.array[index] = true;
}
index = 9721;
while (index <= 9725) : (index += 1) {
instance.array[index] = true;
}
instance.array[9726] = true;
index = 9727;
while (index <= 9728) : (index += 1) {
instance.array[index] = true;
}
index = 9729;
while (index <= 9730) : (index += 1) {
instance.array[index] = true;
}
index = 9731;
while (index <= 9734) : (index += 1) {
instance.array[index] = true;
}
index = 9735;
while (index <= 9736) : (index += 1) {
instance.array[index] = true;
}
index = 9737;
while (index <= 9747) : (index += 1) {
instance.array[index] = true;
}
index = 9748;
while (index <= 9749) : (index += 1) {
instance.array[index] = true;
}
index = 9750;
while (index <= 9754) : (index += 1) {
instance.array[index] = true;
}
index = 9755;
while (index <= 9756) : (index += 1) {
instance.array[index] = true;
}
index = 9757;
while (index <= 9758) : (index += 1) {
instance.array[index] = true;
}
instance.array[9759] = true;
index = 9760;
while (index <= 9764) : (index += 1) {
instance.array[index] = true;
}
instance.array[9765] = true;
instance.array[9766] = true;
instance.array[9767] = true;
instance.array[9768] = true;
instance.array[9769] = true;
instance.array[9770] = true;
instance.array[9771] = true;
index = 9772;
while (index <= 9791) : (index += 1) {
instance.array[index] = true;
}
instance.array[9792] = true;
instance.array[9793] = true;
index = 9794;
while (index <= 9798) : (index += 1) {
instance.array[index] = true;
}
index = 9799;
while (index <= 9800) : (index += 1) {
instance.array[index] = true;
}
index = 9801;
while (index <= 9802) : (index += 1) {
instance.array[index] = true;
}
instance.array[9803] = true;
instance.array[9804] = true;
instance.array[9805] = true;
index = 9806;
while (index <= 9808) : (index += 1) {
instance.array[index] = true;
}
instance.array[9809] = true;
index = 9810;
while (index <= 9811) : (index += 1) {
instance.array[index] = true;
}
instance.array[9812] = true;
index = 9813;
while (index <= 9816) : (index += 1) {
instance.array[index] = true;
}
instance.array[9817] = true;
index = 9818;
while (index <= 9819) : (index += 1) {
instance.array[index] = true;
}
instance.array[9820] = true;
index = 9823;
while (index <= 9827) : (index += 1) {
instance.array[index] = true;
}
instance.array[9828] = true;
instance.array[9829] = true;
instance.array[9830] = true;
index = 9831;
while (index <= 9832) : (index += 1) {
instance.array[index] = true;
}
instance.array[9833] = true;
instance.array[9835] = true;
instance.array[9837] = true;
instance.array[9844] = true;
instance.array[9848] = true;
instance.array[9855] = true;
index = 9866;
while (index <= 9867) : (index += 1) {
instance.array[index] = true;
}
instance.array[9883] = true;
instance.array[9886] = true;
instance.array[9891] = true;
instance.array[9893] = true;
index = 9898;
while (index <= 9900) : (index += 1) {
instance.array[index] = true;
}
instance.array[9902] = true;
instance.array[9914] = true;
instance.array[9915] = true;
index = 9916;
while (index <= 9918) : (index += 1) {
instance.array[index] = true;
}
index = 9964;
while (index <= 9966) : (index += 1) {
instance.array[index] = true;
}
instance.array[9976] = true;
instance.array[9991] = true;
instance.array[10006] = true;
index = 10379;
while (index <= 10380) : (index += 1) {
instance.array[index] = true;
}
index = 10844;
while (index <= 10846) : (index += 1) {
instance.array[index] = true;
}
index = 10866;
while (index <= 10867) : (index += 1) {
instance.array[index] = true;
}
instance.array[10919] = true;
instance.array[10924] = true;
instance.array[12167] = true;
instance.array[12180] = true;
instance.array[12782] = true;
instance.array[12784] = true;
index = 126807;
while (index <= 126810) : (index += 1) {
instance.array[index] = true;
}
instance.array[126811] = true;
index = 126812;
while (index <= 127013) : (index += 1) {
instance.array[index] = true;
}
instance.array[127014] = true;
index = 127015;
while (index <= 127062) : (index += 1) {
instance.array[index] = true;
}
index = 127076;
while (index <= 127078) : (index += 1) {
instance.array[index] = true;
}
instance.array[127110] = true;
index = 127171;
while (index <= 127174) : (index += 1) {
instance.array[index] = true;
}
index = 127175;
while (index <= 127176) : (index += 1) {
instance.array[index] = true;
}
index = 127189;
while (index <= 127190) : (index += 1) {
instance.array[index] = true;
}
instance.array[127205] = true;
index = 127208;
while (index <= 127217) : (index += 1) {
instance.array[index] = true;
}
index = 127236;
while (index <= 127292) : (index += 1) {
instance.array[index] = true;
}
index = 127320;
while (index <= 127321) : (index += 1) {
instance.array[index] = true;
}
index = 127322;
while (index <= 127334) : (index += 1) {
instance.array[index] = true;
}
instance.array[127345] = true;
instance.array[127366] = true;
index = 127369;
while (index <= 127377) : (index += 1) {
instance.array[index] = true;
}
index = 127379;
while (index <= 127382) : (index += 1) {
instance.array[index] = true;
}
index = 127392;
while (index <= 127398) : (index += 1) {
instance.array[index] = true;
}
index = 127399;
while (index <= 127400) : (index += 1) {
instance.array[index] = true;
}
index = 127401;
while (index <= 127574) : (index += 1) {
instance.array[index] = true;
}
index = 127575;
while (index <= 127587) : (index += 1) {
instance.array[index] = true;
}
index = 127588;
while (index <= 127589) : (index += 1) {
instance.array[index] = true;
}
instance.array[127590] = true;
instance.array[127591] = true;
instance.array[127592] = true;
instance.array[127593] = true;
index = 127594;
while (index <= 127596) : (index += 1) {
instance.array[index] = true;
}
index = 127597;
while (index <= 127599) : (index += 1) {
instance.array[index] = true;
}
instance.array[127600] = true;
instance.array[127601] = true;
instance.array[127602] = true;
instance.array[127603] = true;
index = 127604;
while (index <= 127605) : (index += 1) {
instance.array[index] = true;
}
index = 127606;
while (index <= 127607) : (index += 1) {
instance.array[index] = true;
}
instance.array[127608] = true;
index = 127609;
while (index <= 127610) : (index += 1) {
instance.array[index] = true;
}
index = 127611;
while (index <= 127619) : (index += 1) {
instance.array[index] = true;
}
index = 127620;
while (index <= 127622) : (index += 1) {
instance.array[index] = true;
}
index = 127623;
while (index <= 127624) : (index += 1) {
instance.array[index] = true;
}
index = 127625;
while (index <= 127626) : (index += 1) {
instance.array[index] = true;
}
index = 127627;
while (index <= 127628) : (index += 1) {
instance.array[index] = true;
}
instance.array[127629] = true;
index = 127630;
while (index <= 127649) : (index += 1) {
instance.array[index] = true;
}
instance.array[127650] = true;
index = 127651;
while (index <= 127654) : (index += 1) {
instance.array[index] = true;
}
instance.array[127655] = true;
index = 127656;
while (index <= 127698) : (index += 1) {
instance.array[index] = true;
}
instance.array[127699] = true;
instance.array[127700] = true;
index = 127701;
while (index <= 127702) : (index += 1) {
instance.array[index] = true;
}
index = 127703;
while (index <= 127722) : (index += 1) {
instance.array[index] = true;
}
index = 127723;
while (index <= 127724) : (index += 1) {
instance.array[index] = true;
}
index = 127725;
while (index <= 127726) : (index += 1) {
instance.array[index] = true;
}
instance.array[127727] = true;
index = 127728;
while (index <= 127730) : (index += 1) {
instance.array[index] = true;
}
index = 127731;
while (index <= 127732) : (index += 1) {
instance.array[index] = true;
}
index = 127733;
while (index <= 127734) : (index += 1) {
instance.array[index] = true;
}
index = 127735;
while (index <= 127771) : (index += 1) {
instance.array[index] = true;
}
instance.array[127772] = true;
instance.array[127773] = true;
instance.array[127774] = true;
instance.array[127775] = true;
instance.array[127776] = true;
instance.array[127777] = true;
index = 127778;
while (index <= 127781) : (index += 1) {
instance.array[index] = true;
}
index = 127782;
while (index <= 127786) : (index += 1) {
instance.array[index] = true;
}
index = 127787;
while (index <= 127798) : (index += 1) {
instance.array[index] = true;
}
index = 127799;
while (index <= 127802) : (index += 1) {
instance.array[index] = true;
}
instance.array[127803] = true;
index = 127804;
while (index <= 127815) : (index += 1) {
instance.array[index] = true;
}
index = 127816;
while (index <= 127817) : (index += 1) {
instance.array[index] = true;
}
instance.array[127818] = true;
instance.array[127819] = true;
instance.array[127820] = true;
instance.array[127821] = true;
instance.array[127822] = true;
index = 127823;
while (index <= 127825) : (index += 1) {
instance.array[index] = true;
}
index = 127831;
while (index <= 127838) : (index += 1) {
instance.array[index] = true;
}
instance.array[127839] = true;
index = 127840;
while (index <= 127842) : (index += 1) {
instance.array[index] = true;
}
index = 127843;
while (index <= 127845) : (index += 1) {
instance.array[index] = true;
}
index = 127846;
while (index <= 127847) : (index += 1) {
instance.array[index] = true;
}
index = 127848;
while (index <= 127849) : (index += 1) {
instance.array[index] = true;
}
instance.array[127850] = true;
instance.array[127851] = true;
instance.array[127852] = true;
instance.array[127853] = true;
index = 127854;
while (index <= 127872) : (index += 1) {
instance.array[index] = true;
}
instance.array[127873] = true;
index = 127874;
while (index <= 127893) : (index += 1) {
instance.array[index] = true;
}
instance.array[127894] = true;
instance.array[127895] = true;
instance.array[127896] = true;
index = 127897;
while (index <= 127931) : (index += 1) {
instance.array[index] = true;
}
instance.array[127932] = true;
index = 127933;
while (index <= 127938) : (index += 1) {
instance.array[index] = true;
}
index = 127939;
while (index <= 127940) : (index += 1) {
instance.array[index] = true;
}
index = 127941;
while (index <= 128003) : (index += 1) {
instance.array[index] = true;
}
instance.array[128004] = true;
index = 128005;
while (index <= 128012) : (index += 1) {
instance.array[index] = true;
}
index = 128013;
while (index <= 128014) : (index += 1) {
instance.array[index] = true;
}
index = 128015;
while (index <= 128066) : (index += 1) {
instance.array[index] = true;
}
index = 128067;
while (index <= 128068) : (index += 1) {
instance.array[index] = true;
}
instance.array[128069] = true;
instance.array[128070] = true;
index = 128071;
while (index <= 128075) : (index += 1) {
instance.array[index] = true;
}
instance.array[128076] = true;
index = 128077;
while (index <= 128078) : (index += 1) {
instance.array[index] = true;
}
instance.array[128079] = true;
index = 128080;
while (index <= 128083) : (index += 1) {
instance.array[index] = true;
}
instance.array[128084] = true;
instance.array[128085] = true;
index = 128086;
while (index <= 128089) : (index += 1) {
instance.array[index] = true;
}
instance.array[128090] = true;
index = 128091;
while (index <= 128094) : (index += 1) {
instance.array[index] = true;
}
instance.array[128095] = true;
instance.array[128096] = true;
index = 128097;
while (index <= 128107) : (index += 1) {
instance.array[index] = true;
}
instance.array[128108] = true;
index = 128109;
while (index <= 128130) : (index += 1) {
instance.array[index] = true;
}
index = 128131;
while (index <= 128132) : (index += 1) {
instance.array[index] = true;
}
index = 128133;
while (index <= 128148) : (index += 1) {
instance.array[index] = true;
}
index = 128157;
while (index <= 128159) : (index += 1) {
instance.array[index] = true;
}
index = 128160;
while (index <= 128161) : (index += 1) {
instance.array[index] = true;
}
index = 128162;
while (index <= 128165) : (index += 1) {
instance.array[index] = true;
}
instance.array[128166] = true;
index = 128167;
while (index <= 128178) : (index += 1) {
instance.array[index] = true;
}
index = 128179;
while (index <= 128190) : (index += 1) {
instance.array[index] = true;
}
index = 128191;
while (index <= 128197) : (index += 1) {
instance.array[index] = true;
}
index = 128198;
while (index <= 128199) : (index += 1) {
instance.array[index] = true;
}
index = 128200;
while (index <= 128201) : (index += 1) {
instance.array[index] = true;
}
index = 128202;
while (index <= 128208) : (index += 1) {
instance.array[index] = true;
}
instance.array[128209] = true;
index = 128210;
while (index <= 128221) : (index += 1) {
instance.array[index] = true;
}
instance.array[128222] = true;
index = 128223;
while (index <= 128224) : (index += 1) {
instance.array[index] = true;
}
index = 128225;
while (index <= 128228) : (index += 1) {
instance.array[index] = true;
}
index = 128229;
while (index <= 128230) : (index += 1) {
instance.array[index] = true;
}
instance.array[128231] = true;
index = 128232;
while (index <= 128235) : (index += 1) {
instance.array[index] = true;
}
index = 128236;
while (index <= 128237) : (index += 1) {
instance.array[index] = true;
}
index = 128238;
while (index <= 128250) : (index += 1) {
instance.array[index] = true;
}
instance.array[128251] = true;
instance.array[128252] = true;
index = 128253;
while (index <= 128254) : (index += 1) {
instance.array[index] = true;
}
instance.array[128255] = true;
index = 128256;
while (index <= 128263) : (index += 1) {
instance.array[index] = true;
}
index = 128264;
while (index <= 128265) : (index += 1) {
instance.array[index] = true;
}
index = 128266;
while (index <= 128274) : (index += 1) {
instance.array[index] = true;
}
instance.array[128275] = true;
index = 128276;
while (index <= 128280) : (index += 1) {
instance.array[index] = true;
}
index = 128281;
while (index <= 128283) : (index += 1) {
instance.array[index] = true;
}
index = 128284;
while (index <= 128295) : (index += 1) {
instance.array[index] = true;
}
index = 128296;
while (index <= 128298) : (index += 1) {
instance.array[index] = true;
}
index = 128299;
while (index <= 128306) : (index += 1) {
instance.array[index] = true;
}
index = 128307;
while (index <= 128309) : (index += 1) {
instance.array[index] = true;
}
index = 128310;
while (index <= 128311) : (index += 1) {
instance.array[index] = true;
}
instance.array[128312] = true;
instance.array[128313] = true;
instance.array[128314] = true;
index = 128315;
while (index <= 128318) : (index += 1) {
instance.array[index] = true;
}
instance.array[128319] = true;
index = 128320;
while (index <= 128325) : (index += 1) {
instance.array[index] = true;
}
instance.array[128326] = true;
index = 128327;
while (index <= 128329) : (index += 1) {
instance.array[index] = true;
}
instance.array[128330] = true;
index = 128331;
while (index <= 128336) : (index += 1) {
instance.array[index] = true;
}
instance.array[128337] = true;
index = 128338;
while (index <= 128342) : (index += 1) {
instance.array[index] = true;
}
instance.array[128343] = true;
index = 128344;
while (index <= 128349) : (index += 1) {
instance.array[index] = true;
}
index = 128350;
while (index <= 128351) : (index += 1) {
instance.array[index] = true;
}
index = 128352;
while (index <= 128356) : (index += 1) {
instance.array[index] = true;
}
instance.array[128357] = true;
instance.array[128358] = true;
instance.array[128359] = true;
instance.array[128360] = true;
index = 128361;
while (index <= 128363) : (index += 1) {
instance.array[index] = true;
}
instance.array[128364] = true;
instance.array[128365] = true;
instance.array[128366] = true;
instance.array[128367] = true;
instance.array[128368] = true;
instance.array[128369] = true;
instance.array[128370] = true;
index = 128371;
while (index <= 128373) : (index += 1) {
instance.array[index] = true;
}
instance.array[128374] = true;
index = 128375;
while (index <= 128380) : (index += 1) {
instance.array[index] = true;
}
index = 128381;
while (index <= 128382) : (index += 1) {
instance.array[index] = true;
}
index = 128383;
while (index <= 128386) : (index += 1) {
instance.array[index] = true;
}
instance.array[128387] = true;
instance.array[128388] = true;
index = 128389;
while (index <= 128390) : (index += 1) {
instance.array[index] = true;
}
index = 128391;
while (index <= 128394) : (index += 1) {
instance.array[index] = true;
}
instance.array[128395] = true;
instance.array[128396] = true;
instance.array[128397] = true;
index = 128398;
while (index <= 128407) : (index += 1) {
instance.array[index] = true;
}
index = 128408;
while (index <= 128411) : (index += 1) {
instance.array[index] = true;
}
index = 128412;
while (index <= 128422) : (index += 1) {
instance.array[index] = true;
}
instance.array[128471] = true;
index = 128472;
while (index <= 128473) : (index += 1) {
instance.array[index] = true;
}
index = 128474;
while (index <= 128476) : (index += 1) {
instance.array[index] = true;
}
instance.array[128477] = true;
instance.array[128478] = true;
instance.array[128479] = true;
instance.array[128480] = true;
index = 128481;
while (index <= 128482) : (index += 1) {
instance.array[index] = true;
}
instance.array[128483] = true;
instance.array[128484] = true;
instance.array[128485] = true;
instance.array[128486] = true;
instance.array[128487] = true;
index = 128488;
while (index <= 128490) : (index += 1) {
instance.array[index] = true;
}
instance.array[128491] = true;
instance.array[128492] = true;
instance.array[128493] = true;
instance.array[128494] = true;
instance.array[128495] = true;
index = 128496;
while (index <= 128497) : (index += 1) {
instance.array[index] = true;
}
index = 128498;
while (index <= 128504) : (index += 1) {
instance.array[index] = true;
}
instance.array[128505] = true;
instance.array[128506] = true;
index = 128507;
while (index <= 128508) : (index += 1) {
instance.array[index] = true;
}
instance.array[128509] = true;
index = 128510;
while (index <= 128516) : (index += 1) {
instance.array[index] = true;
}
index = 128517;
while (index <= 128520) : (index += 1) {
instance.array[index] = true;
}
instance.array[128521] = true;
index = 128522;
while (index <= 128524) : (index += 1) {
instance.array[index] = true;
}
instance.array[128525] = true;
index = 128526;
while (index <= 128527) : (index += 1) {
instance.array[index] = true;
}
index = 128528;
while (index <= 128533) : (index += 1) {
instance.array[index] = true;
}
instance.array[128534] = true;
instance.array[128535] = true;
index = 128536;
while (index <= 128540) : (index += 1) {
instance.array[index] = true;
}
index = 128541;
while (index <= 128545) : (index += 1) {
instance.array[index] = true;
}
instance.array[128546] = true;
instance.array[128547] = true;
index = 128548;
while (index <= 128550) : (index += 1) {
instance.array[index] = true;
}
instance.array[128551] = true;
index = 128552;
while (index <= 128553) : (index += 1) {
instance.array[index] = true;
}
index = 128554;
while (index <= 128555) : (index += 1) {
instance.array[index] = true;
}
instance.array[128556] = true;
index = 128557;
while (index <= 128558) : (index += 1) {
instance.array[index] = true;
}
index = 128559;
while (index <= 128566) : (index += 1) {
instance.array[index] = true;
}
index = 128567;
while (index <= 128572) : (index += 1) {
instance.array[index] = true;
}
index = 128573;
while (index <= 128575) : (index += 1) {
instance.array[index] = true;
}
instance.array[128576] = true;
instance.array[128577] = true;
index = 128578;
while (index <= 128579) : (index += 1) {
instance.array[index] = true;
}
index = 128580;
while (index <= 128582) : (index += 1) {
instance.array[index] = true;
}
instance.array[128583] = true;
index = 128584;
while (index <= 128585) : (index += 1) {
instance.array[index] = true;
}
instance.array[128586] = true;
index = 128587;
while (index <= 128589) : (index += 1) {
instance.array[index] = true;
}
index = 128590;
while (index <= 128591) : (index += 1) {
instance.array[index] = true;
}
instance.array[128592] = true;
instance.array[128593] = true;
index = 128594;
while (index <= 128595) : (index += 1) {
instance.array[index] = true;
}
index = 128596;
while (index <= 128598) : (index += 1) {
instance.array[index] = true;
}
index = 128715;
while (index <= 128726) : (index += 1) {
instance.array[index] = true;
}
index = 128812;
while (index <= 128822) : (index += 1) {
instance.array[index] = true;
}
index = 128823;
while (index <= 128834) : (index += 1) {
instance.array[index] = true;
}
index = 128835;
while (index <= 128854) : (index += 1) {
instance.array[index] = true;
}
index = 128867;
while (index <= 128870) : (index += 1) {
instance.array[index] = true;
}
index = 128927;
while (index <= 128934) : (index += 1) {
instance.array[index] = true;
}
index = 128945;
while (index <= 128950) : (index += 1) {
instance.array[index] = true;
}
index = 128991;
while (index <= 128998) : (index += 1) {
instance.array[index] = true;
}
index = 129029;
while (index <= 129110) : (index += 1) {
instance.array[index] = true;
}
instance.array[129123] = true;
index = 129124;
while (index <= 129126) : (index += 1) {
instance.array[index] = true;
}
index = 129127;
while (index <= 129135) : (index += 1) {
instance.array[index] = true;
}
index = 129136;
while (index <= 129141) : (index += 1) {
instance.array[index] = true;
}
instance.array[129142] = true;
index = 129143;
while (index <= 129150) : (index += 1) {
instance.array[index] = true;
}
index = 129151;
while (index <= 129158) : (index += 1) {
instance.array[index] = true;
}
instance.array[129159] = true;
index = 129160;
while (index <= 129161) : (index += 1) {
instance.array[index] = true;
}
index = 129162;
while (index <= 129169) : (index += 1) {
instance.array[index] = true;
}
index = 129171;
while (index <= 129173) : (index += 1) {
instance.array[index] = true;
}
instance.array[129174] = true;
index = 129175;
while (index <= 129180) : (index += 1) {
instance.array[index] = true;
}
index = 129182;
while (index <= 129186) : (index += 1) {
instance.array[index] = true;
}
instance.array[129187] = true;
index = 129188;
while (index <= 129190) : (index += 1) {
instance.array[index] = true;
}
index = 129191;
while (index <= 129205) : (index += 1) {
instance.array[index] = true;
}
index = 129206;
while (index <= 129218) : (index += 1) {
instance.array[index] = true;
}
index = 129219;
while (index <= 129223) : (index += 1) {
instance.array[index] = true;
}
instance.array[129224] = true;
instance.array[129225] = true;
index = 129226;
while (index <= 129229) : (index += 1) {
instance.array[index] = true;
}
index = 129230;
while (index <= 129231) : (index += 1) {
instance.array[index] = true;
}
instance.array[129232] = true;
instance.array[129233] = true;
instance.array[129234] = true;
index = 129235;
while (index <= 129238) : (index += 1) {
instance.array[index] = true;
}
index = 129239;
while (index <= 129243) : (index += 1) {
instance.array[index] = true;
}
index = 129244;
while (index <= 129256) : (index += 1) {
instance.array[index] = true;
}
index = 129257;
while (index <= 129262) : (index += 1) {
instance.array[index] = true;
}
index = 129263;
while (index <= 129273) : (index += 1) {
instance.array[index] = true;
}
index = 129274;
while (index <= 129275) : (index += 1) {
instance.array[index] = true;
}
index = 129276;
while (index <= 129281) : (index += 1) {
instance.array[index] = true;
}
index = 129282;
while (index <= 129284) : (index += 1) {
instance.array[index] = true;
}
index = 129285;
while (index <= 129286) : (index += 1) {
instance.array[index] = true;
}
index = 129287;
while (index <= 129296) : (index += 1) {
instance.array[index] = true;
}
index = 129297;
while (index <= 129302) : (index += 1) {
instance.array[index] = true;
}
instance.array[129303] = true;
index = 129304;
while (index <= 129305) : (index += 1) {
instance.array[index] = true;
}
index = 129306;
while (index <= 129313) : (index += 1) {
instance.array[index] = true;
}
instance.array[129314] = true;
instance.array[129315] = true;
index = 129316;
while (index <= 129318) : (index += 1) {
instance.array[index] = true;
}
index = 129319;
while (index <= 129341) : (index += 1) {
instance.array[index] = true;
}
index = 129342;
while (index <= 129366) : (index += 1) {
instance.array[index] = true;
}
index = 129367;
while (index <= 129478) : (index += 1) {
instance.array[index] = true;
}
index = 129479;
while (index <= 129482) : (index += 1) {
instance.array[index] = true;
}
instance.array[129483] = true;
index = 129484;
while (index <= 129486) : (index += 1) {
instance.array[index] = true;
}
index = 129487;
while (index <= 129489) : (index += 1) {
instance.array[index] = true;
}
index = 129490;
while (index <= 129494) : (index += 1) {
instance.array[index] = true;
}
index = 129495;
while (index <= 129497) : (index += 1) {
instance.array[index] = true;
}
index = 129498;
while (index <= 129501) : (index += 1) {
instance.array[index] = true;
}
index = 129502;
while (index <= 129510) : (index += 1) {
instance.array[index] = true;
}
index = 129511;
while (index <= 129516) : (index += 1) {
instance.array[index] = true;
}
index = 129517;
while (index <= 129535) : (index += 1) {
instance.array[index] = true;
}
index = 129536;
while (index <= 129542) : (index += 1) {
instance.array[index] = true;
}
index = 129543;
while (index <= 129549) : (index += 1) {
instance.array[index] = true;
}
index = 129550;
while (index <= 129558) : (index += 1) {
instance.array[index] = true;
}
index = 129559;
while (index <= 129561) : (index += 1) {
instance.array[index] = true;
}
index = 129562;
while (index <= 129574) : (index += 1) {
instance.array[index] = true;
}
index = 129575;
while (index <= 129581) : (index += 1) {
instance.array[index] = true;
}
index = 129582;
while (index <= 129622) : (index += 1) {
instance.array[index] = true;
}
index = 129879;
while (index <= 130900) : (index += 1) {
instance.array[index] = true;
}
// Placeholder: 0. Struct name, 1. Code point kind
return instance;
}
pub fn deinit(self: *ExtendedPictographic) void {
self.allocator.free(self.array);
}
// isExtendedPictographic checks if cp is of the kind Extended_Pictographic.
pub fn isExtendedPictographic(self: ExtendedPictographic, cp: u21) bool {
if (cp < self.lo or cp > self.hi) return false;
const index = cp - self.lo;
return if (index >= self.array.len) false else self.array[index];
} | src/components/autogen/emoji-data/ExtendedPictographic.zig |
const std = @import("std");
const testing = std.testing;
// Import structs.
const Ziglyph = @import("../Ziglyph.zig");
const Collator = Ziglyph.Collator;
const Grapheme = Ziglyph.Grapheme;
const GraphemeIterator = Grapheme.GraphemeIterator;
const ComptimeGraphemeIterator = Grapheme.ComptimeGraphemeIterator;
const Letter = Ziglyph.Letter;
const Normalizer = Ziglyph.Normalizer;
const Punct = Ziglyph.Punct;
const Sentence = Ziglyph.Sentence;
const SentenceIterator = Sentence.SentenceIterator;
const ComptimeSentenceIterator = Sentence.ComptimeSentenceIterator;
const UpperMap = Ziglyph.UpperMap;
const Width = Ziglyph.Width;
const Word = Ziglyph.Word;
const WordIterator = Word.WordIterator;
const ComptimeWordIterator = Word.ComptimeWordIterator;
test "Ziglyph struct" {
const z = 'z';
try testing.expect(Ziglyph.isLetter(z));
try testing.expect(Ziglyph.isAlphaNum(z));
try testing.expect(Ziglyph.isPrint(z));
try testing.expect(!Ziglyph.isUpper(z));
const uz = Ziglyph.toUpper(z);
try testing.expect(Ziglyph.isUpper(uz));
try testing.expectEqual(uz, 'Z');
const tz = Ziglyph.toTitle(z);
try testing.expect(Ziglyph.isUpper(tz));
try testing.expectEqual(tz, 'Z');
// String toLower, toTitle and toUpper.
var allocator = std.testing.allocator;
var got = try Ziglyph.toLowerStr(allocator, "AbC123");
errdefer allocator.free(got);
try testing.expect(std.mem.eql(u8, "abc123", got));
allocator.free(got);
got = try Ziglyph.toUpperStr(allocator, "aBc123");
errdefer allocator.free(got);
try testing.expect(std.mem.eql(u8, "ABC123", got));
allocator.free(got);
got = try Ziglyph.toTitleStr(allocator, "thE aBc123 moVie. yes!");
defer allocator.free(got);
try testing.expect(std.mem.eql(u8, "The Abc123 Movie. Yes!", got));
}
test "Aggregate struct" {
const z = 'z';
try testing.expect(Letter.isLetter(z));
try testing.expect(!Letter.isUpper(z));
try testing.expect(!Punct.isPunct(z));
try testing.expect(Punct.isPunct('!'));
const uz = Letter.toUpper(z);
try testing.expect(Letter.isUpper(uz));
try testing.expectEqual(uz, 'Z');
}
test "Component structs" {
const z = 'z';
try testing.expect(Letter.isLower(z));
try testing.expect(!Letter.isUpper(z));
const uz = UpperMap.toUpper(z);
try testing.expect(Letter.isUpper(uz));
try testing.expectEqual(uz, 'Z');
}
test "normalizeTo" {
var allocator = std.testing.allocator;
var normalizer = try Normalizer.init(allocator);
defer normalizer.deinit();
// Canonical Composition (NFC)
const input_nfc = "Complex char: \u{03D2}\u{0301}";
const want_nfc = "Complex char: \u{03D3}";
const got_nfc = try normalizer.normalizeTo(.composed, input_nfc);
try testing.expectEqualSlices(u8, want_nfc, got_nfc);
// Compatibility Composition (NFKC)
const input_nfkc = "Complex char: \u{03A5}\u{0301}";
const want_nfkc = "Complex char: \u{038E}";
const got_nfkc = try normalizer.normalizeTo(.komposed, input_nfkc);
try testing.expectEqualSlices(u8, want_nfkc, got_nfkc);
// Canonical Decomposition (NFD)
const input_nfd = "Complex char: \u{03D3}";
const want_nfd = "Complex char: \u{03D2}\u{0301}";
const got_nfd = try normalizer.normalizeTo(.canon, input_nfd);
try testing.expectEqualSlices(u8, want_nfd, got_nfd);
// Compatibility Decomposition (NFKD)
const input_nfkd = "Complex char: \u{03D3}";
const want_nfkd = "Complex char: \u{03A5}\u{0301}";
const got_nfkd = try normalizer.normalizeTo(.compat, input_nfkd);
try testing.expectEqualSlices(u8, want_nfkd, got_nfkd);
// String comparisons.
try testing.expect(try normalizer.eqlBy("foé", "foe\u{0301}", .normalize));
try testing.expect(try normalizer.eqlBy("foϓ", "fo\u{03D2}\u{0301}", .normalize));
try testing.expect(try normalizer.eqlBy("Foϓ", "fo\u{03D2}\u{0301}", .norm_ignore));
try testing.expect(try normalizer.eqlBy("FOÉ", "foe\u{0301}", .norm_ignore)); // foÉ == foé
try testing.expect(try normalizer.eqlBy("Foé", "foé", .ident)); // Unicode Identifiers caseless match.
}
test "GraphemeIterator" {
var allocator = std.testing.allocator;
const input = "H\u{0065}\u{0301}llo";
var iter = try GraphemeIterator.init(allocator, input);
defer iter.deinit();
const want = &[_][]const u8{ "H", "\u{0065}\u{0301}", "l", "l", "o" };
var i: usize = 0;
while (iter.next()) |grapheme| : (i += 1) {
try testing.expect(grapheme.eql(want[i]));
}
// Need your grapheme clusters at compile time?
comptime var ct_iter = ComptimeGraphemeIterator(input){};
const n: usize = comptime ct_iter.count();
comptime var graphemes: [n]Grapheme = undefined;
comptime {
var ct_i: usize = 0;
while (ct_iter.next()) |grapheme| : (ct_i += 1) {
graphemes[ct_i] = grapheme;
}
}
for (graphemes) |grapheme, j| {
try testing.expect(grapheme.eql(want[j]));
}
}
test "SentenceIterator" {
var allocator = std.testing.allocator;
const input =
\\("Go.") ("He said.")
;
var iter = try SentenceIterator.init(allocator, input);
defer iter.deinit();
// Note the space after the closing right parenthesis is included as part
// of the first sentence.
const s1 =
\\("Go.")
;
const s2 =
\\("He said.")
;
const want = &[_][]const u8{ s1, s2 };
var i: usize = 0;
while (iter.next()) |sentence| : (i += 1) {
try testing.expectEqualStrings(sentence.bytes, want[i]);
}
// Need your sentences at compile time?
@setEvalBranchQuota(2_000);
comptime var ct_iter = ComptimeSentenceIterator(input){};
const n = comptime ct_iter.count();
var sentences: [n]Sentence = undefined;
comptime {
var ct_i: usize = 0;
while (ct_iter.next()) |sentence| : (ct_i += 1) {
sentences[ct_i] = sentence;
}
}
for (sentences) |sentence, j| {
try testing.expect(sentence.eql(want[j]));
}
}
test "WordIterator" {
var allocator = std.testing.allocator;
const input = "The (quick) fox. Fast! ";
var iter = try WordIterator.init(allocator, input);
defer iter.deinit();
const want = &[_][]const u8{ "The", " ", "(", "quick", ")", " ", "fox", ".", " ", "Fast", "!", " " };
var i: usize = 0;
while (iter.next()) |word| : (i += 1) {
try testing.expectEqualStrings(word.bytes, want[i]);
}
// Need your words at compile time?
@setEvalBranchQuota(2_000);
comptime var ct_iter = ComptimeWordIterator(input){};
const n: usize = comptime ct_iter.count();
comptime var words: [n]Word = undefined;
comptime {
var ct_i: usize = 0;
while (ct_iter.next()) |word| : (ct_i += 1) {
words[ct_i] = word;
}
}
for (words) |word, j| {
try testing.expect(word.eql(want[j]));
}
}
test "Code point / string widths" {
var allocator = std.testing.allocator;
try testing.expectEqual(Width.codePointWidth('é', .half), 1);
try testing.expectEqual(Width.codePointWidth('😊', .half), 2);
try testing.expectEqual(Width.codePointWidth('统', .half), 2);
try testing.expectEqual(try Width.strWidth(allocator, "Hello\r\n", .half), 5);
try testing.expectEqual(try Width.strWidth(allocator, "\u{1F476}\u{1F3FF}\u{0308}\u{200D}\u{1F476}\u{1F3FF}", .half), 2);
try testing.expectEqual(try Width.strWidth(allocator, "Héllo 🇪🇸", .half), 8);
try testing.expectEqual(try Width.strWidth(allocator, "\u{26A1}\u{FE0E}", .half), 1); // Text sequence
try testing.expectEqual(try Width.strWidth(allocator, "\u{26A1}\u{FE0F}", .half), 2); // Presentation sequence
// padLeft, center, padRight
const right_aligned = try Width.padLeft(allocator, "w😊w", 10, "-");
defer allocator.free(right_aligned);
try testing.expectEqualSlices(u8, "------w😊w", right_aligned);
const centered = try Width.center(allocator, "w😊w", 10, "-");
defer allocator.free(centered);
try testing.expectEqualSlices(u8, "---w😊w---", centered);
const left_aligned = try Width.padRight(allocator, "w😊w", 10, "-");
defer allocator.free(left_aligned);
try testing.expectEqualSlices(u8, "w😊w------", left_aligned);
}
test "Collation" {
var allocator = std.testing.allocator;
var collator = try Collator.init(allocator);
defer collator.deinit();
try testing.expect(collator.tertiaryAsc("abc", "def"));
try testing.expect(collator.tertiaryDesc("def", "abc"));
try testing.expect(try collator.orderFn("José", "jose", .primary, .eq));
var strings: [3][]const u8 = .{ "xyz", "def", "abc" };
collator.sortAsc(&strings);
try testing.expectEqual(strings[0], "abc");
try testing.expectEqual(strings[1], "def");
try testing.expectEqual(strings[2], "xyz");
strings = .{ "xyz", "def", "abc" };
collator.sortAsciiAsc(&strings);
try testing.expectEqual(strings[0], "abc");
try testing.expectEqual(strings[1], "def");
try testing.expectEqual(strings[2], "xyz");
}
test "Width wrap" {
var allocator = testing.allocator;
var input = "The quick brown fox\r\njumped over the lazy dog!";
var got = try Width.wrap(allocator, input, 10, 3);
defer allocator.free(got);
var want = "The quick\n brown \nfox jumped\n over the\n lazy dog\n!";
try testing.expectEqualStrings(want, got);
} | src/tests/readme_tests.zig |
const std = @import("std");
const input = @import("input.zig");
pub fn run(stdout: anytype) anyerror!void {
{
var input_ = try input.readFile("inputs/day7");
defer input_.deinit();
const result = try part1(&input_);
try stdout.print("7a: {}\n", .{ result });
std.debug.assert(result == 328187);
}
{
var input_ = try input.readFile("inputs/day7");
defer input_.deinit();
const result = try part2(&input_);
try stdout.print("7b: {}\n", .{ result });
std.debug.assert(result == 91257582);
}
}
const NumCrabs = u8;
const max_distance = 2000;
const Distance = std.math.IntFittingRange(0, max_distance);
// https://www.wolframalpha.com/input/?i=summation%28%28n%5E2+%2B+2n+%2B+1%29+%2F+2%29
const max_fuel_used =
(2 * max_distance * max_distance * max_distance + 9 * max_distance * max_distance + 13 * max_distance) * std.math.maxInt(NumCrabs) / 12;
const FuelUsed = std.math.IntFittingRange(0, max_fuel_used);
fn part1(input_: anytype) !FuelUsed {
return solve(input_, part1_fuel_used);
}
fn part1_fuel_used(distance: Distance) FuelUsed {
return @as(FuelUsed, distance);
}
fn part2(input_: anytype) !FuelUsed {
return solve(input_, part2_fuel_used);
}
fn part2_fuel_used(distance: Distance) FuelUsed {
return (@as(FuelUsed, distance) * @as(FuelUsed, distance + 1)) / 2;
}
fn solve(input_: anytype, fuel_used: fn(Distance) FuelUsed) !FuelUsed {
const line = (try input_.next()) orelse return error.InvalidInput;
var line_parts = std.mem.split(u8, line, ",");
var crabs = [_]NumCrabs { 0 } ** max_distance;
var realMaxDistance: Distance = 0;
while (line_parts.next()) |part| {
var pos = try std.fmt.parseInt(Distance, part, 10);
crabs[pos] += 1;
realMaxDistance = std.math.max(realMaxDistance, pos);
}
var end: Distance = 0;
var best_sum: FuelUsed = max_fuel_used;
outer: while (end <= realMaxDistance) : (end += 1) {
var sum: FuelUsed = 0;
var pos: Distance = 0;
while (pos < crabs.len) : (pos += 1) {
const distance = std.math.max(pos, end) - std.math.min(pos, end);
const num_crabs = crabs[pos];
sum += fuel_used(distance) * num_crabs;
if (sum > best_sum) {
continue :outer;
}
}
best_sum = sum;
}
return best_sum;
}
test "day 7 example 1" {
const input_ =
\\16,1,2,0,4,2,7,1,2,14
;
try std.testing.expectEqual(@as(FuelUsed, 14 + 1 + 0 + 2 + 2 + 0 + 5 + 1 + 0 + 12), try part1(&input.readString(input_)));
try std.testing.expectEqual(@as(FuelUsed, 66 + 10 + 6 + 15 + 1 + 6 + 3 + 10 + 6 + 45), try part2(&input.readString(input_)));
} | src/day7.zig |
usingnamespace @import("raylib-zig.zig");
pub extern fn Clamp(value: f32, min: f32, max: f32) f32;
pub extern fn Lerp(start: f32, end: f32, amount: f32) f32;
pub extern fn Normalize(value: f32, start: f32, end: f32) f32;
pub extern fn Remap(value: f32, inputStart: f32, inputEnd: f32, outputStart: f32, outputEnd: f32) f32;
pub extern fn Vector2Zero() Vector2;
pub extern fn Vector2One() Vector2;
pub extern fn Vector2Add(v1: Vector2, v2: Vector2) Vector2;
pub extern fn Vector2AddValue(v: Vector2, add: f32) Vector2;
pub extern fn Vector2Subtract(v1: Vector2, v2: Vector2) Vector2;
pub extern fn Vector2SubtractValue(v: Vector2, sub: f32) Vector2;
pub extern fn Vector2Length(v: Vector2) f32;
pub extern fn Vector2LengthSqr(v: Vector2) f32;
pub extern fn Vector2DotProduct(v1: Vector2, v2: Vector2) f32;
pub extern fn Vector2Distance(v1: Vector2, v2: Vector2) f32;
pub extern fn Vector2Angle(v1: Vector2, v2: Vector2) f32;
pub extern fn Vector2Scale(v: Vector2, scale: f32) Vector2;
pub extern fn Vector2Multiply(v1: Vector2, v2: Vector2) Vector2;
pub extern fn Vector2Negate(v: Vector2) Vector2;
pub extern fn Vector2Divide(v1: Vector2, v2: Vector2) Vector2;
pub extern fn Vector2Normalize(v: Vector2) Vector2;
pub extern fn Vector2Lerp(v1: Vector2, v2: Vector2, amount: f32) Vector2;
pub extern fn Vector2Reflect(v: Vector2, normal: Vector2) Vector2;
pub extern fn Vector2Rotate(v: Vector2, degs: f32) Vector2;
pub extern fn Vector2MoveTowards(v: Vector2, target: Vector2, maxDistance: f32) Vector2;
pub extern fn Vector3Zero() Vector3;
pub extern fn Vector3One() Vector3;
pub extern fn Vector3Add(v1: Vector3, v2: Vector3) Vector3;
pub extern fn Vector3AddValue(v: Vector3, add: f32) Vector3;
pub extern fn Vector3Subtract(v1: Vector3, v2: Vector3) Vector3;
pub extern fn Vector3SubtractValue(v: Vector3, sub: f32) Vector3;
pub extern fn Vector3Scale(v: Vector3, scalar: f32) Vector3;
pub extern fn Vector3Multiply(v1: Vector3, v2: Vector3) Vector3;
pub extern fn Vector3CrossProduct(v1: Vector3, v2: Vector3) Vector3;
pub extern fn Vector3Perpendicular(v: Vector3) Vector3;
pub extern fn Vector3Length(v: Vector3) f32;
pub extern fn Vector3LengthSqr(v: Vector3) f32;
pub extern fn Vector3DotProduct(v1: Vector3, v2: Vector3) f32;
pub extern fn Vector3Distance(v1: Vector3, v2: Vector3) f32;
pub extern fn Vector3Negate(v: Vector3) Vector3;
pub extern fn Vector3Divide(v1: Vector3, v2: Vector3) Vector3;
pub extern fn Vector3Normalize(v: Vector3) Vector3;
pub extern fn Vector3OrthoNormalize(v1: [*c]const Vector3, v2: [*c]const Vector3) void;
pub extern fn Vector3Transform(v: Vector3, mat: Matrix) Vector3;
pub extern fn Vector3RotateByQuaternion(v: Vector3, q: Quaternion) Vector3;
pub extern fn Vector3Lerp(v1: Vector3, v2: Vector3, amount: f32) Vector3;
pub extern fn Vector3Reflect(v: Vector3, normal: Vector3) Vector3;
pub extern fn Vector3Min(v1: Vector3, v2: Vector3) Vector3;
pub extern fn Vector3Max(v1: Vector3, v2: Vector3) Vector3;
pub extern fn Vector3Barycenter(p: Vector3, a: Vector3, b: Vector3, c: Vector3) Vector3;
pub extern fn Vector3ToFloatV(v: Vector3) float3;
pub extern fn MatrixDeterminant(mat: Matrix) f32;
pub extern fn MatrixTrace(mat: Matrix) f32;
pub extern fn MatrixTranspose(mat: Matrix) Matrix;
pub extern fn MatrixInvert(mat: Matrix) Matrix;
pub extern fn MatrixNormalize(mat: Matrix) Matrix;
pub extern fn MatrixIdentity() Matrix;
pub extern fn MatrixAdd(left: Matrix, right: Matrix) Matrix;
pub extern fn MatrixSubtract(left: Matrix, right: Matrix) Matrix;
pub extern fn MatrixMultiply(left: Matrix, right: Matrix) Matrix;
pub extern fn MatrixTranslate(x: f32, y: f32, z: f32) Matrix;
pub extern fn MatrixRotate(axis: Vector3, angle: f32) Matrix;
pub extern fn MatrixRotateX(angle: f32) Matrix;
pub extern fn MatrixRotateY(angle: f32) Matrix;
pub extern fn MatrixRotateZ(angle: f32) Matrix;
pub extern fn MatrixRotateXYZ(ang: Vector3) Matrix;
pub extern fn MatrixRotateZYX(ang: Vector3) Matrix;
pub extern fn MatrixScale(x: f32, y: f32, z: f32) Matrix;
pub extern fn MatrixFrustum(left: f64, right: f64, bottom: f64, top: f64, near: f64, far: f64) Matrix;
pub extern fn MatrixPerspective(fovy: f64, aspect: f64, near: f64, far: f64) Matrix;
pub extern fn MatrixOrtho(left: f64, right: f64, bottom: f64, top: f64, near: f64, far: f64) Matrix;
pub extern fn MatrixLookAt(eye: Vector3, target: Vector3, up: Vector3) Matrix;
pub extern fn MatrixToFloatV(mat: Matrix) float16;
pub extern fn QuaternionAdd(q1: Quaternion, q2: Quaternion) Quaternion;
pub extern fn QuaternionAddValue(q: Quaternion, add: f32) Quaternion;
pub extern fn QuaternionSubtract(q1: Quaternion, q2: Quaternion) Quaternion;
pub extern fn QuaternionSubtractValue(q: Quaternion, sub: f32) Quaternion;
pub extern fn QuaternionIdentity() Quaternion;
pub extern fn QuaternionLength(q: Quaternion) f32;
pub extern fn QuaternionNormalize(q: Quaternion) Quaternion;
pub extern fn QuaternionInvert(q: Quaternion) Quaternion;
pub extern fn QuaternionMultiply(q1: Quaternion, q2: Quaternion) Quaternion;
pub extern fn QuaternionScale(q: Quaternion, mul: f32) Quaternion;
pub extern fn QuaternionDivide(q1: Quaternion, q2: Quaternion) Quaternion;
pub extern fn QuaternionLerp(q1: Quaternion, q2: Quaternion, amount: f32) Quaternion;
pub extern fn QuaternionNlerp(q1: Quaternion, q2: Quaternion, amount: f32) Quaternion;
pub extern fn QuaternionSlerp(q1: Quaternion, q2: Quaternion, amount: f32) Quaternion;
pub extern fn QuaternionFromVector3ToVector3(from: Vector3, to: Vector3) Quaternion;
pub extern fn QuaternionFromMatrix(mat: Matrix) Quaternion;
pub extern fn QuaternionToMatrix(q: Quaternion) Matrix;
pub extern fn QuaternionFromAxisAngle(axis: Vector3, angle: f32) Quaternion;
pub extern fn QuaternionToAxisAngle(q: Quaternion, outAxis: [*c]const Vector3, outAngle: [*c]const f32) void;
pub extern fn QuaternionFromEuler(pitch: f32, yaw: f32, roll: f32) Quaternion;
pub extern fn QuaternionToEuler(q: Quaternion) Vector3;
pub extern fn QuaternionTransform(q: Quaternion, mat: Matrix) Quaternion;
pub extern fn Vector3Unproject(source: Vector3, projection: Matrix, view: Matrix) Vector3; | lib/raylib-zig-math.zig |
const std = @import("std");
// libs
pub const sokol = @import("sokol");
pub const stb = @import("stb");
pub const imgui = @import("imgui");
pub const filebrowser = @import("filebrowser");
// types
pub const Texture = @import("texture.zig").Texture;
pub const RenderTexture = @import("render_texture.zig").RenderTexture;
pub const MenuItem = @import("menu.zig").MenuItem;
pub const FixedList = @import("utils/fixed_list.zig").FixedList;
// namespaces
pub const mem = @import("mem/mem.zig");
pub const fs = @import("fs.zig");
pub const math = @import("math/math.zig");
pub const colors = @import("colors.zig");
pub const menu = @import("menu.zig");
usingnamespace sokol;
usingnamespace imgui;
pub const Config = struct {
init: fn () void,
update: fn () void,
shutdown: ?fn () void = null,
/// optional, will be called if there is no previous dock layout setup with the id of the main dockspace node
setupDockLayout: ?fn (ImGuiID) void = null,
onFileDropped: ?fn ([]const u8) void = null,
width: c_int = 1024,
height: c_int = 768,
swap_interval: c_int = 1,
high_dpi: bool = false,
fullscreen: bool = false,
window_title: [*c]const u8 = "upaya",
enable_clipboard: bool = true,
clipboard_size: c_int = 4096,
/// optionally adds FontAwesome fonts which are accessible via imgui.icons
icon_font: bool = true,
docking: bool = true,
dark_style: bool = false,
/// how the imgui internal data should be stored. If saved_games_dir is used, app_name MUST be specified!
ini_file_storage: enum { none, current_dir, saved_games_dir } = .current_dir,
/// used if ini_file_storage is saved_games_dir as the subfolder in the save games folder
app_name: ?[]const u8 = null,
};
// private
const font_awesome_range: [3]ImWchar = [_]ImWchar{ icons.icon_range_min, icons.icon_range_max, 0 };
var state = struct {
config: Config = undefined,
pass_action: sg_pass_action = undefined,
cmd_down: bool = false,
}{};
pub fn run(config: Config) void {
state.config = config;
var app_desc = std.mem.zeroes(sapp_desc);
app_desc.init_cb = init;
app_desc.frame_cb = update;
app_desc.cleanup_cb = cleanup;
app_desc.event_cb = event;
app_desc.width = config.width;
app_desc.height = config.height;
app_desc.swap_interval = config.swap_interval;
app_desc.high_dpi = config.high_dpi;
app_desc.window_title = config.window_title;
app_desc.enable_clipboard = config.enable_clipboard;
app_desc.clipboard_size = config.clipboard_size;
if (state.config.onFileDropped == null) {
app_desc.max_dropped_files = 0;
}
app_desc.alpha = false;
_ = sapp_run(&app_desc);
}
// Event functions
export fn init() void {
mem.initTmpAllocator();
var desc = std.mem.zeroes(sg_desc);
desc.context = sapp_sgcontext();
sg_setup(&desc);
var imgui_desc = std.mem.zeroes(simgui_desc_t);
imgui_desc.no_default_font = true;
imgui_desc.dpi_scale = sapp_dpi_scale();
if (state.config.ini_file_storage != .none) {
if (state.config.ini_file_storage == .current_dir) {
imgui_desc.ini_filename = "imgui.ini";
} else {
std.debug.assert(state.config.app_name != null);
const path = fs.getSaveGamesFile(state.config.app_name.?, "imgui.ini") catch unreachable;
imgui_desc.ini_filename = mem.allocator.dupeZ(u8, path) catch unreachable;
}
}
simgui_setup(&imgui_desc);
var io = igGetIO();
if (state.config.docking) io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;
io.ConfigDockingWithShift = true;
if (state.config.dark_style) {
igStyleColorsDark(igGetStyle());
}
igGetStyle().FrameRounding = 0;
igGetStyle().WindowRounding = 0;
loadDefaultFont();
state.pass_action.colors[0].action = .SG_ACTION_CLEAR;
state.pass_action.colors[0].val = [_]f32{ 0.2, 0.2, 0.2, 1.0 };
state.config.init();
}
export fn update() void {
const width = sapp_width();
const height = sapp_height();
simgui_new_frame(width, height, 0.017);
if (state.config.docking) beginDock();
state.config.update();
if (state.config.docking) igEnd();
sg_begin_default_pass(&state.pass_action, width, height);
simgui_render();
sg_end_pass();
sg_commit();
}
export fn event(e: [*c]const sapp_event) void {
// special handling of dropped files
if (e[0].type == .SAPP_EVENTTYPE_FILE_DROPPED) {
if (state.config.onFileDropped) |onFileDropped| {
const dropped_file_cnt = sapp_get_num_dropped_files();
var i: usize = 0;
while (i < dropped_file_cnt) : (i += 1) {
onFileDropped(std.mem.spanZ(sapp_get_dropped_file_path(@intCast(c_int, i))));
}
}
}
// handle cmd+Q on macos
if (std.Target.current.os.tag == .macosx) {
if (e[0].type == .SAPP_EVENTTYPE_KEY_DOWN) {
if (e[0].key_code == .SAPP_KEYCODE_LEFT_SUPER) {
state.cmd_down = true;
} else if (state.cmd_down and e[0].key_code == .SAPP_KEYCODE_Q) {
sapp_request_quit();
}
} else if (e[0].type == .SAPP_EVENTTYPE_KEY_UP and e[0].key_code == .SAPP_KEYCODE_LEFT_SUPER) {
state.cmd_down = false;
}
}
_ = simgui_handle_event(e);
}
export fn cleanup() void {
if (state.config.shutdown) |shutdown| shutdown();
simgui_shutdown();
sg_shutdown();
}
pub fn quit() void {
sapp_request_quit();
}
// helper functions
fn beginDock() void {
const vp = igGetMainViewport();
var work_pos = ImVec2{};
var work_size = ImVec2{};
ImGuiViewport_GetWorkPos(&work_pos, vp);
ImGuiViewport_GetWorkSize(&work_size, vp);
igSetNextWindowPos(work_pos, ImGuiCond_Always, .{});
igSetNextWindowSize(work_size, ImGuiCond_Always);
igSetNextWindowViewport(vp.ID);
var window_flags = ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_MenuBar;
window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove;
window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
igPushStyleVarVec2(ImGuiStyleVar_WindowPadding, .{});
_ = igBegin("Dockspace", null, window_flags);
igPopStyleVar(1);
const io = igGetIO();
const dockspace_id = igGetIDStr("upaya-dockspace");
// igDockBuilderRemoveNode(dockspace_id); // uncomment for testing initial layout setup code
if (igDockBuilderGetNode(dockspace_id) == null) {
if (state.config.setupDockLayout) |setupDockLayout| {
var dock_main_id = igDockBuilderAddNode(dockspace_id, ImGuiDockNodeFlags_DockSpace);
igDockBuilderSetNodeSize(dockspace_id, work_size);
setupDockLayout(dock_main_id);
}
}
igDockSpace(dockspace_id, .{}, ImGuiDockNodeFlags_None, null);
}
fn loadDefaultFont() void {
var io = igGetIO();
_ = ImFontAtlas_AddFontDefault(io.Fonts, null);
// add FontAwesome optionally
if (state.config.icon_font) {
var icons_config = ImFontConfig_ImFontConfig();
icons_config[0].MergeMode = true;
icons_config[0].PixelSnapH = true;
icons_config[0].FontDataOwnedByAtlas = false;
var data = @embedFile("assets/" ++ icons.font_icon_filename_fas);
_ = ImFontAtlas_AddFontFromMemoryTTF(io.Fonts, data, data.len, 14, icons_config, &font_awesome_range[0]);
}
var w: i32 = undefined;
var h: i32 = undefined;
var bytes_per_pixel: i32 = undefined;
var pixels: [*c]u8 = undefined;
ImFontAtlas_GetTexDataAsRGBA32(io.Fonts, &pixels, &w, &h, &bytes_per_pixel);
var tex = Texture.initWithData(pixels[0..@intCast(usize, w * h * bytes_per_pixel)], w, h, .nearest);
ImFontAtlas_SetTexID(io.Fonts, tex.imTextureID());
} | src/upaya.zig |
const std = @import("std");
const firm = @import("firmly-zig").low_level;
const mainLocalVars = 1; // main function has 1 local variable
const dataSize = 30000; // A 30000 byte of storage for brainfuck
const variablePointer = 0; // The pointer to the current position in the data
var typeBu: ?*firm.ir_type = null;
var putchar: ?*firm.ir_node = null;
var getchar: ?*firm.ir_node = null;
var putcharEntity: ?*firm.ir_entity = null;
var getcharEntity: ?*firm.ir_entity = null;
fn initializeFirm() void {
firm.irInit();
}
fn createGraph() ?*firm.ir_graph {
var methodType : ?*firm.ir_type = firm.newTypeMethod(0, 1, false, .{.calling_convention_special = firm.calling_convention_enum.calling_helpers.decl_set}, firm.mtp_additional_properties.no_property);
var intType : ?*firm.ir_type= firm.newTypePrimitive(firm.getMode(.Is));
firm.setMethodResType(methodType, 0, intType);
var id = firm.irPlatformMangleGlobal("bf_main");
var globalType = firm.getGlobType();
var entity = firm.newEntity(globalType, id, methodType);
var irGraph = firm.newIrGraph(entity, mainLocalVars);
firm.setEntityIdent(entity, id);
return irGraph;
}
fn createField() ?*firm.ir_entity {
var byteType = firm.newTypePrimitive(firm.getMode(.Bu));
var arrayType = firm.newTypeArray(byteType, dataSize);
var id = firm.irPlatformMangleGlobal("data");
var globalType = firm.getGlobType();
var entity = firm.newEntity(globalType, id, arrayType);
var nullInitializer = firm.getInitializerNull();
firm.setEntityInitializer(entity, nullInitializer);
firm.setEntityVisibility(entity, firm.ir_visibility.private);
return entity;
}
fn createPutCharEntity() ?*firm.ir_entity {
var typeInt = firm.newTypePrimitive(firm.getMode(.Is));
var methodType = firm.newTypeMethod(1, 1, false, .{.calling_convention_special = firm.calling_convention_enum.calling_helpers.decl_set}, firm.mtp_additional_properties.no_property);
firm.setMethodResType(methodType, 0, typeInt);
firm.setMethodParamType(methodType, 0, typeInt);
var id = firm.irPlatformMangleGlobal("putchar");
var globalType = firm.getGlobType();
var entity = firm.newEntity(globalType, id, methodType);
firm.setEntityIdent(entity, id);
return entity;
}
fn createGetCharEntity() ?*firm.ir_entity {
var typeInt = firm.newTypePrimitive(firm.getMode(.Is));
var methodType = firm.newTypeMethod(0, 1, false, .{.calling_convention_special = firm.calling_convention_enum.calling_helpers.decl_set}, firm.mtp_additional_properties.no_property);
firm.setMethodResType(methodType, 0, typeInt);
var id = firm.irPlatformMangleGlobal("getchar");
var globalType = firm.getGlobType();
var entity = firm.newEntity(globalType, id, methodType);
firm.setEntityIdent(entity, id);
return entity;
}
fn increasePointer() void {
var pointerValue = firm.getValue(variablePointer, firm.getMode(.P));
var offsetMode = firm.getReferenceOffsetMode(firm.getMode(.P));
var tarval = firm.newTarvalFromLong(1, offsetMode);
var one = firm.newConst(tarval);
var add = firm.newAdd(pointerValue, one);
firm.setValue(variablePointer, add);
}
fn decreasePointer() void {
var pointerValue = firm.getValue(variablePointer, firm.getMode(.P));
var offsetMode = firm.getReferenceOffsetMode(firm.getMode(.P));
var tarval = firm.newTarvalFromLong(1, offsetMode);
var one = firm.newConst(tarval);
var sub = firm.newSub(pointerValue, one);
firm.setValue(variablePointer, sub);
}
fn incrementByte() void {
var pointerValue = firm.getValue(variablePointer, firm.getMode(.P));
var mem = firm.getStore();
var load = firm.newLoad(mem, pointerValue, firm.getMode(.Bu), typeBu, firm.ir_cons_flags.cons_none);
var loadResult = firm.newProj(load, firm.getMode(.Bu), @enumToInt(firm.projection_input_Load.res));
var loadMem = firm.newProj(load, firm.getMode(.M), @enumToInt(firm.projection_input_Load.M));
var tarval = firm.newTarvalFromLong(1, firm.getMode(.Bu));
var one = firm.newConst(tarval);
var add = firm.newAdd(loadResult, one);
var store = firm.newStore(loadMem, pointerValue, add, typeBu, firm.ir_cons_flags.cons_none);
var storeMem = firm.newProj(store, firm.getMode(.M), @enumToInt(firm.projection_input_Store.M));
firm.setStore(storeMem);
}
fn decrementByte() void {
var pointerValue = firm.getValue(variablePointer, firm.getMode(.P));
var mem = firm.getStore();
var load = firm.newLoad(mem, pointerValue, firm.getMode(.Bu), typeBu, firm.ir_cons_flags.cons_none);
var loadResult = firm.newProj(load, firm.getMode(.Bu), @enumToInt(firm.projection_input_Load.res));
var loadMem = firm.newProj(load, firm.getMode(.M), @enumToInt(firm.projection_input_Load.M));
var tarval = firm.newTarvalFromLong(1, firm.getMode(.Bu));
var one = firm.newConst(tarval);
var sub = firm.newSub(loadResult, one);
var store = firm.newStore(loadMem, pointerValue, sub, typeBu, firm.ir_cons_flags.cons_none);
var storeMem = firm.newProj(store, firm.getMode(.M), @enumToInt(firm.projection_input_Store.M));
firm.setStore(storeMem);
}
fn outputByte() void {
if (putchar == null) {
putcharEntity = createPutCharEntity();
putchar = firm.newAddress(putcharEntity);
}
var pointerValue = firm.getValue(variablePointer, firm.getMode(.P));
var mem = firm.getStore();
var load = firm.newLoad(mem, pointerValue, firm.getMode(.Bu), typeBu, firm.ir_cons_flags.cons_none);
var loadResult = firm.newProj(load, firm.getMode(.Bu), @enumToInt(firm.projection_input_Load.res));
var convert = firm.newConv(loadResult, firm.getMode(.Is));
var in: [1]?*firm.ir_node = .{convert};
var cType = firm.getEntityType(putcharEntity);
var call = firm.newCall(mem, putchar, 1, &in, cType);
var callMem = firm.newProj(call, firm.getMode(.M), @enumToInt(firm.projection_input_Call.M));
firm.setStore(callMem);
}
fn inputByte() void {
if (getchar == null) {
getcharEntity = createGetCharEntity();
getchar = firm.newAddress(getcharEntity);
}
var mem = firm.getStore();
var ctype = firm.getEntityType(getcharEntity);
var call = firm.newCall(mem, getchar, 0, null, ctype);
var callMem = firm.newProj(call, firm.getMode(.M), @enumToInt(firm.projection_input_Call.M));
var callResults = firm.newProj(call, firm.getMode(.T), @enumToInt(firm.projection_input_Call.T_result));
var callResult = firm.newProj(callResults, firm.getMode(.Is), 0);
var pointerValue = firm.getValue(variablePointer, firm.getMode(.P));
var convert = firm.newConv(callResult, firm.getMode(.Is));
var store = firm.newStore(callMem, pointerValue, convert, typeBu, firm.ir_cons_flags.cons_none);
var storeMem = firm.newProj(store, firm.getMode(.M), @enumToInt(firm.projection_input_Store.M));
firm.setStore(storeMem);
}
fn createReturn() void {
var mem = firm.getStore();
var zero = firm.newConst(firm.newTarvalFromLong(0, firm.getMode(.Is)));
var returnNode = firm.newReturn(mem, 1, &zero);
var endBlock = firm.getIrgEndBlock(firm.current_ir_graph);
firm.addImmblockPred(endBlock, returnNode);
firm.matureImmblock(firm.getCurBlock());
firm.setCurBlock(null);
}
fn parseLoop() void {
var jmp = firm.newJmp();
firm.matureImmblock(firm.getCurBlock());
var loopHeaderBlock = firm.newImmblock();
firm.addImmblockPred(loopHeaderBlock, jmp);
firm.setCurBlock(loopHeaderBlock);
var pointerValue = firm.getValue(variablePointer, firm.getMode(.P));
var mem = firm.getStore();
var load = firm.newLoad(mem, pointerValue, firm.getMode(.Bu), typeBu, firm.ir_cons_flags.cons_none);
var loadResult = firm.newProj(load, firm.getMode(.Bu), @enumToInt(firm.projection_input_Load.res));
var loadMem = firm.newProj(load, firm.getMode(.M), @enumToInt(firm.projection_input_Load.M));
firm.setStore(loadMem);
var zero = firm.newConst(firm.newTarvalFromLong(0, firm.getMode(.Bu)));
var equal = firm.newCmp(loadResult, zero, firm.ir_relation.equal);
var cond = firm.newCond(equal);
var trueProj = firm.newProj(cond, firm.getMode(.X), @enumToInt(firm.projection_input_Cond.True));
var falseProj = firm.newProj(cond, firm.getMode(.X), @enumToInt(firm.projection_input_Cond.False));
var loopBodyBlock = firm.newImmblock();
firm.addImmblockPred(loopBodyBlock, falseProj);
firm.setCurBlock(loopBodyBlock);
suspend {}
var jmp2 = firm.newJmp();
firm.addImmblockPred(loopHeaderBlock, jmp2);
firm.matureImmblock(loopHeaderBlock);
firm.matureImmblock(firm.getCurBlock());
var afterLoop = firm.newImmblock();
firm.addImmblockPred(afterLoop, trueProj);
firm.setCurBlock(afterLoop);
}
fn parse(file: std.fs.File) !void {
var buffer: [128 * 1024]u8 = undefined;
var frameBuffers: [256]@Frame(parseLoop) = undefined;
var reader = file.reader();
var size: usize = 1;
var loop: usize = 0;
while (size != 0) {
size = try reader.read(&buffer);
if (size > 0) {
for (buffer[0..size]) |v| {
// We interpret brainfuck as a sequence of commands.
switch (v) {
'>' => increasePointer(),
'<' => decreasePointer(),
'+' => incrementByte(),
'-' => decrementByte(),
'.' => outputByte(),
',' => inputByte(),
'[' => {
loop += 1;
frameBuffers[loop - 1] = async parseLoop();
},
']' => {
resume frameBuffers[loop-1];
if (@subWithOverflow(usize, loop, 1, &loop)) {
std.log.err("parse error: unexpected '['\n", .{});
}
},
else => {},
}
}
}
}
if (loop > 0) {
std.log.err("parse error: unmatched '['\n", .{});
}
}
/// This is a port of https://github.com/libfirm/firm-bf/blob/master/main.c using firmly-zig low level API
pub fn main() !void {
initializeFirm();
var graph = createGraph();
firm.setCurrentIrGraph(graph);
typeBu = firm.getTypeForMode(firm.getMode(.Bu));
var field = createField();
var fieldStart = firm.newAddress(field);
firm.setValue(variablePointer, fieldStart);
var file: std.fs.File = try std.fs.cwd().openFile("test.bf", std.fs.File.OpenFlags{});
try parse(file);
file.close();
createReturn();
firm.irgFinalizeCons(graph);
firm.irgAssertVerify(graph);
firm.doLoopInversion(graph);
firm.optimizeReassociation(graph);
firm.optimizeLoadStore(graph);
firm.optimizeGraphDf(graph);
firm.combo(graph);
firm.scalarReplacementOpt(graph);
firm.placeCode(graph);
firm.optimizeReassociation(graph);
firm.optimizeGraphDf(graph);
firm.optJumpthreading(graph);
firm.optimizeGraphDf(graph);
firm.constructConfirms(graph);
firm.optimizeGraphDf(graph);
firm.removeConfirms(graph);
firm.optimizeCf(graph);
firm.optimizeLoadStore(graph);
firm.optimizeGraphDf(graph);
firm.combo(graph);
firm.placeCode(graph);
firm.optimizeCf(graph);
var out = std.c.fopen("test.s", "w");
if (out == null) {
std.log.err("could not open output file\n", .{});
return;
}
if (out) |o| {
firm.beMain(o, "");
_ = std.c.fclose(o);
}
} | example/bf_example.zig |
const std = @import("std");
const expect = std.testing.expect;
const Ram = @import("ram.zig").Ram;
test "should initialize correct size of memory locations" {
const ram = Ram.init();
expect(ram.memory.len == 0xFFFF);
}
test "should initialize memory locations to correct values" {
const ram = Ram.init();
expect(ram.memory[0x0000] == 0xFF);
expect(ram.memory[0x0001] == 0xFF);
expect(ram.memory[0x0002] == 0xFF);
expect(ram.memory[0x0003] == 0xFF);
expect(ram.memory[0x0004] == 0xFF);
expect(ram.memory[0x0005] == 0xFF);
expect(ram.memory[0x0006] == 0xFF);
expect(ram.memory[0x0007] == 0xFF);
expect(ram.memory[0x0008] == 0xF7);
expect(ram.memory[0x0009] == 0xEF);
expect(ram.memory[0x000A] == 0xDF);
expect(ram.memory[0x000B] == 0xFF);
expect(ram.memory[0x000C] == 0xFF);
expect(ram.memory[0x000D] == 0xFF);
expect(ram.memory[0x000E] == 0xFF);
expect(ram.memory[0x000F] == 0xBF);
for (ram.memory[0x0010..0x07FF]) |value| {
expect(value == 0xFF);
}
for (ram.memory[0x0800..0xFFFF]) |value| {
expect(value == 0x00);
}
}
test "should initialize stack pointer" {
const ram = Ram.init();
expect(ram.stack_pointer == 0xFD);
}
test "should correctly write 8 bit value to memory" {
var ram = Ram.init();
ram.write(0x0000, 0x42);
expect(ram.memory[0x0000] == 0x42);
}
test "should correctly read 8 bit value from memory" {
var ram = Ram.init();
ram.write(0x0000, 0x42);
expect(ram.read_8(0x0000) == 0x42);
}
test "should correctly read 16 bit value from memory" {
var ram = Ram.init();
ram.write(0x0000, 0x12);
ram.write(0x0001, 0x34);
expect(ram.read_16(0x0000) == 0x3412);
}
test "should correctly read 16 bit value with boundary bug from memory" {
var ram = Ram.init();
ram.write(0x00FF, 0x12);
ram.write(0x0100, 0x34);
ram.write(0x0000, 0x56);
expect(ram.read_16_with_bug(0x00FF) == 0x5612);
}
test "should correctly push value to stack" {
var ram = Ram.init();
ram.push_to_stack(0x42);
expect(ram.stack_pointer == 0xFC);
expect(ram.read_8(0x0100 + @intCast(u16, ram.stack_pointer) + 0x0001) == 0x42);
}
test "should correctly pop value from the stack" {
var ram = Ram.init();
ram.push_to_stack(0x42);
expect(ram.stack_pointer == 0xFC);
expect(ram.pop_from_stack() == 0x42);
expect(ram.stack_pointer == 0xFD);
} | src/test_ram.zig |
const std = @import("std");
const testing = std.testing;
const Allocator = std.mem.Allocator;
const data = @import("data.zig").table;
/// Caller must free returned memory.
pub fn unidecodeAlloc(allocator: Allocator, utf8: []const u8) ![]u8 {
var buf = try std.ArrayList(u8).initCapacity(allocator, utf8.len);
errdefer buf.deinit();
var utf8_view = try std.unicode.Utf8View.init(utf8);
var codepoint_it = utf8_view.iterator();
while (codepoint_it.nextCodepoint()) |codepoint| switch (codepoint) {
// ASCII
0x00...0x7F => {
try buf.append(@intCast(u8, codepoint));
},
// Only have mappings for the Basic Multilingual Plane
0x80...0xFFFF => {
const replacement = getReplacement(codepoint);
try buf.appendSlice(replacement);
},
// skip anything above the Basic Multilingual Plane
else => {},
};
return buf.toOwnedSlice();
}
/// Transliterates the `utf8` into `dest` and returns the length of
/// the transliterated ASCII.
///
/// `dest` must be large enough to handle the converted ASCII,
/// or it will invoke safety-checked illegal behavior (or undefined
/// behavior in modes without runtime safety)
///
/// Because the conversions can be multiple characters long, it is
/// hard to calculate a 'safe' size for any input. As a result, this
/// should probably only be used at comptime or on known inputs.
pub fn unidecodeBuf(dest: []u8, utf8: []const u8) !usize {
var utf8_view = try std.unicode.Utf8View.init(utf8);
var codepoint_it = utf8_view.iterator();
var end_index: usize = 0;
while (codepoint_it.nextCodepoint()) |codepoint| switch (codepoint) {
// ASCII
0x00...0x7F => {
dest[end_index] = @intCast(u8, codepoint);
end_index += 1;
},
// Only have mappings for the Basic Multilingual Plane
0x80...0xFFFF => {
const replacement = getReplacement(codepoint);
std.mem.copy(u8, dest[end_index..], replacement);
end_index += replacement.len;
},
// skip anything above the Basic Multilingual Plane
else => {},
};
return end_index;
}
/// Transliterates a UTF-8 string literal into an ASCII-only string literal.
pub fn unidecodeStringLiteral(comptime utf8: []const u8) *const [calcUnidecodeLen(utf8):0]u8 {
comptime {
const len: usize = calcUnidecodeLen(utf8);
var buf: [len:0]u8 = [_:0]u8{0} ** len;
const buf_len = unidecodeBuf(&buf, utf8) catch |err| @compileError(err);
std.debug.assert(len == buf_len);
return &buf;
}
}
fn calcUnidecodeLen(utf8: []const u8) usize {
var codepoint_it = std.unicode.Utf8Iterator{ .bytes = utf8, .i = 0 };
var dest_len: usize = 0;
while (codepoint_it.nextCodepoint()) |codepoint| switch (codepoint) {
// ASCII
0x00...0x7F => {
dest_len += 1;
},
// Only have mappings for the Basic Multilingual Plane
0x80...0xFFFF => {
const replacement = getReplacement(codepoint);
dest_len += replacement.len;
},
// skip anything above the Basic Multilingual Plane
else => {},
};
return dest_len;
}
fn getReplacement(codepoint: u21) []const u8 {
const section = codepoint >> 8;
const index = codepoint % 256;
return data[section][index];
}
fn expectTransliterated(expected: []const u8, utf8: []const u8) !void {
const transliterated = try unidecodeAlloc(testing.allocator, utf8);
defer testing.allocator.free(transliterated);
try testing.expectEqualStrings(expected, transliterated);
}
test "ascii" {
// all ASCII including control characters should remain unchanged
try expectTransliterated("\x00\x01\r\n", "\x00\x01\r\n");
try expectTransliterated("hello!", "hello!");
}
test "transliteration / romanization" {
// Greek -> unidecode directly
try expectTransliterated("Taugetos", "Ταΰγετος");
// (Greek -> ELOT 743) -> unidecode
try expectTransliterated("Taygetos", "Taÿ́getos");
// Cyrillic -> unidecode directly
try expectTransliterated("Slav'sia, Otechestvo nashe svobodnoe", "Славься, Отечество наше свободное");
// (Cyrillic -> ISO 9) -> unidecode
try expectTransliterated("Slav'sa, Otecestvo nase svobodnoe", "Slavʹsâ, Otečestvo naše svobodnoe");
}
test "readme examples" {
try expectTransliterated("yeah", "ÿéáh");
try expectTransliterated("Bei Jing ", "北亰");
try expectTransliterated("Slav'sia", "Славься");
try expectTransliterated("[## ] 50%", "[██ ] 50%");
}
test "string literals" {
const utf8_literal = "Ταΰγετος";
const unidecoded_literal = comptime unidecodeStringLiteral(utf8_literal);
comptime try testing.expectEqualStrings("Taugetos", unidecoded_literal);
}
test "output is always ASCII" {
// for every UTF-8 codepoint within the Basic Multilingual Plane,
// check that its transliterated form is valid ASCII
var buf: [4]u8 = undefined;
var output_buf: [256]u8 = undefined;
var codepoint: u21 = 0;
while (codepoint <= 0xFFFF) : (codepoint += 1) {
if (!std.unicode.utf8ValidCodepoint(codepoint)) {
continue;
}
const num_bytes = try std.unicode.utf8Encode(codepoint, &buf);
const output_len = try unidecodeBuf(&output_buf, buf[0..num_bytes]);
for (output_buf[0..output_len]) |c| {
testing.expect(std.ascii.isASCII(c)) catch |err| {
std.debug.print("non-ASCII char {} found when converting codepoint {x} ({s})\n", .{ c, codepoint, &buf });
return err;
};
}
}
// TODO: this type of check could be done at comptime?
// comptime evaluation is a bit too slow for that right now though
// (needs like a million backwards branches for this to
// not hit the limit):
//
// for (data) |row| {
// for (row) |conversion| {
// for (conversion) |c| {
// if (!std.ascii.isASCII(c)) {
// @compileError("non-ASCII character found in conversion data");
// }
// }
// }
// }
} | src/unidecode.zig |
const std = @import("std");
const time = std.time;
const testing = std.testing;
const Progress = @This();
fn Typed(comptime Writer: type) type {
return struct {
width: u32 = 20,
total: u32 = 100,
left_end: ?u8 = '[',
right_end: ?u8 = ']',
progress: u32 = 0,
filled: u8 = '=',
head: u8 = '>',
display_fraction: bool = false,
display_percentage: bool = true,
writer: Writer,
const Self = @This();
pub fn init(writer: Writer) Self {
return .{ .writer = writer };
}
/// Draw the current status of the progress bar.
pub fn draw(self: *Self) !void {
if (self.progress > self.total)
self.progress = self.total;
const percent = @intToFloat(f32, self.progress) / @intToFloat(f32, self.total);
const filled_width = @floatToInt(u32, percent * @intToFloat(f32, self.width));
var remaining = self.width;
try self.writer.writeByte('\r');
if (self.left_end) |char|
try self.writer.writeByte(char);
while (remaining > self.width - filled_width) : (remaining -= 1) {
try self.writer.writeByte(self.filled);
}
if (remaining > 0) {
try self.writer.writeByte(self.head);
remaining -= 1;
}
while (remaining > 0) : (remaining -= 1) {
try self.writer.writeByte(' ');
}
if (self.right_end) |char| {
try self.writer.writeByte(char);
}
if (self.display_fraction) {
try self.writer.print(" {d}/{d}", .{ self.progress, self.total });
}
if (self.display_percentage) {
if (percent == 0.0) {
try self.writer.print(" 0%", .{});
} else {
try self.writer.print(" {d:.0}%", .{percent * 100});
}
}
}
/// Increase the progress by 1.
/// Return the current progress, or `null` if complete.
/// Re-renders the progress bar.
pub fn next(self: *Self) !?u32 {
self.progress += 1;
try self.draw();
if (self.progress == self.total) {
return null;
}
return self.progress;
}
/// Increment the progress by `step`.
/// Returns the current progress, or `null` if complete.
/// Re-renders the progress bar.
pub fn increment(self: *Self, step: u32) !?u32 {
self.progress += step;
try self.draw();
if (self.progress == self.total) {
return null;
}
return self.progress;
}
};
}
/// Initialize a new progress bar with a writer, typically stdout or stderr.
pub fn init(writer: anytype) Typed(@TypeOf(writer)) {
return Typed(@TypeOf(writer)).init(writer);
}
test "initialization" {
var stdout = std.io.getStdOut().writer();
var bar = Progress.init(stdout);
}
test "display bar" {
var stdout = std.io.getStdOut().writer();
var bar = Progress.init(stdout);
bar.total = 300;
bar.width = 50;
bar.display_fraction = true;
try stdout.writeByte('\n');
try bar.draw();
while (try bar.next()) |_| {
time.sleep(time.ns_per_ms * 5);
}
try stdout.writeByte('\n');
} | src/main.zig |
const builtin = @import("builtin");
const clap = @import("clap");
const std = @import("std");
const util = @import("util");
const c = @import("c.zig");
const nk = @import("nuklear.zig");
const Executables = @import("Executables.zig");
const debug = std.debug;
const fmt = std.fmt;
const fs = std.fs;
const heap = std.heap;
const io = std.io;
const math = std.math;
const mem = std.mem;
const process = std.process;
const time = std.time;
const escape = util.escape;
const path = fs.path;
// TODO: proper versioning
const program_version = "0.0.0";
const bug_message = "Hi user. You have just hit a bug/limitation in the program. " ++
"If you care about this program, please report this to the issue tracker here: " ++
"https://github.com/TM35-Metronome/metronome/issues/new";
const fps = 60;
const frame_time = time.ns_per_s / fps;
const platform = switch (builtin.target.os.tag) {
.windows => struct {
pub extern "kernel32" fn GetConsoleWindow() callconv(std.os.windows.WINAPI) std.os.windows.HWND;
},
else => struct {},
};
const border_group = c.NK_WINDOW_BORDER | c.NK_WINDOW_NO_SCROLLBAR;
const border_title_group = border_group | c.NK_WINDOW_TITLE;
pub fn main() anyerror!void {
// HACK: I don't want to show a console to the user.
// Here is someone explaing what to pass to the C compiler to make that happen:
// https://stackoverflow.com/a/9619254
// I have no idea how to get the same behavior using the Zig compiler, so instead
// I use this solution:
// https://stackoverflow.com/a/9618984
switch (builtin.target.os.tag) {
.windows => _ = std.os.windows.user32.showWindow(platform.GetConsoleWindow(), 0),
else => {},
}
const allocator = heap.c_allocator;
// Set up essetial state for the program to run. If any of these
// fail, the only thing we can do is exit.
var timer = try time.Timer.start();
const ctx: *nk.Context = c.nkInit(800, 600) orelse return error.CouldNotInitNuklear;
defer c.nkDeinit(ctx);
{
const black = nk.rgb(0x00, 0x00, 0x00);
const white = nk.rgb(0xff, 0xff, 0xff);
const header_gray = nk.rgb(0xf5, 0xf5, 0xf5);
const border_gray = nk.rgb(0xda, 0xdb, 0xdc);
const light_gray1 = nk.rgb(0xe1, 0xe1, 0xe1);
const light_gray2 = nk.rgb(0xd0, 0xd0, 0xd0);
const light_gray3 = nk.rgb(0xbf, 0xbf, 0xbf);
const light_gray4 = nk.rgb(0xaf, 0xaf, 0xaf);
// I color all elements not used in the ui an ugly red color.
// This will let me easily see when I need to update this color table.
const ugly_red = nk.rgb(0xff, 0x00, 0x00);
var colors: [c.NK_COLOR_COUNT]nk.Color = undefined;
colors[c.NK_COLOR_TEXT] = black;
colors[c.NK_COLOR_WINDOW] = white;
colors[c.NK_COLOR_HEADER] = header_gray;
colors[c.NK_COLOR_BORDER] = border_gray;
colors[c.NK_COLOR_BUTTON] = light_gray1;
colors[c.NK_COLOR_BUTTON_HOVER] = light_gray2;
colors[c.NK_COLOR_BUTTON_ACTIVE] = light_gray4;
colors[c.NK_COLOR_TOGGLE] = light_gray1;
colors[c.NK_COLOR_TOGGLE_HOVER] = light_gray2;
colors[c.NK_COLOR_TOGGLE_CURSOR] = black;
colors[c.NK_COLOR_SELECT] = white;
colors[c.NK_COLOR_SELECT_ACTIVE] = light_gray4;
colors[c.NK_COLOR_SLIDER] = ugly_red;
colors[c.NK_COLOR_SLIDER_CURSOR] = ugly_red;
colors[c.NK_COLOR_SLIDER_CURSOR_HOVER] = ugly_red;
colors[c.NK_COLOR_SLIDER_CURSOR_ACTIVE] = ugly_red;
colors[c.NK_COLOR_PROPERTY] = ugly_red;
colors[c.NK_COLOR_EDIT] = light_gray1;
colors[c.NK_COLOR_EDIT_CURSOR] = ugly_red;
colors[c.NK_COLOR_COMBO] = light_gray1;
colors[c.NK_COLOR_CHART] = ugly_red;
colors[c.NK_COLOR_CHART_COLOR] = ugly_red;
colors[c.NK_COLOR_CHART_COLOR_HIGHLIGHT] = ugly_red;
colors[c.NK_COLOR_SCROLLBAR] = light_gray1;
colors[c.NK_COLOR_SCROLLBAR_CURSOR] = light_gray2;
colors[c.NK_COLOR_SCROLLBAR_CURSOR_HOVER] = light_gray3;
colors[c.NK_COLOR_SCROLLBAR_CURSOR_ACTIVE] = light_gray4;
colors[c.NK_COLOR_TAB_HEADER] = ugly_red;
c.nk_style_from_table(ctx, &colors);
ctx.style.edit.cursor_size = 1;
ctx.style.window.min_row_height_padding = 4;
}
// From this point on, we can report errors to the user. This is done
// with this 'Popups' struct.
var popups = Popups{ .allocator = allocator };
defer popups.deinit();
const exes = Executables.find(allocator) catch |err| blk: {
popups.err("Failed to find exes: {}", .{err});
break :blk Executables{ .arena = heap.ArenaAllocator.init(allocator) };
};
defer exes.deinit();
var settings = Settings{ .arena = heap.ArenaAllocator.init(allocator) };
defer settings.deinit();
var rom: ?Rom = null;
var selected: usize = 0;
while (true) {
timer.reset();
if (c.nkInput(ctx) == 0)
return;
const window_rect = nk.rect(0, 0, @intToFloat(f32, c.width), @intToFloat(f32, c.height));
if (nk.begin(ctx, "", window_rect, c.NK_WINDOW_NO_SCROLLBAR)) {
const group_height = groupHeight(ctx);
c.nk_layout_row_template_begin(ctx, group_height);
c.nk_layout_row_template_push_static(ctx, 300);
c.nk_layout_row_template_push_dynamic(ctx);
c.nk_layout_row_template_end(ctx);
selected = drawCommands(ctx, exes, &settings, selected);
if (nk.nonPaddedGroupBegin(ctx, "opt_and_actions", c.NK_WINDOW_NO_SCROLLBAR)) {
defer nk.nonPaddedGroupEnd(ctx);
const action_group_height =
ctx.style.window.padding.y * 2 +
ctx.style.window.spacing.y * 1 +
ctx.style.button.padding.y * 4 +
ctx.style.font.*.height * 2 +
groupOuterHeight(ctx);
c.nk_layout_row_template_begin(ctx, action_group_height);
c.nk_layout_row_template_push_static(ctx, 250);
c.nk_layout_row_template_push_dynamic(ctx);
c.nk_layout_row_template_push_dynamic(ctx);
c.nk_layout_row_template_end(ctx);
rom = drawActions(ctx, &popups, rom, exes, &settings);
drawInfo(ctx, rom);
noopGroup(ctx, "");
const options_group_height = group_height - (action_group_height +
ctx.style.window.spacing.y);
c.nk_layout_row_dynamic(ctx, options_group_height, 1);
drawOptions(ctx, &popups, exes, &settings, selected);
}
try drawPopups(ctx, &popups);
}
c.nk_end(ctx);
c.nkRender(ctx);
time.sleep(math.sub(u64, frame_time, timer.read()) catch 0);
}
}
pub fn noopGroup(ctx: *nk.Context, name: [*:0]const u8) void {
if (c.nk_group_begin(ctx, name, border_title_group) != 0) {
defer c.nk_group_end(ctx);
}
}
// +---------------------------+
// | Commands |
// +---------------------------+
// | +-+ +-------------------+ |
// | |^| | # tm35-rand-stats | |
// | +-+ | # tm35-rand-wild | |
// | +-+ | | |
// | |V| | | |
// | +-+ | | |
// | +-------------------+ |
// +---------------------------+
pub fn drawCommands(
ctx: *nk.Context,
exes: Executables,
settings: *Settings,
in_selected: usize,
) usize {
var tmp_buf: [128]u8 = undefined;
var selected = in_selected;
const layout = ctx.current.*.layout;
const min_height = layout.*.row.min_height;
const inner_height = groupHeight(ctx) - groupOuterHeight(ctx);
if (c.nk_group_begin(ctx, "Commands", border_title_group) == 0)
return selected;
defer c.nk_group_end(ctx);
c.nk_layout_row_template_begin(ctx, inner_height);
c.nk_layout_row_template_push_static(ctx, min_height);
c.nk_layout_row_template_push_dynamic(ctx);
c.nk_layout_row_template_end(ctx);
if (nk.nonPaddedGroupBegin(ctx, "command-buttons", c.NK_WINDOW_NO_SCROLLBAR)) {
defer nk.nonPaddedGroupEnd(ctx);
c.nk_layout_row_dynamic(ctx, 0, 1);
if (c.nk_button_symbol(ctx, c.NK_SYMBOL_TRIANGLE_UP) != 0 and
settings.commands.items.len != 0)
{
const before = selected -| 1;
mem.swap(
Settings.Command,
&settings.commands.items[before],
&settings.commands.items[selected],
);
selected = before;
}
if (c.nk_button_symbol(ctx, c.NK_SYMBOL_TRIANGLE_DOWN) != 0 and
settings.commands.items.len != 0)
{
const after = math.min(selected + 1, settings.commands.items.len - 1);
mem.swap(
Settings.Command,
&settings.commands.items[selected],
&settings.commands.items[after],
);
selected = after;
}
if (c.nk_button_symbol(ctx, c.NK_SYMBOL_MINUS) != 0 and
settings.commands.items.len != 0)
{
_ = settings.commands.orderedRemove(selected);
selected = math.min(selected, settings.commands.items.len -| 1);
}
}
var list_view: c.nk_list_view = undefined;
if (c.nk_list_view_begin(ctx, &list_view, "command-list", c.NK_WINDOW_BORDER, 0, @intCast(c_int, exes.commands.len + 1)) != 0) {
defer c.nk_list_view_end(&list_view);
for (settings.commands.items) |setting, i| {
const command = exes.commands[setting.executable];
if (i < @intCast(usize, list_view.begin))
continue;
if (@intCast(usize, list_view.end) <= i)
break;
c.nk_layout_row_dynamic(ctx, 0, 1);
const ui_name = toUserfriendly(&tmp_buf, command.name());
if (c.nk_select_text(ctx, ui_name.ptr, @intCast(c_int, ui_name.len), c.NK_TEXT_LEFT, @boolToInt(i == selected)) != 0)
selected = i;
}
c.nk_layout_row_dynamic(ctx, 0, 1);
var bounds: c.struct_nk_rect = undefined;
c.nkWidgetBounds(ctx, &bounds);
if (c.nkComboBeginText(ctx, "Add Command", @intCast(c_int, "Add Command".len), &nk.vec2(bounds.w, 500)) != 0) {
c.nk_layout_row_dynamic(ctx, 0, 1);
for (exes.commands) |command, i| {
const command_name = toUserfriendly(&tmp_buf, command.name());
if (c.nk_combo_item_text(ctx, command_name.ptr, @intCast(c_int, command_name.len), c.NK_TEXT_LEFT) != 0) {
// TODO: Handle memory error.
const setting = settings.commands.addOne(settings.arena.allocator()) catch unreachable;
setting.* = Settings.Command.init(settings.arena.allocator(), i, command) catch unreachable;
}
}
c.nk_combo_end(ctx);
}
}
return selected;
}
// +---------------------------+
// | Options |
// +---------------------------+
// | This is the help message |
// | # flag-a |
// | # flag-b |
// | drop-down | V| |
// | field-a | | |
// | field-b | | |
// | |
// +--------------------------+
pub fn drawOptions(
ctx: *nk.Context,
popups: *Popups,
exes: Executables,
settings: *Settings,
selected: usize,
) void {
var tmp_buf: [128]u8 = undefined;
if (c.nk_group_begin(ctx, "Options", border_title_group) == 0)
return;
defer c.nk_group_end(ctx);
if (exes.commands.len == 0)
return;
if (settings.commands.items.len == 0)
return;
const setting = settings.commands.items[selected];
const command = exes.commands[setting.executable];
var it = mem.split(u8, command.help, "\n");
while (it.next()) |line_notrim| {
const line = mem.trimRight(u8, line_notrim, " ");
if (line.len == 0)
continue;
if (mem.startsWith(u8, line, "Usage:"))
continue;
if (mem.startsWith(u8, line, "Options:"))
continue;
if (mem.startsWith(u8, line, " "))
continue;
if (mem.startsWith(u8, line, "\t"))
continue;
c.nk_layout_row_dynamic(ctx, 0, 1);
c.nk_text(ctx, line.ptr, @intCast(c_int, line.len), c.NK_TEXT_LEFT);
}
for (command.flags) |flag, i| {
const param = command.params[flag.i];
const help = param.id.msg;
var bounds: c.struct_nk_rect = undefined;
c.nkWidgetBounds(ctx, &bounds);
if (c.nkInputIsMouseHoveringRect(&ctx.input, &bounds) != 0)
c.nk_tooltip_text(ctx, help.ptr, @intCast(c_int, help.len));
const name = param.names.long orelse @as(*const [1]u8, ¶m.names.short.?)[0..];
const ui_name = toUserfriendly(&tmp_buf, name);
c.nk_layout_row_dynamic(ctx, 0, 1);
setting.flags[i] = c.nk_check_text(
ctx,
ui_name.ptr,
@intCast(c_int, ui_name.len),
@boolToInt(setting.flags[i]),
) != 0;
}
for (command.ints) |int, i| {
drawOptionsLayout(ctx, command.params[int.i]);
var buf: [32]u8 = undefined;
var formatted = fmt.bufPrint(&buf, "{}", .{setting.ints[i]}) catch unreachable;
var len = @intCast(c_int, formatted.len);
_ = c.nk_edit_string(
ctx,
c.NK_EDIT_SIMPLE,
formatted.ptr,
&len,
buf.len,
c.nk_filter_decimal,
);
setting.ints[i] = fmt.parseInt(usize, buf[0..@intCast(usize, len)], 10) catch
setting.ints[i];
}
for (command.floats) |float, i| {
drawOptionsLayout(ctx, command.params[float.i]);
var buf: [32]u8 = undefined;
var formatted = fmt.bufPrint(&buf, "{d:.2}", .{setting.floats[i]}) catch unreachable;
var len = @intCast(c_int, formatted.len);
_ = c.nk_edit_string(
ctx,
c.NK_EDIT_SIMPLE,
formatted.ptr,
&len,
buf.len,
c.nk_filter_float,
);
setting.floats[i] = fmt.parseFloat(f64, buf[0..@intCast(usize, len)]) catch
setting.floats[i];
}
for (command.enums) |enumeration, i| {
drawOptionsLayout(ctx, command.params[enumeration.i]);
const selected_enum = setting.enums[i];
const selected_name = enumeration.options[selected_enum];
const selected_ui = toUserfriendly(&tmp_buf, selected_name);
var bounds: c.struct_nk_rect = undefined;
c.nkWidgetBounds(ctx, &bounds);
if (c.nkComboBeginText(ctx, selected_ui.ptr, @intCast(c_int, selected_ui.len), &nk.vec2(bounds.w, 500)) != 0) {
c.nk_layout_row_dynamic(ctx, 0, 1);
for (enumeration.options) |option, option_i| {
const option_ui = toUserfriendly(&tmp_buf, option);
if (c.nk_combo_item_text(ctx, option_ui.ptr, @intCast(c_int, option_ui.len), c.NK_TEXT_LEFT) != 0)
setting.enums[i] = option_i;
}
c.nk_combo_end(ctx);
}
}
for (command.strings) |string, i| {
drawOptionsLayout(ctx, command.params[string.i]);
const value = &setting.strings[i];
var len = @intCast(c_int, value.items.len);
defer value.items.len = @intCast(usize, len);
value.ensureUnusedCapacity(settings.arena.allocator(), 10) catch {};
_ = c.nk_edit_string(
ctx,
c.NK_EDIT_SIMPLE,
value.items.ptr,
&len,
@intCast(c_int, value.capacity),
c.nk_filter_default,
);
}
for (command.files) |file, i| {
drawOptionsLayout(ctx, command.params[file.i]);
const value = &setting.files[i];
if (!nk.button(ctx, value.items))
continue;
var m_out_path: ?[*:0]u8 = null;
switch (c.NFD_SaveDialog("", null, &m_out_path)) {
c.NFD_ERROR => {
popups.err("Could not open file browser: {s}", .{c.NFD_GetError()});
continue;
},
c.NFD_CANCEL => continue,
c.NFD_OKAY => {
const out_path_z = m_out_path.?;
const out_path = mem.span(out_path_z);
defer std.c.free(out_path_z);
value.ensureTotalCapacity(settings.arena.allocator(), out_path.len) catch {};
value.shrinkRetainingCapacity(0);
value.appendSliceAssumeCapacity(out_path);
},
else => unreachable,
}
}
for (command.multi_strings) |multi, i| {
const param = command.params[multi.i];
var bounds: c.struct_nk_rect = undefined;
c.nkWidgetBounds(ctx, &bounds);
if (c.nkInputIsMouseHoveringRect(&ctx.input, &bounds) != 0)
c.nk_tooltip_text(ctx, param.id.msg.ptr, @intCast(c_int, param.id.msg.len));
const name = param.names.long orelse @as(*const [1]u8, ¶m.names.short.?)[0..];
const ui_name = toUserfriendly(&tmp_buf, name);
c.nk_text(ctx, ui_name.ptr, @intCast(c_int, ui_name.len), c.NK_TEXT_LEFT);
c.nk_layout_row_dynamic(ctx, 120, 1);
const value = &setting.multi_strings[i];
var len = @intCast(c_int, value.items.len);
defer value.items.len = @intCast(usize, len);
value.ensureUnusedCapacity(settings.arena.allocator(), 10) catch {};
_ = c.nk_edit_string(
ctx,
c.NK_EDIT_SIMPLE | c.NK_EDIT_MULTILINE,
value.items.ptr,
&len,
@intCast(c_int, value.capacity),
c.nk_filter_default,
);
}
}
pub fn drawOptionsLayout(ctx: *nk.Context, param: clap.Param(clap.Help)) void {
const width = 185;
c.nk_layout_row_template_begin(ctx, 0);
c.nk_layout_row_template_push_static(ctx, width);
c.nk_layout_row_template_push_dynamic(ctx);
c.nk_layout_row_template_end(ctx);
var bounds: c.struct_nk_rect = undefined;
c.nkWidgetBounds(ctx, &bounds);
if (c.nkInputIsMouseHoveringRect(&ctx.input, &bounds) != 0)
c.nk_tooltip_text(ctx, param.id.msg.ptr, @intCast(c_int, param.id.msg.len));
const name = param.names.long orelse @as(*const [1]u8, ¶m.names.short.?)[0..];
var tmp_buf: [128]u8 = undefined;
const ui_name = toUserfriendly(&tmp_buf, name);
c.nk_text(ctx, ui_name.ptr, @intCast(c_int, ui_name.len), c.NK_TEXT_LEFT);
}
pub const Rom = struct {
path: util.Path,
info: util.Path,
};
// +-------------------------------------+
// | Actions |
// +-------------------------------------+
// | +---------------+ +---------------+ |
// | | Open Rom | | Randomize | |
// | +---------------+ +---------------+ |
// | +---------------+ +---------------+ |
// | | Load Settings | | Save Settings | |
// | +---------------+ +---------------+ |
// +-------------------------------------+
pub fn drawActions(
ctx: *nk.Context,
popups: *Popups,
in_rom: ?Rom,
exes: Executables,
settings: *Settings,
) ?Rom {
var rom = in_rom;
if (c.nk_group_begin(ctx, "Actions", border_title_group) == 0)
return rom;
defer c.nk_group_end(ctx);
var m_file_browser_kind: ?enum {
load_rom,
randomize,
load_settings,
save_settings,
} = null;
c.nk_layout_row_dynamic(ctx, 0, 2);
if (nk.button(ctx, "Open rom"))
m_file_browser_kind = .load_rom;
if (nk.buttonActivatable(ctx, "Randomize", rom != null))
m_file_browser_kind = .randomize;
if (nk.button(ctx, "Load settings"))
m_file_browser_kind = .load_settings;
if (nk.button(ctx, "Save settings"))
m_file_browser_kind = .save_settings;
const file_browser_kind = m_file_browser_kind orelse return rom;
var m_out_path: ?[*:0]u8 = null;
const dialog_result = switch (file_browser_kind) {
.save_settings => c.NFD_SaveDialog(null, null, &m_out_path),
.load_settings => c.NFD_OpenDialog(null, null, &m_out_path),
.load_rom => c.NFD_OpenDialog("gb,gba,nds", null, &m_out_path),
.randomize => blk: {
const in_rom_path = in_rom.?.path.constSlice();
const dirname = path.dirname(in_rom_path) orelse ".";
const ext = path.extension(in_rom_path);
const in_name = util.path.basenameNoExt(in_rom_path);
var default_path = util.Path{ .buffer = undefined };
default_path.appendSlice(dirname) catch {};
default_path.appendSlice(path.sep_str) catch {};
default_path.appendSlice(in_name) catch {};
default_path.appendSlice("-randomized") catch {};
default_path.appendSlice(ext) catch {};
default_path.append(0) catch {};
const default = default_path.slice();
// Ensure we are null terminated even if the above fails.
default[default.len - 1] = 0;
break :blk c.NFD_SaveDialog("gb,gba,nds", default.ptr, &m_out_path);
},
};
const selected_path = switch (dialog_result) {
c.NFD_ERROR => {
popups.err("Could not open file browser: {s}", .{c.NFD_GetError()});
return rom;
},
c.NFD_CANCEL => return rom,
c.NFD_OKAY => blk: {
const out_path = m_out_path.?;
defer std.c.free(out_path);
break :blk util.Path.fromSlice(mem.span(out_path)) catch {
popups.err("File name '{s}' is too long", .{out_path});
return rom;
};
},
else => unreachable,
};
const selected_path_slice = selected_path.constSlice();
switch (file_browser_kind) {
.load_rom => {
var buf: [1024 * 40]u8 = undefined;
var fba = heap.FixedBufferAllocator.init(&buf);
const result = std.ChildProcess.exec(.{
.allocator = fba.allocator(),
.argv = &[_][]const u8{
exes.identify.constSlice(),
selected_path_slice,
},
}) catch |err| {
popups.err("Failed to identify {s}: {}", .{ selected_path_slice, err });
rom = null;
return rom;
};
const output = util.Path.fromSlice(result.stdout);
if (result.term != .Exited or result.term.Exited != 0) {
popups.err("{s} is not a Pokémon rom.\n{s}", .{ selected_path_slice, result.stderr });
rom = null;
} else if (output) |info| {
rom = Rom{
.path = selected_path,
.info = info,
};
} else |_| {
popups.err("Output too long", .{});
rom = null;
}
},
.randomize => {
// in should never be null here as the "Randomize" button is inactive when
// it is.
const in_path = rom.?.path.slice();
const out_path = selected_path.constSlice();
const stderr = std.io.getStdErr();
outputScript(stderr.writer(), exes, settings.*, in_path, out_path) catch {};
stderr.writeAll("\n") catch {};
randomize(exes, settings.*, in_path, out_path) catch |err| {
// TODO: Maybe print the stderr from the command we run in the randomizer
// function
popups.err("Failed to randomize '{s}': {}", .{ in_path, err });
return rom;
};
popups.info("Rom has been randomized!", .{});
},
.load_settings => {
const file = fs.cwd().openFile(selected_path.constSlice(), .{}) catch |err| {
popups.err("Could not open '{s}': {}", .{ selected_path.constSlice(), err });
return rom;
};
defer file.close();
const allocator = settings.arena.child_allocator;
const new_settings = Settings.load(allocator, exes, file.reader()) catch |err| {
popups.err("Failed to load from '{s}': {}", .{ selected_path.constSlice(), err });
return rom;
};
settings.deinit();
settings.* = new_settings;
},
.save_settings => {
const file = fs.cwd().createFile(selected_path.constSlice(), .{}) catch |err| {
popups.err("Could not open '{s}': {}", .{ selected_path.constSlice(), err });
return rom;
};
defer file.close();
settings.save(exes, file.writer()) catch |err| {
popups.err("Failed to write to '{s}': {}", .{ selected_path.constSlice(), err });
return rom;
};
},
}
return rom;
}
pub fn drawInfo(ctx: *nk.Context, m_rom: ?Rom) void {
if (c.nk_group_begin(ctx, "Info", border_title_group) == 0)
return;
defer c.nk_group_end(ctx);
const info = if (m_rom) |*rom| rom.info.constSlice() else "No rom has been opened yet.";
var it = mem.split(u8, info, "\n");
while (it.next()) |line_notrim| {
const line = mem.trimRight(u8, line_notrim, " ");
if (line.len == 0)
continue;
c.nk_layout_row_dynamic(ctx, 0, 1);
c.nk_text(ctx, line.ptr, @intCast(c_int, line.len), c.NK_TEXT_LEFT);
}
}
// +-------------------+
// | Error |
// +-------------------+
// | This is an error |
// | +------+ |
// | | Ok | |
// | +------+ |
// +-------------------+
pub fn drawPopups(ctx: *nk.Context, popups: *Popups) !void {
const layout = ctx.current.*.layout;
const min_height = layout.*.row.min_height;
const w: f32 = 350;
const h: f32 = 150;
const x = (@intToFloat(f32, c.width) / 2) - (w / 2);
const y = (@intToFloat(f32, c.height) / 2) - (h / 2);
const popup_rect = nk.rect(x, y, w, h);
const fatal_err = popups.fatalError();
const is_err = popups.errors.items.len != 0;
const is_info = popups.infos.items.len != 0;
if (fatal_err == null and !is_err and !is_info)
return;
const title = if (fatal_err) |_| "Fatal error!" else if (is_err) "Error" else "Info";
if (c.nkPopupBegin(ctx, c.NK_POPUP_STATIC, title, border_title_group, &popup_rect) == 0)
return;
defer c.nk_popup_end(ctx);
const text = fatal_err orelse if (is_err) popups.lastError() else popups.lastInfo();
const padding_height = groupOuterHeight(ctx);
const buttons_height = ctx.style.window.spacing.y + min_height;
const text_height = h - (padding_height + buttons_height);
c.nk_layout_row_dynamic(ctx, text_height, 1);
c.nk_text_wrap(ctx, text.ptr, @intCast(c_int, text.len));
switch (nk.buttons(ctx, .right, nk.buttonWidth(ctx, "Quit"), 0, &[_]nk.Button{
nk.Button{ .text = if (fatal_err) |_| "Quit" else "Ok" },
})) {
0 => {
if (fatal_err) |_|
return error.FatalError;
if (is_err) {
popups.allocator.free(popups.errors.pop());
c.nk_popup_close(ctx);
}
if (is_info) {
popups.allocator.free(popups.infos.pop());
c.nk_popup_close(ctx);
}
},
else => {},
}
}
/// The structure that keeps track of errors that need to be reported as popups to the user.
/// If an error occurs, it should be appended with 'popups.err("error str {}", arg1, arg2...)'.
/// It is also possible to report a fatal error with
/// 'popups.fatal("error str {}", arg1, arg2...)'. A fatal error means, that the only way to
/// recover is to exit. This error is reported to the user, after which the only option they
/// have is to quit the program. Finally, we can also just inform the user of something with
/// 'popups.info("info str {}", arg1, arg2...)'.
const Popups = struct {
allocator: mem.Allocator,
fatal_error: [127:0]u8 = ("\x00" ** 127).*,
errors: std.ArrayListUnmanaged([]const u8) = std.ArrayListUnmanaged([]const u8){},
infos: std.ArrayListUnmanaged([]const u8) = std.ArrayListUnmanaged([]const u8){},
fn err(popups: *Popups, comptime format: []const u8, args: anytype) void {
popups.append(&popups.errors, format, args);
}
fn lastError(popups: *Popups) []const u8 {
return popups.errors.items[popups.errors.items.len - 1];
}
fn info(popups: *Popups, comptime format: []const u8, args: anytype) void {
popups.append(&popups.infos, format, args);
}
fn lastInfo(popups: *Popups) []const u8 {
return popups.infos.items[popups.infos.items.len - 1];
}
fn append(
popups: *Popups,
list: *std.ArrayListUnmanaged([]const u8),
comptime format: []const u8,
args: anytype,
) void {
const msg = fmt.allocPrint(popups.allocator, format, args) catch {
return popups.fatal("Allocation failed", .{});
};
list.append(popups.allocator, msg) catch {
popups.allocator.free(msg);
return popups.fatal("Allocation failed", .{});
};
}
fn fatal(popups: *Popups, comptime format: []const u8, args: anytype) void {
_ = fmt.bufPrint(&popups.fatal_error, format ++ "\x00", args) catch return;
}
fn fatalError(popups: *const Popups) ?[]const u8 {
const res = mem.sliceTo(&popups.fatal_error, 0);
if (res.len == 0)
return null;
return res;
}
fn deinit(popups: *Popups) void {
for (popups.errors.items) |e|
popups.allocator.free(e);
for (popups.infos.items) |i|
popups.allocator.free(i);
popups.errors.deinit(popups.allocator);
popups.infos.deinit(popups.allocator);
}
};
fn groupOuterHeight(ctx: *const nk.Context) f32 {
return headerHeight(ctx) + (ctx.style.window.group_padding.y * 2) + ctx.style.window.spacing.y;
}
fn groupHeight(ctx: *nk.Context) f32 {
var total_space: c.struct_nk_rect = undefined;
c.nkWindowGetContentRegion(ctx, &total_space);
return total_space.h - ctx.style.window.padding.y * 2;
}
fn headerHeight(ctx: *const nk.Context) f32 {
return ctx.style.font.*.height +
(ctx.style.window.header.padding.y * 2) +
(ctx.style.window.header.label_padding.y * 2) + 1;
}
fn randomize(exes: Executables, settings: Settings, in: []const u8, out: []const u8) !void {
var buf: [1024 * 40]u8 = undefined;
var fba = heap.FixedBufferAllocator.init(&buf);
const term = switch (builtin.target.os.tag) {
.linux => blk: {
var sh = std.ChildProcess.init(&[_][]const u8{ "sh", "-e" }, fba.allocator());
sh.stdin_behavior = .Pipe;
try sh.spawn();
const writer = sh.stdin.?.writer();
try outputScript(writer, exes, settings, in, out);
sh.stdin.?.close();
sh.stdin = null;
break :blk try sh.wait();
},
.windows => blk: {
const cache_dir = try util.dir.folder(.cache);
const program_cache_dir = util.path.join(&[_][]const u8{
cache_dir.constSlice(),
Executables.program_name,
});
const script_file_name = util.path.join(&[_][]const u8{
program_cache_dir.constSlice(),
"tmp_scipt.bat",
});
{
try fs.cwd().makePath(program_cache_dir.constSlice());
const file = try fs.cwd().createFile(script_file_name.constSlice(), .{});
defer file.close();
try outputScript(file.writer(), exes, settings, in, out);
}
var cmd = std.ChildProcess.init(
&[_][]const u8{ "cmd", "/c", "call", script_file_name.constSlice() },
fba.allocator(),
);
break :blk try cmd.spawnAndWait();
},
else => @compileError("Unsupported os"),
};
switch (term) {
.Exited => |code| {
if (code != 0)
return error.CommandFailed;
},
.Signal, .Stopped, .Unknown => |_| {
return error.CommandFailed;
},
}
}
fn outputScript(
writer: anytype,
exes: Executables,
settings: Settings,
in: []const u8,
out: []const u8,
) !void {
const escapes = switch (builtin.target.os.tag) {
.linux => [_]escape.Escape{
.{ .escaped = "'\\''", .unescaped = "\'" },
},
.windows => [_]escape.Escape{
.{ .escaped = "\\\"", .unescaped = "\"" },
},
else => @compileError("Unsupported os"),
};
const quotes = switch (builtin.target.os.tag) {
.linux => "'",
.windows => "\"",
else => @compileError("Unsupported os"),
};
const esc = escape.generate(&escapes);
try writer.writeAll(quotes);
try esc.escapeWrite(writer, exes.load.constSlice());
try writer.writeAll(quotes ++ " " ++ quotes);
try esc.escapeWrite(writer, in);
try writer.writeAll(quotes ++ " | ");
for (settings.commands.items) |setting| {
const command = exes.commands[setting.executable];
try writer.writeAll(quotes);
try esc.escapeWrite(writer, command.path);
try writer.writeAll(quotes);
for (command.flags) |flag_param, i| {
const param = command.params[flag_param.i];
const prefix = if (param.names.long) |_| "--" else "-";
const name = param.names.long orelse @as(*const [1]u8, ¶m.names.short.?)[0..];
const flag = setting.flags[i];
if (!flag)
continue;
try writer.writeAll(" " ++ quotes);
try esc.escapePrint(writer, "{s}{s}", .{ prefix, name });
try writer.writeAll(quotes);
}
for (command.ints) |int_param, i| {
const param = command.params[int_param.i];
try writer.writeAll(" " ++ quotes);
try outputArgument(writer, esc, param, setting.ints[i], "");
try writer.writeAll(quotes);
}
for (command.floats) |float_param, i| {
const param = command.params[float_param.i];
try writer.writeAll(" " ++ quotes);
try outputArgument(writer, esc, param, setting.floats[i], "d");
try writer.writeAll(quotes);
}
for (command.enums) |enum_param, i| {
const param = command.params[enum_param.i];
const value = enum_param.options[setting.enums[i]];
try writer.writeAll(" " ++ quotes);
try outputArgument(writer, esc, param, value, "s");
try writer.writeAll(quotes);
}
for (command.strings) |string_param, i| {
const param = command.params[string_param.i];
try writer.writeAll(" " ++ quotes);
try outputArgument(writer, esc, param, setting.strings[i].items, "s");
try writer.writeAll(quotes);
}
for (command.files) |file_param, i| {
const param = command.params[file_param.i];
try writer.writeAll(" " ++ quotes);
try outputArgument(writer, esc, param, setting.files[i].items, "s");
try writer.writeAll(quotes);
}
for (command.multi_strings) |multi_param, i| {
const param = command.params[multi_param.i];
var it = mem.tokenize(u8, setting.multi_strings[i].items, "\r\n");
while (it.next()) |string| {
try writer.writeAll(" " ++ quotes);
try outputArgument(writer, esc, param, string, "s");
try writer.writeAll(quotes);
}
}
try writer.writeAll(" | ");
}
try writer.writeAll(quotes);
try esc.escapeWrite(writer, exes.apply.constSlice());
try writer.writeAll(quotes ++ " --replace --output " ++ quotes);
try esc.escapeWrite(writer, out);
try writer.writeAll(quotes ++ " " ++ quotes);
try esc.escapeWrite(writer, in);
try writer.writeAll(quotes);
try writer.writeAll("\n");
}
fn outputArgument(
writer: anytype,
escapes: anytype,
param: clap.Param(clap.Help),
value: anytype,
comptime value_fmt: []const u8,
) !void {
const prefix = if (param.names.long) |_| "--" else "-";
const name = param.names.long orelse @as(*const [1]u8, ¶m.names.short.?)[0..];
try escapes.escapePrint(writer, "{s}{s}={" ++ value_fmt ++ "}", .{
prefix,
name,
value,
});
}
fn toUserfriendly(human_out: []u8, programmer_in: []const u8) []u8 {
debug.assert(programmer_in.len <= human_out.len);
const suffixes = [_][]const u8{};
const prefixes = [_][]const u8{"tm35-"};
var trimmed = programmer_in;
for (prefixes) |prefix| {
if (mem.startsWith(u8, trimmed, prefix)) {
trimmed = trimmed[prefix.len..];
break;
}
}
for (suffixes) |suffix| {
if (mem.endsWith(u8, trimmed, suffix)) {
trimmed = trimmed[0 .. trimmed.len - suffix.len];
break;
}
}
trimmed = mem.trim(u8, trimmed[0..trimmed.len], " \t");
const result = human_out[0..trimmed.len];
mem.copy(u8, result, trimmed);
for (result) |*char| switch (char.*) {
'-', '_' => char.* = ' ',
else => {},
};
if (result.len != 0)
result[0] = std.ascii.toUpper(result[0]);
human_out[result.len] = 0;
return result;
}
const Settings = struct {
arena: heap.ArenaAllocator,
/// The options for all commands in `exes.commands`.
commands: std.ArrayListUnmanaged(Command) = std.ArrayListUnmanaged(Command){},
const Command = struct {
/// Which executable does these settings belong to
executable: usize,
/// For boolean options like `--enable` and `--enabled=true`
flags: []bool,
/// For interger options like `--int-option=10`.
ints: []usize,
/// For float options like `--float-option=10.0`.
floats: []f64,
/// For enum options like `--enum-option=option_a`. This is an index into
/// exe.commands.emums.options
enums: []usize,
/// For generic string options like `--string-option='this is a string'`
strings: []String,
/// For options taking a file path like `--file=/home/user/.config/test.conf`
files: []String,
/// For multi string options like `--exclude=a --exclude=b`. Stored as lines in a string
multi_strings: []String,
fn init(allocator: mem.Allocator, exe_i: usize, exe: Executables.Command) !Command {
var setting = Command{
.executable = exe_i,
.flags = try allocator.alloc(bool, exe.flags.len),
.ints = try allocator.alloc(usize, exe.ints.len),
.floats = try allocator.alloc(f64, exe.floats.len),
.enums = try allocator.alloc(usize, exe.enums.len),
.strings = try allocator.alloc(String, exe.strings.len),
.files = try allocator.alloc(String, exe.files.len),
.multi_strings = try allocator.alloc(String, exe.multi_strings.len),
};
mem.set(bool, setting.flags, false);
mem.set(String, setting.multi_strings, .{});
for (setting.ints) |*int, j|
int.* = exe.ints[j].default;
for (setting.floats) |*float, j|
float.* = exe.floats[j].default;
for (setting.enums) |*enumeration, j|
enumeration.* = exe.enums[j].default;
for (setting.strings) |*string, j| {
string.* = .{};
try string.appendSlice(allocator, exe.strings[j].default);
}
for (setting.files) |*string, j| {
string.* = .{};
try string.appendSlice(allocator, exe.files[j].default);
}
return setting;
}
};
const String = std.ArrayListUnmanaged(u8);
fn deinit(settings: Settings) void {
settings.arena.deinit();
}
const csv_escapes = escape.default_escapes ++ [_]escape.Escape{
.{ .escaped = "\\,", .unescaped = "," },
.{ .escaped = "\\n", .unescaped = "\n" },
};
const csv_escape = escape.generate(csv_escapes);
fn save(settings: Settings, exes: Executables, writer: anytype) !void {
for (settings.commands.items) |setting| {
const command = exes.commands[setting.executable];
try csv_escape.escapeWrite(writer, util.path.basenameNoExt(command.path));
for (command.flags) |flag, i| {
if (!setting.flags[i])
continue;
const param = command.params[flag.i];
const prefix = if (param.names.long) |_| "--" else "-";
const name = param.names.long orelse @as(*const [1]u8, ¶m.names.short.?)[0..];
try writer.writeAll(",");
try csv_escape.escapePrint(writer, "{s}{s}", .{ prefix, name });
}
for (command.ints) |int, i| {
const param = command.params[int.i];
try writer.writeAll(",");
try outputArgument(writer, csv_escape, param, setting.ints[i], "");
}
for (command.floats) |float, i| {
const param = command.params[float.i];
try writer.writeAll(",");
try outputArgument(writer, csv_escape, param, setting.floats[i], "d");
}
for (command.enums) |enumeration, i| {
const param = command.params[enumeration.i];
const value = enumeration.options[setting.enums[i]];
try writer.writeAll(",");
try outputArgument(writer, csv_escape, param, value, "s");
}
for (command.strings) |string, i| {
const param = command.params[string.i];
try writer.writeAll(",");
try outputArgument(writer, csv_escape, param, setting.strings[i].items, "s");
}
for (command.files) |file, i| {
const param = command.params[file.i];
try writer.writeAll(",");
try outputArgument(writer, csv_escape, param, setting.files[i].items, "s");
}
for (command.multi_strings) |multi, i| {
const param = command.params[multi.i];
const value = setting.multi_strings[i];
var it = mem.tokenize(u8, value.items, "\r\n");
while (it.next()) |string| {
try writer.writeAll(",");
try outputArgument(writer, csv_escape, param, string, "s");
}
}
try writer.writeAll("\n");
}
}
fn load(allocator: mem.Allocator, exes: Executables, reader: anytype) !Settings {
var arena_state = heap.ArenaAllocator.init(allocator);
const arena = arena_state.allocator();
errdefer arena_state.deinit();
var settings = std.ArrayList(Command).init(arena);
const EscapedSplitterArgIterator = struct {
separator: escape.EscapedSplitter,
buf: [mem.page_size]u8 = undefined,
pub fn next(iter: *@This()) ?[]const u8 {
const n = iter.separator.next() orelse return null;
var fba = std.heap.FixedBufferAllocator.init(&iter.buf);
return csv_escape.unescapeAlloc(fba.allocator(), n) catch null;
}
};
var fifo = util.io.Fifo(.Dynamic).init(allocator);
defer fifo.deinit();
while (try util.io.readLine(reader, &fifo)) |line| {
var separator = escape.splitEscaped(line, "\\", ",");
const name = separator.next() orelse continue;
const i = findCommandIndex(exes, name) orelse continue;
const command = exes.commands[i];
const setting = try settings.addOne();
setting.* = try Command.init(arena, i, command);
var args = EscapedSplitterArgIterator{ .separator = separator };
var streaming_clap = clap.StreamingClap(clap.Help, EscapedSplitterArgIterator){
.iter = &args,
.params = command.params,
};
while (try streaming_clap.next()) |arg| {
const param_i = util.indexOfPtr(clap.Param(clap.Help), command.params, arg.param);
if (findParam(command.flags, param_i)) |j| {
setting.flags[j] = true;
} else if (findParam(command.ints, param_i)) |j| {
setting.ints[j] = fmt.parseInt(usize, arg.value.?, 10) catch
command.ints[j].default;
} else if (findParam(command.floats, param_i)) |j| {
setting.floats[j] = fmt.parseFloat(f64, arg.value.?) catch
command.floats[j].default;
} else if (findParam(command.enums, param_i)) |j| {
for (command.enums[j].options) |option, option_i| {
if (mem.eql(u8, option, arg.value.?)) {
setting.enums[j] = option_i;
break;
}
} else setting.enums[j] = command.enums[j].default;
} else if (findParam(command.strings, param_i)) |j| {
const entry = &setting.strings[j];
entry.shrinkRetainingCapacity(0);
try entry.appendSlice(arena, arg.value.?);
} else if (findParam(command.files, param_i)) |j| {
const entry = &setting.files[j];
entry.shrinkRetainingCapacity(0);
try entry.appendSlice(arena, arg.value.?);
} else if (findParam(command.multi_strings, param_i)) |j| {
const entry = &setting.multi_strings[j];
try entry.appendSlice(arena, arg.value.?);
try entry.append(arena, '\n');
}
}
}
return Settings{
.arena = arena_state,
.commands = settings.moveToUnmanaged(),
};
}
fn findCommandIndex(e: Executables, name: []const u8) ?usize {
for (e.commands) |command, i| {
if (mem.eql(u8, command.name(), name))
return i;
}
return null;
}
fn findParam(items: anytype, i: usize) ?usize {
for (items) |item, j| {
if (item.i == i)
return j;
}
return null;
}
}; | src/gui/tm35-randomizer.zig |
const std = @import("std");
const testing = std.testing;
pub fn BinaryTree(comptime T: type) type {
return struct {
root: usize = 1,
items: []?Node,
count: usize = 0,
capacity: usize = 0,
allocator: *std.mem.Allocator,
const Self = @This();
pub const SearchResult = union(enum) {
found: Found,
not_found,
};
const Found = struct {
location: usize,
data: T,
};
const Node = struct {
left: usize,
right: usize,
location: usize,
data: T,
pub fn init(data: T, location: usize) Node {
return Node{
.left = 2 * location,
.right = (2 * location) + 1,
.location = location,
.data = data,
};
}
};
pub fn init(allocator: *std.mem.Allocator) Self {
return Self{
.items = &[_]?Node{},
.allocator = allocator,
};
}
pub fn deinit(self: *Self) void {
self.allocator.free(self.items.ptr[0..self.capacity]);
}
pub fn insert(self: *Self, data: T) !void {
var iter: usize = 1;
while (true) {
try self.ensureCapacity(iter);
if (self.items[iter]) |node| {
if (data == node.data) {
break;
} else if (data > node.data) {
iter = node.right;
} else {
iter = node.left;
}
} else {
self.items[iter] = Node.init(data, iter);
self.count += 1;
break;
}
}
}
pub fn map(self: *Self, func: fn (T) T) void {
for (self.items) |*item| {
if (item.*) |node| {
item.*.?.data = func(node.data);
}
}
}
// TODO: fix the links might need to shift some nodes around
pub fn delete(self: *Self, data: T) void {
switch (self.search(data)) {
.found => |result| {
var temp = self.items[result.location];
self.items[result.location] = null;
self.count -= 1;
},
.not_found => {},
}
}
pub fn search(self: *Self, data: T) SearchResult {
var iter: usize = 1;
while (true) {
if (iter > self.capacity) {
return .not_found;
}
if (self.items[iter]) |node| {
if (data == node.data) {
return .{ .found = .{ .location = node.location, .data = node.data } };
} else if (data > node.data) {
iter = node.right;
} else {
iter = node.left;
}
} else {
return .not_found;
}
}
}
fn ensureCapacity(self: *Self, new_capacity: usize) !void {
var better_capacity = self.capacity;
if (better_capacity >= new_capacity) return;
while (true) {
better_capacity += better_capacity / 2 + 8;
if (better_capacity >= new_capacity) break;
}
const new_memory = try self.allocator.realloc(self.items.ptr[0..self.capacity], better_capacity);
self.items.ptr = new_memory.ptr;
self.capacity = new_memory.len;
self.items.len = self.capacity;
}
};
}
test "BinaryTree.init" {
var tree = BinaryTree(i32).init(testing.allocator);
defer tree.deinit();
testing.expectEqual(@as(usize, 0), tree.count);
testing.expectEqual(@as(usize, 0), tree.items.len);
}
test "BinaryTree.insert" {
var tree = BinaryTree(i32).init(testing.allocator);
defer tree.deinit();
try tree.insert(3);
try tree.insert(7);
try tree.insert(2);
testing.expectEqual(@as(usize, 3), tree.count);
testing.expectEqual(@as(i32, 3), tree.items[tree.root].?.data);
testing.expectEqual(@as(i32, 7), tree.items[tree.items[tree.root].?.right].?.data);
testing.expectEqual(@as(i32, 2), tree.items[tree.items[tree.root].?.left].?.data);
}
test "BinaryTree.map" {
var tree = BinaryTree(i32).init(testing.allocator);
defer tree.deinit();
try tree.insert(3);
try tree.insert(7);
try tree.insert(2);
const addOne = struct {
fn function(data: i32) i32 {
return data + 1;
}
}.function;
tree.map(addOne);
testing.expectEqual(@as(usize, 3), tree.count);
testing.expectEqual(@as(i32, 4), tree.items[tree.root].?.data);
testing.expectEqual(@as(i32, 8), tree.items[tree.items[tree.root].?.right].?.data);
testing.expectEqual(@as(i32, 3), tree.items[tree.items[tree.root].?.left].?.data);
}
test "BinaryTree.search" {
var tree = BinaryTree(i32).init(testing.allocator);
defer tree.deinit();
const SearchResult = BinaryTree(i32).SearchResult;
testing.expectEqual(SearchResult.not_found, tree.search(7));
try tree.insert(5);
try tree.insert(7);
try tree.insert(4);
testing.expectEqual(SearchResult{
.found = .{
.data = 7,
.location = 3,
},
}, tree.search(7));
testing.expectEqual(SearchResult{
.found = .{
.data = 4,
.location = 2,
},
}, tree.search(4));
testing.expectEqual(SearchResult.not_found, tree.search(8));
}
test "BinaryTree.delete" {
var tree = BinaryTree(i32).init(testing.allocator);
defer tree.deinit();
try tree.insert(4);
try tree.insert(7);
try tree.insert(1);
try tree.insert(3);
try tree.insert(6);
testing.expectEqual(@as(usize, 5), tree.count);
tree.delete(3);
testing.expectEqual(@as(usize, 4), tree.count);
} | src/binary_tree.zig |
const std = @import("../std.zig");
const valgrind = std.valgrind;
pub const CallgrindClientRequest = extern enum {
DumpStats = valgrind.ToolBase("CT"),
ZeroStats,
ToggleCollect,
DumpStatsAt,
StartInstrumentation,
StopInstrumentation,
};
fn doCallgrindClientRequestExpr(default: usize, request: CallgrindClientRequest, a1: usize, a2: usize, a3: usize, a4: usize, a5: usize) usize {
return valgrind.doClientRequest(default, @intCast(usize, @enumToInt(request)), a1, a2, a3, a4, a5);
}
fn doCallgrindClientRequestStmt(request: CallgrindClientRequest, a1: usize, a2: usize, a3: usize, a4: usize, a5: usize) void {
_ = doCallgrindClientRequestExpr(0, request, a1, a2, a3, a4, a5);
}
/// Dump current state of cost centers, and zero them afterwards
pub fn dumpStats() void {
doCallgrindClientRequestStmt(.DumpStats, 0, 0, 0, 0, 0);
}
/// Dump current state of cost centers, and zero them afterwards.
/// The argument is appended to a string stating the reason which triggered
/// the dump. This string is written as a description field into the
/// profile data dump.
pub fn dumpStatsAt(pos_str: [*]u8) void {
doCallgrindClientRequestStmt(.DumpStatsAt, @ptrToInt(pos_str), 0, 0, 0, 0);
}
/// Zero cost centers
pub fn zeroStats() void {
doCallgrindClientRequestStmt(.ZeroStats, 0, 0, 0, 0, 0);
}
/// Toggles collection state.
/// The collection state specifies whether the happening of events
/// should be noted or if they are to be ignored. Events are noted
/// by increment of counters in a cost center
pub fn toggleCollect() void {
doCallgrindClientRequestStmt(.ToggleCollect, 0, 0, 0, 0, 0);
}
/// Start full callgrind instrumentation if not already switched on.
/// When cache simulation is done, it will flush the simulated cache;
/// this will lead to an artificial cache warmup phase afterwards with
/// cache misses which would not have happened in reality.
pub fn startInstrumentation() void {
doCallgrindClientRequestStmt(.StartInstrumentation, 0, 0, 0, 0, 0);
}
/// Stop full callgrind instrumentation if not already switched off.
/// This flushes Valgrinds translation cache, and does no additional
/// instrumentation afterwards, which effectivly will run at the same
/// speed as the "none" tool (ie. at minimal slowdown).
/// Use this to bypass Callgrind aggregation for uninteresting code parts.
/// To start Callgrind in this mode to ignore the setup phase, use
/// the option "--instr-atstart=no".
pub fn stopInstrumentation() void {
doCallgrindClientRequestStmt(.StopInstrumentation, 0, 0, 0, 0, 0);
} | lib/std/valgrind/callgrind.zig |
const std = @import("std");
const format = @import("format.zig");
const request = @import("request.zig");
pub const DiscordLogger = struct {
// Token format: "Bot <token>"
discord_auth: []const u8,
allocator: *std.mem.Allocator,
pub fn init(discord_auth: []const u8, allocator: *std.mem.Allocator) DiscordLogger {
if (!std.mem.startsWith(u8, discord_auth, "Bot ") and !std.mem.startsWith(u8, discord_auth, "User "))
@panic("The discord_auth property needs to start with 'Bot ' or 'User '.");
return .{ .discord_auth = discord_auth, .allocator = allocator };
}
pub fn sendMessage(self: DiscordLogger, channel_id: []const u8, comptime fmt: []const u8, args: anytype) !void {
const discord_token = std.os.getenv("DISCORD_TOKEN") orelse @panic("no token!");
var path: [0x100]u8 = undefined;
var req = try request.Https.init(.{
.allocator = self.allocator,
.pem = @embedFile("./certs/discord-com-chain.pem"),
.host = "discord.com",
.method = "POST",
.path = try std.fmt.bufPrint(&path, "/api/v6/channels/{}/messages", .{channel_id}),
});
defer req.deinit();
try req.client.writeHeaderValue("Accept", "application/json");
try req.client.writeHeaderValue("Content-Type", "application/json");
try req.client.writeHeaderValue("Authorization", discord_token);
const FmtWrapper = struct {
args: @TypeOf(args),
pub fn format(
wrapper: @This(),
comptime _: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
try writer.print(fmt, wrapper.args);
}
};
try req.printSend(
\\{{
\\ "content": "",
\\ "tts": false,
\\ "embed": {{
\\ "title": "{0}",
\\ "description": "{1}",
\\ "color": {2}
\\ }}
\\}}
,
.{
"New Log Line",
FmtWrapper{ .args = args },
@enumToInt(HexColor.blue),
},
);
_ = try req.expectSuccessStatus();
}
// Created because comptime fmt hits compiler TODO when put in a panic handler
pub fn sendSimpleMessage(self: DiscordLogger, channel_id: []const u8, msg: []const u8) !void {
const discord_token = std.os.getenv("DISCORD_TOKEN") orelse @panic("no token!");
var path: [0x100]u8 = undefined;
var req = try request.Https.init(.{
.allocator = self.allocator,
.pem = @embedFile("./certs/discord-com-chain.pem"),
.host = "discord.com",
.method = "POST",
.path = try std.fmt.bufPrint(&path, "/api/v6/channels/{}/messages", .{channel_id}),
});
defer req.deinit();
try req.client.writeHeaderValue("Accept", "application/json");
try req.client.writeHeaderValue("Content-Type", "application/json");
try req.client.writeHeaderValue("Authorization", discord_token);
try req.printSend(
\\{{
\\ "content": "",
\\ "tts": false,
\\ "embed": {{
\\ "title": "{0}",
\\ "description": "{1}",
\\ "color": {2}
\\ }}
\\}}
,
.{
"Important message from apanicking Zig application!",
msg,
@enumToInt(HexColor.blue),
},
);
_ = try req.expectSuccessStatus();
}
const HexColor = enum(u24) {
black = 0,
aqua = 0x1ABC9C,
green = 0x2ECC71,
blue = 0x3498DB,
red = 0xE74C3C,
gold = 0xF1C40F,
_,
pub fn init(raw: u32) HexColor {
return @intToEnum(HexColor, raw);
}
};
}; | src/discord_logger/discord_logger.zig |
const std = @import("std");
const dbgLog = @import("Log.zig").dbgLog;
const c_allocator = std.heap.c_allocator;
const tls_ = @import("TLS.zig");
const TLSConnection = tls_.TLSConnection;
const HTTPRequestHandler = @import("HTTPRequestHandler.zig");
const ObjectPool = @import("ObjectPool.zig").ObjectPool;
const MAX_HEADER_SIZE = std.math.min(8192, tls_.BUFFER_SIZE);
threadlocal var http_state_pool: ObjectPool(HTTPSState, 4096, null) = undefined;
pub fn statePoolSize() usize {
return http_state_pool.size();
}
// Per-connection state. Not persistent.
pub const HTTPSState = struct {
tls: TLSConnection,
request_response_state: ?HTTPRequestHandler.RequestResponseState = null,
// Used for keeping track of position in decrypted read buffer
read_buffer_index: u32 = 0,
pub fn threadLocalInit() void {
http_state_pool = ObjectPool(HTTPSState, 4096, null).init(c_allocator, c_allocator);
}
pub fn new() !usize {
const state = try http_state_pool.alloc();
errdefer http_state_pool.free(state);
state.* = HTTPSState{
.tls = TLSConnection{},
};
try state.*.tls.startConnection();
return @ptrToInt(state);
}
pub fn get(user_data: usize) !*HTTPSState {
if (user_data == 0) {
return error.NoUserData;
}
return @intToPtr(*HTTPSState, user_data);
}
pub fn free(self: *HTTPSState, conn: usize) void {
self.tls.deinit(conn);
http_state_pool.free(self);
}
pub fn free2(user_data: usize, conn: usize) void {
@intToPtr(*HTTPSState, user_data).free(conn);
}
pub fn read(self: *HTTPSState, conn: usize, encrypted_data: []const u8) !void {
const data_in = try self.tls.read(conn, encrypted_data);
if (data_in == 0) {
// SSL handshake, nothing to be done
return;
}
var decrypted_data = self.tls.read_buffer.?.data[self.read_buffer_index..std.math.min(tls_.BUFFER_SIZE, data_in)];
var this_header = decrypted_data;
while (this_header.len > 0) {
if (self.request_response_state == null) {
self.request_response_state = try HTTPRequestHandler.parseRequest(&this_header);
if (self.request_response_state != null) {
// Header fully received.
if (this_header.len == 0 or self.request_response_state.?.http_version == 0) {
// Nothing else in the read buffer, clear the read buffer.
self.tls.resetRead();
self.read_buffer_index = 0;
} else {
// Another header is in the read buffer
self.read_buffer_index += @intCast(u32, decrypted_data.len - this_header.len);
}
} else {
if (data_in >= tls_.BUFFER_SIZE and self.read_buffer_index > 0) {
// TLS read buffer is full, move the data to the start of the buffer to make space
std.mem.copy(u8, self.tls.read_buffer.?.data[0..decrypted_data.len], decrypted_data);
self.read_buffer_index = 0;
break;
}
// Don't call tls.resetRead. Data will be read again next time, hopefully with the full headers
if (data_in >= tls_.BUFFER_SIZE) {
// TODO: Support request headers bigger than 1 buffer?
return error.HeadersTooLarge;
}
break;
}
}
// Now sending response headers and data
if (!self.request_response_state.?.response_headers_sent and
tls_.BUFFER_SIZE - self.tls.write_tmp_buffer_len < MAX_HEADER_SIZE)
{
// Not enough buffer space to store biggest possible headers
// Do it later (in writeDone())
break;
}
try HTTPRequestHandler.sendResponse(conn, &self.tls, &self.request_response_state);
if (self.request_response_state != null) {
break;
}
}
try self.tls.flushWrite(conn);
}
pub fn writeDone(self: *HTTPSState, conn: usize, data: []const u8) !void {
try self.tls.writeDone(conn, data);
if (self.request_response_state != null) {
if (self.request_response_state.?.response_headers_sent or tls_.BUFFER_SIZE - self.tls.write_tmp_buffer_len < MAX_HEADER_SIZE) {
// Can send headers and data now.
try HTTPRequestHandler.sendResponse(conn, &self.tls, &self.request_response_state);
try self.tls.flushWrite(conn);
}
}
}
}; | src/HTTPSState.zig |
const std = @import("std");
const webgpu = @import("../../webgpu.zig");
const dummy = @import("./dummy.zig");
pub const Buffer = struct {
const vtable = webgpu.Buffer.VTable{
.destroy_fn = destroy,
.get_const_mapped_range_fn = getConstMappedRange,
.get_mapped_range_fn = getMappedRange,
.map_async_fn = mapAsync,
.unmap_fn = unmap,
};
super: webgpu.Buffer,
data: []align(16) u8,
pub fn create(device: *dummy.Device, descriptor: webgpu.BufferDescriptor) webgpu.Device.CreateBufferError!*Buffer {
var buffer = try device.allocator.create(Buffer);
errdefer device.allocator.destroy(buffer);
buffer.super = .{
.__vtable = &vtable,
.device = &device.super,
};
buffer.data = try device.allocator.allocAdvanced(u8, 16, descriptor.size, .at_least);
errdefer device.allocator.free(buffer.data);
return buffer;
}
fn destroy(super: *webgpu.Buffer) void {
var buffer = @fieldParentPtr(Buffer, "super", super);
buffer.device.allocator.free(buffer.data);
buffer.device.allocator.destroy(buffer);
}
fn getConstMappedRange(super: *webgpu.Buffer, offset: usize, size: usize) webgpu.Buffer.GetConstMappedRangeError![]align(16) const u8 {
var buffer = @fieldParentPtr(Buffer, "super", super);
if (offset + size > buffer.data.len) {
return error.Failed;
}
return buffer.data[offset..(offset + size)];
}
fn getMappedRange(super: *webgpu.Buffer, offset: usize, size: usize) webgpu.Buffer.GetMappedRangeError![]align(16) u8 {
var buffer = @fieldParentPtr(Buffer, "super", super);
if (offset + size > buffer.data.len) {
return error.Failed;
}
return buffer.data[offset..(offset + size)];
}
fn mapAsync(super: *webgpu.Buffer, mode: webgpu.MapMode, offset: usize, size: usize) webgpu.Buffer.MapAsyncError!void {
_ = super;
_ = mode;
_ = offset;
_ = size;
}
fn unmap(super: *webgpu.Buffer) webgpu.Buffer.UnmapError!void {
_ = super;
}
};
pub const QuerySet = struct {
const vtable = webgpu.QuerySet.VTable{
.destroy_fn = destroy,
};
super: webgpu.QuerySet,
pub fn create(device: *dummy.Device, descriptor: webgpu.QuerySetDescriptor) dummy.Device.CreateQuerySetError!*QuerySet {
_ = descriptor;
var query_set = try device.allocator.create(QuerySet);
errdefer device.allocator.destroy(query_set);
query_set.super = .{
.__vtable = &vtable,
.device = &device.super,
};
return query_set;
}
fn destroy(super: *webgpu.QuerySet) void {
var query_set = @fieldParentPtr(QuerySet, "super", super);
query_set.device.allocator.destroy(query_set);
}
};
pub const Sampler = struct {
const vtable = webgpu.Sampler.VTable{
.destroy_fn = destroy,
};
super: webgpu.Sampler,
pub fn create(device: *dummy.Device, descriptor: webgpu.SamplerDescriptor) webgpu.Device.CreateSamplerError!*Sampler {
_ = descriptor;
var sampler = try device.allocator.create(Sampler);
errdefer device.allocator.destroy(sampler);
sampler.super = .{
.__vtable = &vtable,
.device = &device.super,
};
return sampler;
}
fn destroy(super: *webgpu.Sampler) void {
var sampler = @fieldParentPtr(Sampler, "super", super);
sampler.device.allocator.destroy(sampler);
}
};
pub const SwapChain = struct {
const vtable = webgpu.SwapChain.VTable{
.destroy_fn = destroy,
.get_current_texture_view_fn = getCurrentTextureView,
};
super: webgpu.SwapChain,
texture_view: *TextureView,
pub fn create(device: *dummy.Device, descriptor: webgpu.SwapChainDescriptor) webgpu.Device.CreateSwapChainError!*SwapChain {
_ = descriptor;
var swap_chain = try device.allocator.create(SwapChain);
errdefer device.allocator.destroy(swap_chain);
swap_chain.super = .{
.__vtable = &vtable,
.device = &device.super,
};
swap_chain.texture_view = try TextureView.create(device, .{});
errdefer swap_chain.texture_view.super.destroy();
return swap_chain;
}
fn destroy(super: *webgpu.TextureView) void {
var swap_chain = @fieldParentPtr(SwapChain, "super", super);
swap_chain.texture_view.super.destroy();
swap_chain.device.allocator.destroy(swap_chain);
}
fn getCurrentTextureView(super: *webgpu.SwapChain) *webgpu.TextureView {
var swap_chain = @fieldParentPtr(SwapChain, "super", super);
return &swap_chain.texture_view.super;
}
};
pub const Texture = struct {
const vtable = webgpu.Texture.VTable{
.destroy_fn = destroy,
.create_view_fn = createView,
};
super: webgpu.Texture,
pub fn create(device: *dummy.Device, descriptor: webgpu.TextureDescriptor) webgpu.Device.CreateTextureError!*Texture {
_ = descriptor;
var texture = try device.allocator.create(Texture);
errdefer device.allocator.destroy(texture);
texture.super = .{
.__vtable = &vtable,
.device = &device.super,
};
return texture;
}
fn destroy(super: *webgpu.Texture) void {
var texture = @fieldParentPtr(Texture, "super", super);
texture.device.allocator.destroy(texture);
}
fn createView(super: *webgpu.Texture, descriptor: webgpu.TextureViewDescriptor) webgpu.Texture.CreateViewError!*webgpu.TextureView {
var texture = @fieldParentPtr(Texture, "super", super);
var texture_view = try TextureView.create(texture.device, texture, descriptor);
return &texture_view.super;
}
};
pub const TextureView = struct {
const vtable = webgpu.TextureView.VTable{
.destroy_fn = destroy,
};
super: webgpu.TextureView,
pub fn create(device: *dummy.Device, texture: *Texture, descriptor: webgpu.TextureViewDescriptor) webgpu.Texture.CreateViewError!*TextureView {
_ = descriptor;
var texture_view = try device.allocator.create(TextureView);
errdefer device.allocator.destroy(texture_view);
texture_view.super = .{
.__vtable = &vtable,
.device = &device.super,
.texture = &texture.super,
};
return texture_view;
}
fn destroy(super: *webgpu.TextureView) void {
var texture_view = @fieldParentPtr(TextureView, "super", super);
texture_view.device.allocator.destroy(texture_view);
}
}; | src/backends/dummy/resource.zig |
const std = @import("std");
const Sector = @import("sector.zig").Sector;
pub const Slot = packed struct {
// A save slot is comprised of 14 sectors, each 4 KiB, meaning the slot itself is 56 KiB.
comptime {
std.debug.assert(@sizeOf(Slot) == 0xE000);
}
sectors: [14]Sector,
/// The game seems to treat the slot as valid even if the counter differs between sectors.
pub fn getStatus(self: Slot) SlotStatus {
// Keeps track of whether any of the sectors had the magic number of 0x08012025. If not,
// the slot is considered empty.
var security_passed = false;
// A counter for how many times the game has been saved.
var counter: u32 = undefined;
// The corresponding bit of a sector's ID is flipped if the sector passes the security and
// checksum tests. If all bits are flipped, it means that all sectors are valid, and have
// an unique ID.
var sector_flag: u14 = 0;
for (self.sectors) |sector| {
if (sector.security == Sector.security_num) {
security_passed = true;
// TODO: Check what happens on cartidge when the id is higher than 13.
if (sector.id < 14 and sector.checksum == sector.getChecksum()) {
counter = sector.counter;
sector_flag |= @as(u14, 1) << @intCast(u4, sector.id);
}
}
}
if (security_passed) {
if (sector_flag == std.math.maxInt(u14))
return .{ .valid = counter };
return .invalid;
}
return .empty;
}
pub fn makeSimple() Slot {
var array = [1]u8{0} ** @sizeOf(Slot);
var id: u8 = 0;
while (id < 14) : (id += 1) {
const offset = 0x1000 * @as(u16, id);
// Fill the ID field.
array[offset + 0xFF4] = id;
// Set the security field.
std.mem.copy(u8, array[offset + 0xFF8 .. offset + 0xFFC], &.{ 0x25, 0x20, 0x01, 0x08 });
}
return @bitCast(Slot, array);
}
test "check simple slot" {
const slot = Slot.makeSimplest();
try std.testing.expectEqual(SlotStatus{ .valid = 0 }, slot.getStatus());
}
};
// TODO: Check for other possible status values.
const SlotStatus = union(enum) {
empty: void,
// A "valid" slot is defined as a slot that the game is willing to attempt to load. It does not
// mean the slot is an authentic save that can be attained without hacking, and running a valid
// slot can still crash the game.
//
// The u32 value represents the save counter of the slot.
valid: u32,
invalid: void,
}; | src/save/slot.zig |
const std = @import("std");
const http = @import("http_server.zig");
const httpc = @import("http_client.zig");
pub fn main() !void {
errdefer std.log.err("Fehler!", .{});
defer std.log.debug("main korrekt beendet.", .{});
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = &gpa.allocator;
//const allocator = std.testing.allocator;
var pages = http.Server.Pages.init(allocator);
defer pages.deinit();
_ = try pages.put("/index.html", &http.Server.PageAction{ .fktAlloc = index });
_ = try pages.put("/about.html", &http.Server.PageAction{ .fktAlloc = about });
_ = try pages.put("/shutdown.html", &http.Server.PageAction{ .fktAlloc = shutdown });
const server_addr = std.net.Address.initIp4(.{ 0, 0, 0, 0 }, 9000);
var server = try http.Server.init(allocator, pages, server_addr);
try server.run();
defer server.deinit();
std.time.sleep(std.time.ns_per_s * 1); // warten bis Server läuft
if (true) {
var client = try httpc.Client.init(allocator, "localhost", 9000);
defer client.deinit();
std.log.debug("client init done", .{});
if (true) {
const response = try client.requestAlloc("/index.html");
defer allocator.free(response);
const expected = "Hallo, das hier ist Index.html\r\nPage count = 1";
std.testing.expectEqualStrings(expected, response);
}
if (true) {
if (true) {
const response = try client.requestAlloc("/index.html");
defer allocator.free(response);
const expected = "Hallo, das hier ist Index.html\r\nPage count = 2";
std.testing.expectEqualStrings(expected, response);
}
}
if (true) {
if (true) {
const response = try client.requestAlloc("/shutdown.html");
defer allocator.free(response);
const expected = "Hallo, das hier ist Index.html\r\nPage count = 2";
std.testing.expectEqualStrings(expected, response);
}
}
}
std.log.info("zurück in Main", .{});
}
fn index(allocator: *std.mem.Allocator, ctx: *const http.Server.ConnectionContext) ?[]const u8 {
return std.fmt.allocPrint(allocator, "Hallo, das hier ist Index.html\r\nPage count = {}", .{ctx.server.page_cnt.get()}) catch {
return null;
};
}
fn about(allocator: *std.mem.Allocator, ctx: *const http.Server.ConnectionContext) ?[]const u8 {
return std.fmt.allocPrint(allocator, "Hallo, das hier ist About.html\r\nPage count = {}", .{ctx.server.page_cnt.get()}) catch {
return null;
};
}
fn shutdown(allocator: *std.mem.Allocator, ctx: *const http.Server.ConnectionContext) ?[]const u8 {
if (ctx.server.shutdown()) |_| {
return std.fmt.allocPrint(allocator, "Ok, HTML server shutdown now.", .{}) catch {
return null;
};
} else |err| {
return std.fmt.allocPrint(allocator, "can not signal HTML shutdown, err = {}\r\n", .{err}) catch {
return null;
};
}
}
test "single client to server" {
const allocator = std.testing.allocator;
var pages = http.Server.Pages.init(allocator);
defer pages.deinit();
_ = try pages.put("/index.html", &http.Server.PageAction{ .fktAlloc = index });
_ = try pages.put("/about.html", &http.Server.PageAction{ .fktAlloc = about });
_ = try pages.put("/shutdown.html", &http.Server.PageAction{ .fktAlloc = shutdown });
const server_addr = std.net.Address.initIp4(.{ 0, 0, 0, 0 }, 9000);
var server = try http.Server.init(allocator, pages, server_addr);
try server.run();
defer server.deinit();
std.time.sleep(std.time.ns_per_s * 1); // warten bis Server läuft
if (true) {
var client = try httpc.Client.init(allocator, "localhost", 9000);
defer client.deinit();
std.log.debug("client init done", .{});
if (true) {
const response = try client.requestAlloc("/index.html");
defer allocator.free(response);
const expected = "Hallo, das hier ist Index.html\r\nPage count = 1";
std.testing.expectEqualStrings(expected, response);
}
if (true) {
if (true) {
const response = try client.requestAlloc("/index.html");
defer allocator.free(response);
const expected = "Hallo, das hier ist Index.html\r\nPage count = 2";
std.testing.expectEqualStrings(expected, response);
}
}
if (true) {
if (true) {
const response = try client.requestAlloc("/shutdown.html");
defer allocator.free(response);
const expected = "Ok, HTML server shutdown now.";
std.testing.expectEqualStrings(expected, response);
}
}
}
} | src/main.zig |
const std = @import("std");
const assert = std.debug.assert;
pub fn main() !void {
var input_file = try std.fs.cwd().openFile("input/11.txt", .{});
defer input_file.close();
var buffered_reader = std.io.bufferedReader(input_file.reader());
const count = try simulate(buffered_reader.reader());
std.debug.print("number of steps required: {}\n", .{count});
}
fn simulate(reader: anytype) !u64 {
var buf: [1024]u8 = undefined;
var grid_buf = try std.BoundedArray(u8, 100).init(0);
while (try reader.readUntilDelimiterOrEof(&buf, '\n')) |line| {
for (line) |c| try grid_buf.append(c - '0');
}
const grid = grid_buf.slice();
const width = 10;
var step: u64 = 0;
while (!std.mem.allEqual(u8, grid, 0)) : (step += 1) {
for (grid) |*x| x.* += 1;
while (std.mem.max(u8, grid) > 9) {
for (grid) |*x, i| {
if (x.* > 9) {
x.* = 0;
const has_north = i >= width;
const has_south = i < grid.len - width;
const has_west = i % width >= 1;
const has_east = i % width < width - 1;
// North
if (has_north and grid[i - width] != 0) grid[i - width] += 1;
// North west
if (has_north and has_west and grid[i - width - 1] != 0) grid[i - width - 1] += 1;
// North east
if (has_north and has_east and grid[i - width + 1] != 0) grid[i - width + 1] += 1;
// South
if (has_south and grid[i + width] != 0) grid[i + width] += 1;
// South west
if (has_south and has_west and grid[i + width - 1] != 0) grid[i + width - 1] += 1;
// South east
if (has_south and has_east and grid[i + width + 1] != 0) grid[i + width + 1] += 1;
// West
if (has_west and grid[i - 1] != 0) grid[i - 1] += 1;
// East
if (has_east and grid[i + 1] != 0) grid[i + 1] += 1;
}
}
}
}
return step;
}
test "example 1" {
const text =
\\5483143223
\\2745854711
\\5264556173
\\6141336146
\\6357385478
\\4167524645
\\2176841721
\\6882881134
\\4846848554
\\5283751526
;
var fbs = std.io.fixedBufferStream(text);
const count = try simulate(fbs.reader());
try std.testing.expectEqual(@as(u64, 195), count);
} | src/11_2.zig |
const std = @import("std");
const util = @import("util.zig");
const data = @embedFile("../data/day11.txt");
const Input = struct {
energy: [10][10]u8 = undefined,
pub fn init(input_text: []const u8, allocator: std.mem.Allocator) !@This() {
_ = allocator;
var input = Input{};
errdefer input.deinit();
var lines = std.mem.tokenize(u8, input_text, "\r\n");
var y: usize = 0;
while (lines.next()) |line| : (y += 1) {
for (line) |c, x| {
input.energy[y][x] = c - '0';
}
}
return input;
}
pub fn deinit(self: @This()) void {
_ = self;
}
};
const Coord2 = struct {
x: usize,
y: usize,
};
const Offset = struct {
x: isize,
y: isize,
};
pub fn flash(energy: *[10][10]u8, coord: Coord2, flashers: *std.BoundedArray(Coord2, 100), flashed: *std.StaticBitSet(100)) void {
assert(coord.x < 10 and coord.y < 10);
const offsets = [8]Offset{
Offset{ .x = -1, .y = -1 },
Offset{ .x = 0, .y = -1 },
Offset{ .x = 1, .y = -1 },
Offset{ .x = -1, .y = 0 },
Offset{ .x = 1, .y = 0 },
Offset{ .x = -1, .y = 1 },
Offset{ .x = 0, .y = 1 },
Offset{ .x = 1, .y = 1 },
};
for (offsets) |offset| {
const cx: isize = @intCast(isize, coord.x) + offset.x;
const cy: isize = @intCast(isize, coord.y) + offset.y;
if (cx < 0 or cx >= 10 or cy < 0 or cy >= 10) {
continue; // out of bounds
}
const c = Coord2{ .x = @intCast(usize, cx), .y = @intCast(usize, cy) };
if (flashed.isSet(10 * c.y + c.x)) {
continue; // already flashed this step
}
energy[c.y][c.x] += 1;
if (energy[c.y][c.x] > 9) {
flashers.append(Coord2{ .x = c.x, .y = c.y }) catch unreachable;
flashed.set(10 * c.y + c.x);
}
}
}
fn part1(input: Input) i64 {
var energy = input.energy;
var flashers = std.BoundedArray(Coord2, 100).init(0) catch unreachable;
var step: usize = 0;
var flash_count: i64 = 0;
while (step < 100) : (step += 1) {
assert(flashers.len == 0);
var flashed = std.StaticBitSet(100).initEmpty();
// increase energy of all cells & track any that flash
for (energy) |*row, y| {
for (row) |*e, x| {
e.* += 1;
if (e.* > 9) {
flashers.append(Coord2{ .x = x, .y = y }) catch unreachable;
assert(!flashed.isSet(10 * y + x));
flashed.set(10 * y + x);
}
}
}
// process flashes
while (flashers.len > 0) {
const center = flashers.pop();
flash(&energy, center, &flashers, &flashed);
}
// Anything that flashed this step gets its energy reset to zero
for (energy) |*row, y| {
for (row) |*e, x| {
if (flashed.isSet(10 * y + x)) {
assert(e.* > 9);
e.* = 0;
flash_count += 1;
} else {
assert(e.* <= 9);
}
}
}
}
return flash_count;
}
fn part2(input: Input) i64 {
var energy = input.energy; // TODO: is this a copy?
var flashers = std.BoundedArray(Coord2, 100).init(0) catch unreachable;
var step: i64 = 0;
while (true) : (step += 1) {
assert(flashers.len == 0);
var flashed = std.StaticBitSet(100).initEmpty();
// increase energy of all cells & track any that flash
for (energy) |*row, y| {
for (row) |*e, x| {
assert(e.* <= 9);
e.* += 1;
if (e.* > 9) {
flashers.append(Coord2{ .x = x, .y = y }) catch unreachable;
assert(!flashed.isSet(10 * y + x));
flashed.set(10 * y + x);
}
}
}
// process flashes
while (flashers.len > 0) {
const center = flashers.pop();
flash(&energy, center, &flashers, &flashed);
}
// Anything that flashed this step gets its energy reset to zero
var flash_count: i64 = 0;
for (energy) |*row, y| {
for (row) |*e, x| {
if (flashed.isSet(10 * y + x)) {
assert(e.* > 9);
e.* = 0;
flash_count += 1;
} else {
assert(e.* <= 9);
}
}
}
if (flash_count == 100)
return step + 1;
}
unreachable;
}
const test_data =
\\5483143223
\\2745854711
\\5264556173
\\6141336146
\\6357385478
\\4167524645
\\2176841721
\\6882881134
\\4846848554
\\5283751526
;
const part1_test_solution: ?i64 = 1656;
const part1_solution: ?i64 = 1673;
const part2_test_solution: ?i64 = 195;
const part2_solution: ?i64 = 279;
// Just boilerplate below here, nothing to see
fn testPart1() !void {
var test_input = try Input.init(test_data, std.testing.allocator);
defer test_input.deinit();
if (part1_test_solution) |solution| {
try std.testing.expectEqual(solution, part1(test_input));
}
var timer = try std.time.Timer.start();
var input = try Input.init(data, std.testing.allocator);
defer input.deinit();
if (part1_solution) |solution| {
try std.testing.expectEqual(solution, part1(input));
print("part1 took {d:9.3}ms\n", .{@intToFloat(f64, timer.lap()) / 1000000.0});
}
}
fn testPart2() !void {
var test_input = try Input.init(test_data, std.testing.allocator);
defer test_input.deinit();
if (part2_test_solution) |solution| {
try std.testing.expectEqual(solution, part2(test_input));
}
var timer = try std.time.Timer.start();
var input = try Input.init(data, std.testing.allocator);
defer input.deinit();
if (part2_solution) |solution| {
try std.testing.expectEqual(solution, part2(input));
print("part2 took {d:9.3}ms\n", .{@intToFloat(f64, timer.lap()) / 1000000.0});
}
}
pub fn main() !void {
try testPart1();
try testPart2();
}
test "part1" {
try testPart1();
}
test "part2" {
try testPart2();
}
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const parseInt = std.fmt.parseInt;
const min = std.math.min;
const max = std.math.max;
const print = std.debug.print;
const expect = std.testing.expect;
const assert = std.debug.assert; | src/day11.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const List = std.ArrayList;
const Map = std.AutoHashMap;
const StrMap = std.StringHashMap;
const BitSet = std.DynamicBitSet;
const Str = []const u8;
const util = @import("util.zig");
const gpa = util.gpa;
const data = @embedFile("../data/day03.txt");
const int = i64;
const Rec = struct {
value: int,
dir: Kind,
};
const Kind = enum {
down,
up,
forward,
};
pub fn main() !void {
var counts: [12]u32 = std.mem.zeroes([12]u32);
var recs = blk: {
var list = List(u12).init(gpa);
list.ensureTotalCapacity(1000) catch unreachable;
var lines = tokenize(u8, data, "\n\r");
while (lines.next()) |line| {
if (line.len == 0) {continue;}
const value = try parseInt(u12, line, 2);
list.append(value) catch unreachable;
var i: u12 = 1;
var x: usize = 0;
while (i != 0) : (i = i << 1) {
counts[x] += @boolToInt(value & i != 0);
x += 1;
}
}
break :blk list.toOwnedSlice();
};
var gamma: u12 = 0;
{
var i: u12 = 1;
var x: usize = 0;
while (i != 0) : (i = i << 1) {
if (counts[x] * 2 >= recs.len) {
gamma |= i;
}
x += 1;
}
}
const part1 = @as(usize, gamma) * @as(usize, ~gamma);
print("part1={}\n", .{part1});
assert(part1 == 4103154);
const gamma_high_bit = gamma & (1<<11);
bench(recs, part2FilteredLists, gamma_high_bit, "filtered lists");
bench(recs, part2InPlaceFilter, gamma_high_bit, "in place filtering");
bench(recs, part2Sorting, gamma_high_bit, "sorting");
bench(recs, part2CountingSort, gamma_high_bit, "counting sort");
}
fn bench(recs: []const u12, comptime benchmark: anytype, gamma_high_bit: u12, name: []const u8) void {
const scratch = gpa.alloc(u12, recs.len) catch unreachable;
defer gpa.free(scratch);
var i: usize = 0;
var best_time: usize = std.math.maxInt(usize);
var total_time: usize = 0;
const num_runs = 10000;
while (i < num_runs) : (i += 1) {
@memcpy(@ptrCast([*]u8, scratch.ptr), @ptrCast([*]const u8, recs.ptr), recs.len * @sizeOf(u12));
std.mem.doNotOptimizeAway(scratch.ptr);
const timer = std.time.Timer.start() catch unreachable;
@call(.{}, benchmark, .{scratch, gamma_high_bit});
asm volatile ("" : : : "memory");
const lap_time = timer.read();
if (best_time > lap_time) best_time = lap_time;
total_time += lap_time;
}
print("min {} avg {} {s}\n", .{best_time, total_time / num_runs, name});
}
fn part2FilteredLists(recs: []const u12, gamma_high_bit: u12) void {
var oxygen_remain = List(u12).init(gpa);
var co2_remain = List(u12).init(gpa);
var next = List(u12).init(gpa);
defer oxygen_remain.deinit();
defer co2_remain.deinit();
defer next.deinit();
oxygen_remain.ensureTotalCapacity(recs.len) catch unreachable;
co2_remain.ensureTotalCapacity(recs.len) catch unreachable;
next.ensureTotalCapacity(recs.len) catch unreachable;
for (recs) |item| {
if (item & (1<<11) == gamma_high_bit) {
oxygen_remain.appendAssumeCapacity(item);
} else {
co2_remain.appendAssumeCapacity(item);
}
}
{
var i: u12 = 1<<10;
while (oxygen_remain.items.len != 1) : (i = i >> 1) {
assert(i != 0);
const bit_target = gammaMask(oxygen_remain.items, i) & i;
for (oxygen_remain.items) |item| {
if (bit_target == item & i) {
next.appendAssumeCapacity(item);
}
}
var tmp = oxygen_remain;
oxygen_remain = next;
tmp.clearRetainingCapacity();
next = tmp;
}
}
const oxygen = oxygen_remain.items[0];
{
var mask: u12 = gamma_high_bit ^ (1<<11);
var i: u12 = 1<<10;
while (co2_remain.items.len != 1) : (i = i >> 1) {
assert(i != 0);
const bit_target = (~gammaMask(co2_remain.items, i)) & i;
mask |= bit_target;
for (co2_remain.items) |item| {
if (bit_target == item & i) {
next.appendAssumeCapacity(item);
}
}
//print("bit {x} co2 mask {x} {}/{}\n", .{i, mask, next.items.len, co2_remain.items.len});
var tmp = co2_remain;
co2_remain = next;
tmp.clearRetainingCapacity();
next = tmp;
}
}
const co2 = co2_remain.items[0];
const part2 = @as(usize, oxygen) * @as(usize, co2);
std.mem.doNotOptimizeAway(&part2);
// Don't use assert here because that could influence the optimizer
if (std.debug.runtime_safety and oxygen != 3399) @panic("Bad oxygen value");
if (std.debug.runtime_safety and co2 != 1249) @panic("Bad co2 value");
}
fn part2InPlaceFilter(recs: []const u12, gamma_high_bit: u12) void {
var last_oxy_match: u12 = 0;
var last_co2_match: u12 = 0;
var i: u12 = 1<<10;
var mask: u12 = 1<<11;
var oxy_target: u12 = gamma_high_bit;
var co2_target: u12 = gamma_high_bit ^ (1<<11);
while (true) : (i = i >> 1) {
const prev_mask = mask;
mask |= i;
const oxy_untarget = oxy_target | i;
const co2_untarget = co2_target | i;
var oxy_zero_count: usize = 0;
var oxy_one_count: usize = 0;
var co2_zero_count: usize = 0;
var co2_one_count: usize = 0;
for (recs) |it| {
oxy_zero_count += @boolToInt(it & mask == oxy_target);
co2_zero_count += @boolToInt(it & mask == co2_target);
if (it & prev_mask == oxy_target) last_oxy_match = it;
if (it & prev_mask == co2_target) last_co2_match = it;
oxy_one_count += @boolToInt(it & mask == oxy_untarget);
co2_one_count += @boolToInt(it & mask == co2_untarget);
}
oxy_target |= std.math.boolMask(u12, oxy_zero_count <= oxy_one_count) & i;
co2_target |= std.math.boolMask(u12, co2_zero_count > co2_one_count) & i;
const oxy_matches = if (oxy_zero_count <= oxy_one_count) oxy_one_count else oxy_zero_count;
const co2_matches = if (co2_zero_count > co2_one_count) co2_one_count else co2_zero_count;
//print("bit {x} co2 mask {x} {}/{}\n", .{i, co2_target, co2_matches, co2_zero_count + co2_one_count});
// we need to do at least one pass after all bits are set to record the last co2 zero correctly
if (@boolToInt(oxy_matches <= 1) & @boolToInt(co2_matches <= 1) != 0) break;
assert(i != 0);
}
const part2 = @as(usize, last_oxy_match) * @as(usize, last_co2_match);
std.mem.doNotOptimizeAway(&part2);
// Don't use assert here because that could influence the optimizer
if (std.debug.runtime_safety and last_oxy_match != 3399) @panic("Bad oxygen value");
if (std.debug.runtime_safety and last_co2_match != 1249) @panic("Bad co2 value");
}
const Divider = struct {
halfway_bit: u12,
idx: usize,
};
fn findSortedDivider(recs: []const u12, bit: u12, comptime sentinel_must_exist: bool) Divider {
var idx = recs.len/2;
var halfway_bit = recs[idx] & bit;
if (halfway_bit != 0) {
while (sentinel_must_exist or idx > 0) {
if (recs[idx-1] & bit == 0) break;
idx -= 1;
}
} else {
idx += 1;
while (sentinel_must_exist or idx < recs.len) {
if(recs[idx] & bit != 0) break;
idx += 1;
}
}
return .{
.halfway_bit = halfway_bit,
.idx = idx,
};
}
fn part2Sorting(recs: []u12, gamma_high_bit: u12) void {
_ = gamma_high_bit;
sort(u12, recs, {}, comptime asc(u12));
var oxy_min: usize = 0;
var oxy_max: usize = recs.len;
var co2_min: usize = 0;
var co2_max: usize = recs.len;
// First divider applies to both
{
const div = findSortedDivider(recs, 1<<11, true);
if (div.halfway_bit == 0) {
oxy_max = div.idx;
co2_min = div.idx;
} else {
co2_max = div.idx;
oxy_min = div.idx;
}
}
// Now do co2
{
var i: u12 = 1<<10;
while (co2_min + 1 != co2_max) : (i = i >> 1) {
assert(i != 0);
const div = findSortedDivider(recs[co2_min..co2_max], i, true);
if (div.halfway_bit != 0) {
co2_max = co2_min + div.idx;
} else {
co2_min = co2_min + div.idx;
}
}
}
// Then oxygen
{
var i: u12 = 1<<10;
while (oxy_min + 1 != oxy_max) : (i = i >> 1) {
assert(i != 0);
const div = findSortedDivider(recs[oxy_min..oxy_max], i, false);
if (div.halfway_bit != 0) {
oxy_min = oxy_min + div.idx;
} else {
oxy_max = oxy_min + div.idx;
}
}
}
const oxy = recs[oxy_min];
const co2 = recs[co2_min];
const part2 = @as(usize, oxy) * @as(usize, co2);
std.mem.doNotOptimizeAway(&part2);
// Don't use assert here because that could influence the optimizer
if (std.debug.runtime_safety and oxy != 3399) @panic("Bad oxygen value");
if (std.debug.runtime_safety and co2 != 1249) @panic("Bad co2 value");
}
fn part2CountingSort(recs: []u12, gamma_high_bit: u12) void {
_ = gamma_high_bit;
// Sort by making a bit set and then splatting it back out
{
var set_values = std.StaticBitSet(1<<12).initEmpty();
for (recs) |rec| {
set_values.set(rec);
}
var it = set_values.iterator(.{});
var i: usize = 0;
while (it.next()) |value| : (i += 1) {
recs[i] = @intCast(u12, value);
}
assert(i == recs.len);
}
var oxy_min: usize = 0;
var oxy_max: usize = recs.len;
var co2_min: usize = 0;
var co2_max: usize = recs.len;
// First divider applies to both
{
const div = findSortedDivider(recs, 1<<11, true);
if (div.halfway_bit == 0) {
oxy_max = div.idx;
co2_min = div.idx;
} else {
co2_max = div.idx;
oxy_min = div.idx;
}
}
// Now do co2
{
var i: u12 = 1<<10;
while (co2_min + 1 != co2_max) : (i = i >> 1) {
assert(i != 0);
const div = findSortedDivider(recs[co2_min..co2_max], i, true);
if (div.halfway_bit != 0) {
co2_max = co2_min + div.idx;
} else {
co2_min = co2_min + div.idx;
}
}
}
// Then oxygen
{
var i: u12 = 1<<10;
while (oxy_min + 1 != oxy_max) : (i = i >> 1) {
assert(i != 0);
const div = findSortedDivider(recs[oxy_min..oxy_max], i, false);
if (div.halfway_bit != 0) {
oxy_min = oxy_min + div.idx;
} else {
oxy_max = oxy_min + div.idx;
}
}
}
const oxy = recs[oxy_min];
const co2 = recs[co2_min];
const part2 = @as(usize, oxy) * @as(usize, co2);
std.mem.doNotOptimizeAway(&part2);
// Don't use assert here because that could influence the optimizer
if (std.debug.runtime_safety and oxy != 3399) @panic("Bad oxygen value");
if (std.debug.runtime_safety and co2 != 1249) @panic("Bad co2 value");
}
fn gammaMask(items: []const u12, bit: u12) u12 {
var count: usize = 0;
for (items) |it| {
count += @boolToInt(it & bit != 0);
}
return std.math.boolMask(u12, count * 2 >= items.len);
}
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const indexOf = std.mem.indexOfScalar;
const indexOfAny = std.mem.indexOfAny;
const indexOfStr = std.mem.indexOfPosLinear;
const lastIndexOf = std.mem.lastIndexOfScalar;
const lastIndexOfAny = std.mem.lastIndexOfAny;
const lastIndexOfStr = std.mem.lastIndexOfLinear;
const trim = std.mem.trim;
const sliceMin = std.mem.min;
const sliceMax = std.mem.max;
const eql = std.mem.eql;
const parseEnum = std.meta.stringToEnum;
const parseInt = std.fmt.parseInt;
const parseFloat = std.fmt.parseFloat;
const min = std.math.min;
const min3 = std.math.min3;
const max = std.math.max;
const max3 = std.math.max3;
const print = std.debug.print;
const assert = std.debug.assert;
const sort = std.sort.sort;
const asc = std.sort.asc;
const desc = std.sort.desc; | src/day03.zig |
const std = @import("std");
const interop = @import("../interop.zig");
const iup = @import("../iup.zig");
const Impl = @import("../impl.zig").Impl;
const CallbackHandler = @import("../callback_handler.zig").CallbackHandler;
const debug = std.debug;
const trait = std.meta.trait;
const Element = iup.Element;
const Handle = iup.Handle;
const Error = iup.Error;
const ChildrenIterator = iup.ChildrenIterator;
const Size = iup.Size;
const Margin = iup.Margin;
///
/// Creates a dialog element.
/// It manages user interaction with the interface elements.
/// For any interface element to be shown, it must be encapsulated in a dialog.
pub const Dialog = opaque {
pub const CLASS_NAME = "dialog";
pub const NATIVE_TYPE = iup.NativeType.Dialog;
const Self = @This();
///
/// FOCUS_CB: Called when the dialog or any of its children gets the focus, or
/// when another dialog or any control in another dialog gets the focus.
/// It is called after the common callbacks GETFOCUS_CB and KILL_FOCUS_CB.
/// (since 3.21) int function(Ihandle *ih, int focus); [in C]ih:focus_cb(focus:
/// number) -> (ret: number) [in Lua]
pub const OnFocusFn = fn (self: *Self, arg0: i32) anyerror!void;
///
/// K_ANY K_ANY Action generated when a keyboard event occurs.
/// Callback int function(Ihandle *ih, int c); [in C] ih:k_any(c: number) ->
/// (ret: number) [in Lua] ih: identifier of the element that activated the event.
/// c: identifier of typed key.
/// Please refer to the Keyboard Codes table for a list of possible values.
/// Returns: If IUP_IGNORE is returned the key is ignored and not processed by
/// the control and not propagated.
/// If returns IUP_CONTINUE, the key will be processed and the event will be
/// propagated to the parent of the element receiving it, this is the default behavior.
/// If returns IUP_DEFAULT the key is processed but it is not propagated.
/// IUP_CLOSE will be processed.
/// Notes Keyboard callbacks depend on the keyboard usage of the control with
/// the focus.
/// So if you return IUP_IGNORE the control will usually not process the key.
/// But be aware that sometimes the control process the key in another event so
/// even returning IUP_IGNORE the key can get processed.
/// Although it will not be propagated.
/// IMPORTANT: The callbacks "K_*" of the dialog or native containers depend on
/// the IUP_CONTINUE return value to work while the control is in focus.
/// If the callback does not exists it is automatically propagated to the
/// parent of the element.
/// K_* callbacks All defined keys are also callbacks of any element, called
/// when the respective key is activated.
/// For example: "K_cC" is also a callback activated when the user press
/// Ctrl+C, when the focus is at the element or at a children with focus.
/// This is the way an application can create shortcut keys, also called hot keys.
/// These callbacks are not available in IupLua.
/// Affects All elements with keyboard interaction.
pub const OnKAnyFn = fn (self: *Self, arg0: i32) anyerror!void;
///
/// HELP_CB HELP_CB Action generated when the user press F1 at a control.
/// In Motif is also activated by the Help button in some workstations keyboard.
/// Callback void function(Ihandle *ih); [in C] ih:help_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Returns: IUP_CLOSE will be processed.
/// Affects All elements with user interaction.
pub const OnHelpFn = fn (self: *Self) anyerror!void;
///
/// CLOSE_CB CLOSE_CB Called just before a dialog is closed when the user
/// clicks the close button of the title bar or an equivalent action.
/// Callback int function(Ihandle *ih); [in C] ih:close_cb() -> (ret: number)
/// [in Lua] ih: identifies the element that activated the event.
/// Returns: if IUP_IGNORE, it prevents the dialog from being closed.
/// If you destroy the dialog in this callback, you must return IUP_IGNORE.
/// IUP_CLOSE will be processed.
/// Affects IupDialog
pub const OnCloseFn = fn (self: *Self) anyerror!void;
pub const OnDropMotionFn = fn (self: *Self, arg0: i32, arg1: i32, arg2: [:0]const u8) anyerror!void;
pub const OnDragEndFn = fn (self: *Self, arg0: i32) anyerror!void;
pub const OnDragBeginFn = fn (self: *Self, arg0: i32, arg1: i32) anyerror!void;
///
/// MAP_CB MAP_CB Called right after an element is mapped and its attributes
/// updated in IupMap.
/// When the element is a dialog, it is called after the layout is updated.
/// For all other elements is called before the layout is updated, so the
/// element current size will still be 0x0 during MAP_CB (since 3.14).
/// Callback int function(Ihandle *ih); [in C] ih:map_cb() -> (ret: number) [in
/// Lua] ih: identifier of the element that activated the event.
/// Affects All that have a native representation.
pub const OnMapFn = fn (self: *Self) anyerror!void;
///
/// ENTERWINDOW_CB ENTERWINDOW_CB Action generated when the mouse enters the
/// native element.
/// Callback int function(Ihandle *ih); [in C] ih:enterwindow_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// Notes When the cursor is moved from one element to another, the call order
/// in all platforms will be first the LEAVEWINDOW_CB callback of the old
/// control followed by the ENTERWINDOW_CB callback of the new control.
/// (since 3.14) If the mouse button is hold pressed and the cursor moves
/// outside the element the behavior is system dependent.
/// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in
/// GTK the callbacks are called.
/// Affects All controls with user interaction.
/// See Also LEAVEWINDOW_CB
pub const OnEnterWindowFn = fn (self: *Self) anyerror!void;
///
/// DESTROY_CB DESTROY_CB Called right before an element is destroyed.
/// Callback int function(Ihandle *ih); [in C] ih:destroy_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Notes If the dialog is visible then it is hidden before it is destroyed.
/// The callback will be called right after it is hidden.
/// The callback will be called before all other destroy procedures.
/// For instance, if the element has children then it is called before the
/// children are destroyed.
/// For language binding implementations use the callback name "LDESTROY_CB" to
/// release memory allocated by the binding for the element.
/// Also the callback will be called before the language callback.
/// Affects All.
pub const OnDestroyFn = fn (self: *Self) anyerror!void;
pub const OnDropDataFn = fn (self: *Self, arg0: [:0]const u8, arg1: *iup.Unknow, arg2: i32, arg3: i32, arg4: i32) anyerror!void;
///
/// KILLFOCUS_CB KILLFOCUS_CB Action generated when an element loses keyboard focus.
/// This callback is called before the GETFOCUS_CB of the element that gets the focus.
/// Callback int function(Ihandle *ih); [in C] ih:killfocus_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// Affects All elements with user interaction, except menus.
/// In Windows, there are restrictions when using this callback.
/// From MSDN on WM_KILLFOCUS: "While processing this message, do not make any
/// function calls that display or activate a window.
/// This causes the thread to yield control and can cause the application to
/// stop responding to messages.
/// See Also GETFOCUS_CB, IupGetFocus, IupSetFocus
pub const OnKillFocusFn = fn (self: *Self) anyerror!void;
pub const OnDragDataFn = fn (self: *Self, arg0: [:0]const u8, arg1: *iup.Unknow, arg2: i32) anyerror!void;
pub const OnDragDataSizeFn = fn (self: *Self, arg0: [:0]const u8) anyerror!void;
///
/// SHOW_CB SHOW_CB Called right after the dialog is showed, hidden, maximized,
/// minimized or restored from minimized/maximized.
/// This callback is called when those actions were performed by the user or
/// programmatically by the application.
/// Callback int function(Ihandle *ih, int state); [in C] ih:show_cb(state:
/// number) -> (ret: number) [in Lua] ih: identifier of the element that
/// activated the event.
/// state: indicates which of the following situations generated the event:
/// IUP_HIDE (since 3.0) IUP_SHOW IUP_RESTORE (was minimized or maximized)
/// IUP_MINIMIZE IUP_MAXIMIZE (since 3.0) (not received in Motif when activated
/// from the maximize button) Returns: IUP_CLOSE will be processed.
/// Affects IupDialog
pub const OnShowFn = fn (self: *Self, arg0: i32) anyerror!void;
///
/// DROPFILES_CB DROPFILES_CB Action called when a file is "dropped" into the control.
/// When several files are dropped at once, the callback is called several
/// times, once for each file.
/// If defined after the element is mapped then the attribute DROPFILESTARGET
/// must be set to YES.
/// [Windows and GTK Only] (GTK 2.6) Callback int function(Ihandle *ih, const
/// char* filename, int num, int x, int y); [in C] ih:dropfiles_cb(filename:
/// string; num, x, y: number) -> (ret: number) [in Lua] ih: identifier of the
/// element that activated the event.
/// filename: Name of the dropped file.
/// num: Number index of the dropped file.
/// If several files are dropped, num is the index of the dropped file starting
/// from "total-1" to "0".
/// x: X coordinate of the point where the user released the mouse button.
/// y: Y coordinate of the point where the user released the mouse button.
/// Returns: If IUP_IGNORE is returned the callback will NOT be called for the
/// next dropped files, and the processing of dropped files will be interrupted.
/// Affects IupDialog, IupCanvas, IupGLCanvas, IupText, IupList
pub const OnDropFilesFn = fn (self: *Self, arg0: [:0]const u8, arg1: i32, arg2: i32, arg3: i32) anyerror!void;
///
/// RESIZE_CB RESIZE_CB Action generated when the canvas or dialog size is changed.
/// Callback int function(Ihandle *ih, int width, int height); [in C]
/// ih:resize_cb(width, height: number) -> (ret: number) [in Lua] ih:
/// identifier of the element that activated the event.
/// width: the width of the internal element size in pixels not considering the
/// decorations (client size) height: the height of the internal element size
/// in pixels not considering the decorations (client size) Notes For the
/// dialog, this action is also generated when the dialog is mapped, after the
/// map and before the show.
/// When XAUTOHIDE=Yes or YAUTOHIDE=Yes, if the canvas scrollbar is
/// hidden/shown after changing the DX or DY attributes from inside the
/// callback, the size of the drawing area will immediately change, so the
/// parameters with and height will be invalid.
/// To update the parameters consult the DRAWSIZE attribute.
/// Also activate the drawing toolkit only after updating the DX or DY attributes.
/// Affects IupCanvas, IupGLCanvas, IupDialog
pub const OnResizeFn = fn (self: *Self, arg0: i32, arg1: i32) anyerror!void;
///
/// UNMAP_CB UNMAP_CB Called right before an element is unmapped.
/// Callback int function(Ihandle *ih); [in C] ih:unmap_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Affects All that have a native representation.
pub const OnUnmapFn = fn (self: *Self) anyerror!void;
///
/// TRAYCLICK_CB [Windows and GTK Only]: Called right after the mouse button is
/// pressed or released over the tray icon.
/// (GTK 2.10) int function(Ihandle *ih, int but, int pressed, int dclick); [in
/// C]elem:trayclick_cb(but, pressed, dclick: number) -> (ret: number) [in Lua]
pub const OnTrayClickFn = fn (self: *Self, arg0: i32, arg1: i32, arg2: i32) anyerror!void;
///
/// GETFOCUS_CB GETFOCUS_CB Action generated when an element is given keyboard focus.
/// This callback is called after the KILLFOCUS_CB of the element that loosed
/// the focus.
/// The IupGetFocus function during the callback returns the element that
/// loosed the focus.
/// Callback int function(Ihandle *ih); [in C] ih:getfocus_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that received keyboard focus.
/// Affects All elements with user interaction, except menus.
/// See Also KILLFOCUS_CB, IupGetFocus, IupSetFocus
pub const OnGetFocusFn = fn (self: *Self) anyerror!void;
pub const OnLDestroyFn = fn (self: *Self) anyerror!void;
///
/// LEAVEWINDOW_CB LEAVEWINDOW_CB Action generated when the mouse leaves the
/// native element.
/// Callback int function(Ihandle *ih); [in C] ih:leavewindow_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// Notes When the cursor is moved from one element to another, the call order
/// in all platforms will be first the LEAVEWINDOW_CB callback of the old
/// control followed by the ENTERWINDOW_CB callback of the new control.
/// (since 3.14) If the mouse button is hold pressed and the cursor moves
/// outside the element the behavior is system dependent.
/// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in
/// GTK the callbacks are called.
/// Affects All controls with user interaction.
/// See Also ENTERWINDOW_CB
pub const OnLeaveWindowFn = fn (self: *Self) anyerror!void;
pub const OnPostMessageFn = fn (self: *Self, arg0: [:0]const u8, arg1: i32, arg2: f64, arg3: *iup.Unknow) anyerror!void;
pub const ZOrder = enum {
Top,
Bottom,
};
///
/// EXPAND (non inheritable): The default value is "YES".
pub const Expand = enum {
Yes,
Horizontal,
Vertical,
HorizontalFree,
VerticalFree,
No,
};
///
/// PLACEMENT: Changes how the dialog will be shown.
/// Values: "FULL", "MAXIMIZED", "MINIMIZED" and "NORMAL".
/// Default: NORMAL.
/// After IupShow/IupPopup the attribute is set back to "NORMAL".
/// FULL is similar to FULLSCREEN but only the dialog client area covers the
/// screen area, menu and decorations will be there but out of the screen.
/// In UNIX there is a chance that the placement won't work correctly, that
/// depends on the Window Manager.
/// In Windows, the SHOWNOACTIVATE attribute can be set to Yes to prevent the
/// window from being activated (since 3.15).
/// In Windows, the SHOWMINIMIZENEXT attribute can be set to Yes to activate
/// the next top-level window in the Z order when minimizing (since 3.15).
pub const Placement = enum {
Maximized,
Minimized,
Full,
};
pub const Floating = enum {
Yes,
Ignore,
No,
};
pub const Initializer = struct {
last_error: ?anyerror = null,
ref: *Self,
///
/// Returns a pointer to IUP element or an error.
/// Only top-level or detached elements needs to be unwraped,
pub fn unwrap(self: Initializer) !*Self {
if (self.last_error) |e| {
return e;
} else {
return self.ref;
}
}
///
/// Captures a reference into a external variable
/// Allows to capture some references even using full declarative API
pub fn capture(self: *Initializer, ref: **Self) Initializer {
ref.* = self.ref;
return self.*;
}
pub fn setStrAttribute(self: *Initializer, attributeName: [:0]const u8, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
Self.setStrAttribute(self.ref, attributeName, arg);
return self.*;
}
pub fn setIntAttribute(self: *Initializer, attributeName: [:0]const u8, arg: i32) Initializer {
if (self.last_error) |_| return self.*;
Self.setIntAttribute(self.ref, attributeName, arg);
return self.*;
}
pub fn setBoolAttribute(self: *Initializer, attributeName: [:0]const u8, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
Self.setBoolAttribute(self.ref, attributeName, arg);
return self.*;
}
pub fn setPtrAttribute(self: *Initializer, comptime T: type, attributeName: [:0]const u8, value: ?*T) Initializer {
if (self.last_error) |_| return self.*;
Self.setPtrAttribute(self.ref, T, attributeName, value);
return self.*;
}
pub fn setHandle(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setHandle(self.ref, arg);
return self.*;
}
pub fn setChildren(self: *Initializer, tuple: anytype) Initializer {
if (self.last_error) |_| return self.*;
Self.appendChildren(self.ref, tuple) catch |err| {
self.last_error = err;
};
return self.*;
}
pub fn setHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "HANDLENAME", .{}, arg);
return self.*;
}
pub fn setTipBgColor(self: *Initializer, rgb: iup.Rgb) Initializer {
if (self.last_error) |_| return self.*;
interop.setRgb(self.ref, "TIPBGCOLOR", .{}, rgb);
return self.*;
}
///
/// MDICLIENT (creation only) [Windows Only] (non inheritable): Configure the
/// canvas as a MDI client.
/// Can be YES or NO.
/// No callbacks will be called.
/// This canvas will be used internally only by the MDI Frame and its MDI Children.
/// The MDI frame must have one and only one MDI client.
/// Default: NO.
pub fn setMdiClient(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "MDICLIENT", .{}, arg);
return self.*;
}
///
/// CONTROL [Windows Only] (creation only): Embeds the dialog inside another window.
pub fn setControl(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "CONTROL", .{}, arg);
return self.*;
}
pub fn setTipIcon(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TIPICON", .{}, arg);
return self.*;
}
///
/// MENU: Name of a menu.
/// Associates a menu to the dialog as a menu bar.
/// The previous menu, if any, is unmapped.
/// Use IupSetHandle or IupSetAttributeHandle to associate a menu to a name.
/// See also IupMenu.
pub fn setMenu(self: *Initializer, arg: *iup.Menu) Initializer {
if (self.last_error) |_| return self.*;
interop.setHandleAttribute(self.ref, "MENU", .{}, arg);
return self.*;
}
pub fn setMenuHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "MENU", .{}, arg);
return self.*;
}
pub fn setNoFlush(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "NOFLUSH", .{}, arg);
return self.*;
}
///
/// MAXSIZE: Maximum size for the dialog in raster units (pixels).
/// The windowing system will not be able to change the size beyond this limit.
/// Default: 65535x65535.
/// (since 3.0)
pub fn setMaxSize(self: *Initializer, width: ?i32, height: ?i32) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self.ref, "MAXSIZE", .{}, value);
return self.*;
}
///
/// OPACITYIMAGE [Windows Only]: sets an RGBA image as the dialog background so
/// it is possible to create a non rectangle window with transparency, but it
/// can not have children.
/// Used usually for splash screens.
/// It must be set before map so the native window would be properly
/// initialized when mapped.
/// Works also for GTK but as the SHAPEIMAGE attribute.
/// (since 3.16)
pub fn setOpacityImage(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "OPACITYIMAGE", .{}, arg);
return self.*;
}
///
/// HELPBUTTON [Windows Only] (creation only): Inserts a help button in the
/// same place of the maximize button.
/// It can only be used for dialogs without the minimize and maximize buttons,
/// and with the menu box.
/// For the next interaction of the user with a control in the dialog, the
/// callback HELP_CB will be called instead of the control defined ACTION callback.
/// Possible values: YES, NO.
/// Default: NO.
pub fn setHelpButton(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "HELPBUTTON", .{}, arg);
return self.*;
}
///
/// SHOWNOFOCUS: do not set focus after show.
/// (since 3.30)
pub fn setShowNoFocus(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "SHOWNOFOCUS", .{}, arg);
return self.*;
}
///
/// OPACITY [Windows and GTK Only]: sets the dialog transparency alpha value.
/// Valid values range from 0 (completely transparent) to 255 (opaque).
/// In Windows must be set before map so the native window would be properly
/// initialized when mapped (since 3.16).
/// (GTK 2.12)
pub fn setOpacity(self: *Initializer, arg: i32) Initializer {
if (self.last_error) |_| return self.*;
interop.setIntAttribute(self.ref, "OPACITY", .{}, arg);
return self.*;
}
pub fn setPosition(self: *Initializer, x: i32, y: i32) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var value = iup.XYPos.intIntToString(&buffer, x, y, ',');
interop.setStrAttribute(self.ref, "POSITION", .{}, value);
return self.*;
}
///
/// COMPOSITED [Windows Only] (creation only): controls if the window will have
/// an automatic double buffer for all children.
/// Default is "NO".
/// In Windows Vista it is NOT working as expected.
/// It is NOT compatible with IupCanvas and all derived IUP controls such as
/// IupFlat*, IupGL*, IupPlot and IupMatrix, because IupCanvas uses CS_OWNDC in
/// the window class.
pub fn setComposited(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "COMPOSITED", .{}, arg);
return self.*;
}
///
/// DROPFILESTARGET [Windows and GTK Only] (non inheritable): Enable or disable
/// the drop of files.
/// Default: NO, but if DROPFILES_CB is defined when the element is mapped then
/// it will be automatically enabled.
pub fn setDropFilesTarget(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "DROPFILESTARGET", .{}, arg);
return self.*;
}
pub fn setTip(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TIP", .{}, arg);
return self.*;
}
pub fn setCanFocus(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "CANFOCUS", .{}, arg);
return self.*;
}
pub fn setDragSourceMove(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "DRAGSOURCEMOVE", .{}, arg);
return self.*;
}
///
/// ICON: Dialogs icon.
/// The Windows SDK recommends that cursors and icons should be implemented as
/// resources rather than created at run time.
pub fn setIcon(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "ICON", .{}, arg);
return self.*;
}
///
/// VISIBLE: Simply call IupShow or IupHide for the dialog.
pub fn setVisible(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "VISIBLE", .{}, arg);
return self.*;
}
///
/// CURSOR (non inheritable): Defines a cursor for the dialog.
pub fn setCursor(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "CURSOR", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setCursorHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "CURSOR", .{}, arg);
return self.*;
}
///
/// MENUBOX (creation only): Requires a system menu box from the window manager.
/// If hidden will also remove the Close button.
/// Default: YES.
/// In Motif the decorations are controlled by the Window Manager and may not
/// be possible to be changed from IUP.
/// In Windows if hidden will hide also MAXBOX and MINBOX.
pub fn setMenuBox(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "MENUBOX", .{}, arg);
return self.*;
}
pub fn zOrder(self: *Initializer, arg: ?ZOrder) Initializer {
if (self.last_error) |_| return self.*;
if (arg) |value| switch (value) {
.Top => interop.setStrAttribute(self.ref, "ZORDER", .{}, "TOP"),
.Bottom => interop.setStrAttribute(self.ref, "ZORDER", .{}, "BOTTOM"),
} else {
interop.clearAttribute(self.ref, "ZORDER", .{});
}
return self.*;
}
///
/// HIDETITLEBAR [GTK Only] (non inheritable): hides the title bar with al its elements.
/// (since 3.20) (GTK 3.10)
pub fn setHideTitleBar(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "HIDETITLEBAR", .{}, arg);
return self.*;
}
///
/// MAXBOX (creation only): Requires a maximize button from the window manager.
/// If RESIZE=NO then MAXBOX will be set to NO.
/// Default: YES.
/// In Motif the decorations are controlled by the Window Manager and may not
/// be possible to be changed from IUP.
/// In Windows MAXBOX is hidden only if MINBOX is hidden as well, or else it
/// will be just disabled.
pub fn setMaxBox(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "MAXBOX", .{}, arg);
return self.*;
}
pub fn setDragDrop(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "DRAGDROP", .{}, arg);
return self.*;
}
///
/// DIALOGHINT [GTK Only] (creation-only): if enabled sets the window type hint
/// to a dialog hint.
pub fn setDialogHint(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "DIALOGHINT", .{}, arg);
return self.*;
}
///
/// DIALOGFRAME: Set the common decorations for modal dialogs.
/// This means RESIZE=NO, MINBOX=NO and MAXBOX=NO.
/// In Windows, if the PARENTDIALOG is defined then the MENUBOX is also
/// removed, but the Close button remains.
pub fn setDialogFrame(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "DIALOGFRAME", .{}, arg);
return self.*;
}
///
/// NACTIVE (non inheritable): same as ACTIVE but does not affects the controls
/// inside the dialog.
/// (since 3.13)
pub fn setNActive(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "NACTIVE", .{}, arg);
return self.*;
}
pub fn setTheme(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "THEME", .{}, arg);
return self.*;
}
///
/// SAVEUNDER [Windows and Motif Only] (creation only): When this attribute is
/// true (YES), the dialog stores the original image of the desktop region it
/// occupies (if the system has enough memory to store the image).
/// In this case, when the dialog is closed or moved, a redrawing event is not
/// generated for the windows that were shadowed by it.
/// Its default value is YES if the dialog has a parent dialog (since 3.24).
/// To save memory disable it for your main dialog.
/// Not available in GTK.
pub fn setSaveUnder(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "SAVEUNDER", .{}, arg);
return self.*;
}
///
/// TRAY [Windows and GTK Only]: When set to "YES", displays an icon on the
/// system tray.
/// (GTK 2.10 and GTK < 3.14)
pub fn setTray(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "TRAY", .{}, arg);
return self.*;
}
///
/// CHILDOFFSET: Allow to specify a position offset for the child.
/// Available for native containers only.
/// It will not affect the natural size, and allows to position controls
/// outside the client area.
/// Format "dxxdy", where dx and dy are integer values corresponding to the
/// horizontal and vertical offsets, respectively, in pixels.
/// Default: 0x0.
/// (since 3.14)
pub fn setChildOffset(self: *Initializer, width: ?i32, height: ?i32) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self.ref, "CHILDOFFSET", .{}, value);
return self.*;
}
///
/// EXPAND (non inheritable): The default value is "YES".
pub fn setExpand(self: *Initializer, arg: ?Expand) Initializer {
if (self.last_error) |_| return self.*;
if (arg) |value| switch (value) {
.Yes => interop.setStrAttribute(self.ref, "EXPAND", .{}, "YES"),
.Horizontal => interop.setStrAttribute(self.ref, "EXPAND", .{}, "HORIZONTAL"),
.Vertical => interop.setStrAttribute(self.ref, "EXPAND", .{}, "VERTICAL"),
.HorizontalFree => interop.setStrAttribute(self.ref, "EXPAND", .{}, "HORIZONTALFREE"),
.VerticalFree => interop.setStrAttribute(self.ref, "EXPAND", .{}, "VERTICALFREE"),
.No => interop.setStrAttribute(self.ref, "EXPAND", .{}, "NO"),
} else {
interop.clearAttribute(self.ref, "EXPAND", .{});
}
return self.*;
}
///
/// SIZE (non inheritable): Dialogs size.
/// Additionally the following values can also be defined for width and/or
/// height: "FULL": Defines the dialogs width (or height) equal to the screen's
/// width (or height) "HALF": Defines the dialogs width (or height) equal to
/// half the screen's width (or height) "THIRD": Defines the dialogs width (or
/// height) equal to 1/3 the screen's width (or height) "QUARTER": Defines the
/// dialogs width (or height) equal to 1/4 of the screen's width (or height)
/// "EIGHTH": Defines the dialogs width (or height) equal to 1/8 of the
/// screen's width (or height).
/// Values set at SIZE or RASTERSIZE attributes of a dialog are always
/// accepted, regardless of the minimum size required by its children.
/// For a dialog to have the minimum necessary size to fit all elements
/// contained in it, simply define SIZE or RASTERSIZE to NULL.
/// Also if you set SIZE or RASTERSIZE to be used as the initial size of the
/// dialog, its contents will be limited to this size as the minimum size, if
/// you do not want that, then after showing the dialog reset this size to NULL
/// so the dialog can be resized to smaller values.
/// But notice that its contents will still be limited by the Natural size, to
/// also remove that limitation set SHRINK=YES.
/// To only change the User size in pixels, without resetting the Current size,
/// set the USERSIZE attribute (since 3.12).
/// Values set at SIZE or RASTERSIZE attributes of a dialog are always
/// accepted, regardless of the minimum size required by its children.
/// For a dialog to have the minimum necessary size to fit all elements
/// contained in it, simply define SIZE or RASTERSIZE to NULL.
/// Also if you set SIZE or RASTERSIZE to be used as the initial size of the
/// dialog, its contents will be limited to this size as the minimum size, if
/// you do not want that, then after showing the dialog reset this size to NULL
/// so the dialog can be resized to smaller values.
/// But notice that its contents will still be limited by the Natural size, to
/// also remove that limitation set SHRINK=YES.
/// To only change the User size in pixels, without resetting the Current size,
/// set the USERSIZE attribute (since 3.12).
/// Values set at SIZE or RASTERSIZE attributes of a dialog are always
/// accepted, regardless of the minimum size required by its children.
/// For a dialog to have the minimum necessary size to fit all elements
/// contained in it, simply define SIZE or RASTERSIZE to NULL.
/// Also if you set SIZE or RASTERSIZE to be used as the initial size of the
/// dialog, its contents will be limited to this size as the minimum size, if
/// you do not want that, then after showing the dialog reset this size to NULL
/// so the dialog can be resized to smaller values.
/// But notice that its contents will still be limited by the Natural size, to
/// also remove that limitation set SHRINK=YES.
/// To only change the User size in pixels, without resetting the Current size,
/// set the USERSIZE attribute (since 3.12).
pub fn setSize(self: *Initializer, width: ?iup.ScreenSize, height: ?iup.ScreenSize) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var str = iup.DialogSize.screenSizeToString(&buffer, width, height);
interop.setStrAttribute(self.ref, "SIZE", .{}, str);
return self.*;
}
pub fn setTipMarkup(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TIPMARKUP", .{}, arg);
return self.*;
}
///
/// MDIMENU (creation only) [Windows Only]: Name of a IupMenu to be used as the
/// Window list of a MDI frame.
/// The system will automatically add the list of MDI child windows there.
pub fn setMdiMenu(self: *Initializer, arg: *iup.Menu) Initializer {
if (self.last_error) |_| return self.*;
interop.setHandleAttribute(self.ref, "MDIMENU", .{}, arg);
return self.*;
}
pub fn setMdiMenuHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "MDIMENU", .{}, arg);
return self.*;
}
///
/// STARTFOCUS: Name of the element that must receive the focus right after the
/// dialog is shown using IupShow or IupPopup.
/// If not defined then the first control than can receive the focus is
/// selected (same effect of calling IupNextField for the dialog).
/// Updated after SHOW_CB is called and only if the focus was not changed
/// during the callback.
pub fn setStartFocus(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "STARTFOCUS", .{}, arg);
return self.*;
}
pub fn setFontSize(self: *Initializer, arg: i32) Initializer {
if (self.last_error) |_| return self.*;
interop.setIntAttribute(self.ref, "FONTSIZE", .{}, arg);
return self.*;
}
pub fn setDropTypes(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "DROPTYPES", .{}, arg);
return self.*;
}
///
/// TRAYTIPMARKUP [GTK Only]: allows the tip string to contains Pango markup commands.
/// Can be "YES" or "NO".
/// Default: "NO".
/// Must be set before setting the TRAYTIP attribute.
/// (GTK 2.16) (since 3.6)
pub fn setTrayTipMarkup(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TRAYTIPMARKUP", .{}, arg);
return self.*;
}
pub fn setUserSize(self: *Initializer, width: ?i32, height: ?i32) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self.ref, "USERSIZE", .{}, value);
return self.*;
}
pub fn setTipDelay(self: *Initializer, arg: i32) Initializer {
if (self.last_error) |_| return self.*;
interop.setIntAttribute(self.ref, "TIPDELAY", .{}, arg);
return self.*;
}
///
/// CUSTOMFRAME [Windows and GTK Only] (non inheritable): allows the
/// application to customize the dialog frame elements (the title and its
/// buttons) by using IUP controls for its elements like caption, minimize
/// button, maximize button, and close buttons.
/// The custom frame support uses the native system support for custom frames.
/// The application is responsible for leaving space for the borders.
/// One drawback is that menu bars will not work.
/// For the dialog to be able to be moved an IupLabel or an IupCanvas must be
/// at the top of the dialog and must have the NAME attribute set to
/// CUSTOMFRAMECAPTION (since 3.22).
/// Native custom frames are supported only in Windows and in GTK version 3.10,
/// so for older GTK versions we have to simulate the support using CUSTOMFRAMESIMULATE.
/// (since 3.18) (renamed in 3.22) (GTK support since 3.22) See the Custom
/// Frame notes bellow.
pub fn setCustomFrame(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "CUSTOMFRAME", .{}, arg);
return self.*;
}
///
/// TITLE (non inheritable): Dialogs title.
/// Default: NULL.
/// If you want to remove the title bar you must also set MENUBOX=NO, MAXBOX=NO
/// and MINBOX=NO, before map.
/// But in Motif and GTK it will hide it only if RESIZE=NO also.
pub fn setTitle(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TITLE", .{}, arg);
return self.*;
}
///
/// DEFAULTESC: Name of the button activated when the user press Esc when focus
/// is in another control of the dialog.
/// Use IupSetHandle or IupSetAttributeHandle to associate a button to a name.
pub fn setDefaultEsc(self: *Initializer, arg: *iup.Button) Initializer {
if (self.last_error) |_| return self.*;
interop.setHandleAttribute(self.ref, "DEFAULTESC", .{}, arg);
return self.*;
}
pub fn setDefaultEscHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "DEFAULTESC", .{}, arg);
return self.*;
}
///
/// PLACEMENT: Changes how the dialog will be shown.
/// Values: "FULL", "MAXIMIZED", "MINIMIZED" and "NORMAL".
/// Default: NORMAL.
/// After IupShow/IupPopup the attribute is set back to "NORMAL".
/// FULL is similar to FULLSCREEN but only the dialog client area covers the
/// screen area, menu and decorations will be there but out of the screen.
/// In UNIX there is a chance that the placement won't work correctly, that
/// depends on the Window Manager.
/// In Windows, the SHOWNOACTIVATE attribute can be set to Yes to prevent the
/// window from being activated (since 3.15).
/// In Windows, the SHOWMINIMIZENEXT attribute can be set to Yes to activate
/// the next top-level window in the Z order when minimizing (since 3.15).
pub fn setPlacement(self: *Initializer, arg: ?Placement) Initializer {
if (self.last_error) |_| return self.*;
if (arg) |value| switch (value) {
.Maximized => interop.setStrAttribute(self.ref, "PLACEMENT", .{}, "MAXIMIZED"),
.Minimized => interop.setStrAttribute(self.ref, "PLACEMENT", .{}, "MINIMIZED"),
.Full => interop.setStrAttribute(self.ref, "PLACEMENT", .{}, "FULL"),
} else {
interop.clearAttribute(self.ref, "PLACEMENT", .{});
}
return self.*;
}
pub fn setPropagateFocus(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "PROPAGATEFOCUS", .{}, arg);
return self.*;
}
pub fn setBgColor(self: *Initializer, rgb: iup.Rgb) Initializer {
if (self.last_error) |_| return self.*;
interop.setRgb(self.ref, "BGCOLOR", .{}, rgb);
return self.*;
}
pub fn setDropTarget(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "DROPTARGET", .{}, arg);
return self.*;
}
pub fn setDragSource(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "DRAGSOURCE", .{}, arg);
return self.*;
}
///
/// RESIZE (creation only): Allows interactively changing the dialogs size.
/// Default: YES.
/// If RESIZE=NO then MAXBOX will be set to NO.
/// In Motif the decorations are controlled by the Window Manager and may not
/// be possible to be changed from IUP.
pub fn setResize(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "RESIZE", .{}, arg);
return self.*;
}
pub fn setFloating(self: *Initializer, arg: ?Floating) Initializer {
if (self.last_error) |_| return self.*;
if (arg) |value| switch (value) {
.Yes => interop.setStrAttribute(self.ref, "FLOATING", .{}, "YES"),
.Ignore => interop.setStrAttribute(self.ref, "FLOATING", .{}, "IGNORE"),
.No => interop.setStrAttribute(self.ref, "FLOATING", .{}, "NO"),
} else {
interop.clearAttribute(self.ref, "FLOATING", .{});
}
return self.*;
}
pub fn setNormalizerGroup(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "NORMALIZERGROUP", .{}, arg);
return self.*;
}
///
/// Values set at SIZE or RASTERSIZE attributes of a dialog are always
/// accepted, regardless of the minimum size required by its children.
/// For a dialog to have the minimum necessary size to fit all elements
/// contained in it, simply define SIZE or RASTERSIZE to NULL.
/// Also if you set SIZE or RASTERSIZE to be used as the initial size of the
/// dialog, its contents will be limited to this size as the minimum size, if
/// you do not want that, then after showing the dialog reset this size to NULL
/// so the dialog can be resized to smaller values.
/// But notice that its contents will still be limited by the Natural size, to
/// also remove that limitation set SHRINK=YES.
/// To only change the User size in pixels, without resetting the Current size,
/// set the USERSIZE attribute (since 3.12).
/// Values set at SIZE or RASTERSIZE attributes of a dialog are always
/// accepted, regardless of the minimum size required by its children.
/// For a dialog to have the minimum necessary size to fit all elements
/// contained in it, simply define SIZE or RASTERSIZE to NULL.
/// Also if you set SIZE or RASTERSIZE to be used as the initial size of the
/// dialog, its contents will be limited to this size as the minimum size, if
/// you do not want that, then after showing the dialog reset this size to NULL
/// so the dialog can be resized to smaller values.
/// But notice that its contents will still be limited by the Natural size, to
/// also remove that limitation set SHRINK=YES.
/// To only change the User size in pixels, without resetting the Current size,
/// set the USERSIZE attribute (since 3.12).
/// Values set at SIZE or RASTERSIZE attributes of a dialog are always
/// accepted, regardless of the minimum size required by its children.
/// For a dialog to have the minimum necessary size to fit all elements
/// contained in it, simply define SIZE or RASTERSIZE to NULL.
/// Also if you set SIZE or RASTERSIZE to be used as the initial size of the
/// dialog, its contents will be limited to this size as the minimum size, if
/// you do not want that, then after showing the dialog reset this size to NULL
/// so the dialog can be resized to smaller values.
/// But notice that its contents will still be limited by the Natural size, to
/// also remove that limitation set SHRINK=YES.
/// To only change the User size in pixels, without resetting the Current size,
/// set the USERSIZE attribute (since 3.12).
pub fn setRasterSize(self: *Initializer, width: ?i32, height: ?i32) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self.ref, "RASTERSIZE", .{}, value);
return self.*;
}
///
/// SHAPEIMAGE [Windows and GTK Only]: sets a RGBA image as the dialog shape so
/// it is possible to create a non rectangle window with children.
/// (GTK 2.12) Only the fully transparent pixels will be transparent.
/// The pixels colors will be ignored, only the alpha channel is used.
/// (since 3.26)
pub fn setShapeImage(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "SHAPEIMAGE", .{}, arg);
return self.*;
}
pub fn setTipFgColor(self: *Initializer, rgb: iup.Rgb) Initializer {
if (self.last_error) |_| return self.*;
interop.setRgb(self.ref, "TIPFGCOLOR", .{}, rgb);
return self.*;
}
pub fn setFontFace(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "FONTFACE", .{}, arg);
return self.*;
}
///
/// TOPMOST [Windows and GTK Only]: puts the dialog always in front of all
/// other dialogs in all applications.
/// Default: NO.
pub fn topMost(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "TOPMOST", .{}, arg);
return self.*;
}
pub fn setName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "NAME", .{}, arg);
return self.*;
}
///
/// MINBOX (creation only): Requires a minimize button from the window manager.
/// Default: YES.
/// In Motif the decorations are controlled by the Window Manager and may not
/// be possible to be changed from IUP.
/// In Windows MINBOX is hidden only if MAXBOX is hidden as well, or else it
/// will be just disabled.
pub fn setMinBox(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "MINBOX", .{}, arg);
return self.*;
}
///
/// DEFAULTENTER: Name of the button activated when the user press Enter when
/// focus is in another control of the dialog.
/// Use IupSetHandle or IupSetAttributeHandle to associate a button to a name.
pub fn setDefaultEnter(self: *Initializer, arg: *iup.Button) Initializer {
if (self.last_error) |_| return self.*;
interop.setHandleAttribute(self.ref, "DEFAULTENTER", .{}, arg);
return self.*;
}
pub fn setDefaultEnterHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "DEFAULTENTER", .{}, arg);
return self.*;
}
///
/// PARENTDIALOG (creation only): Name of a dialog to be used as parent.
pub fn setParentDialog(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Dialog, arg)) {
interop.setHandleAttribute(self.ref, "PARENTDIALOG", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setParentDialogHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "PARENTDIALOG", .{}, arg);
return self.*;
}
///
/// BACKGROUND (non inheritable): Dialog background color or image.
/// Can be a non inheritable alternative to BGCOLOR or can be the name of an
/// image to be tiled on the background.
/// See also the screenshots of the sample.c results with normal background,
/// changing the dialog BACKGROUND, the dialog BGCOLOR and the children BGCOLOR.
/// Not working in GTK 3.
/// (since 3.0)
pub fn setBackground(self: *Initializer, rgb: iup.Rgb) Initializer {
if (self.last_error) |_| return self.*;
interop.setRgb(self.ref, "BACKGROUND", .{}, rgb);
return self.*;
}
///
/// HIDETASKBAR [Windows and GTK Only] (write-only): Action attribute that when
/// set to "YES", hides the dialog, but does not decrement the visible dialog
/// count, does not call SHOW_CB and does not mark the dialog as hidden inside IUP.
/// It is usually used to hide the dialog and keep the tray icon working
/// without closing the main loop.
/// It has the same effect as setting LOCKLOOP=Yes and normally hiding the dialog.
/// IMPORTANT: when you hide using HIDETASKBAR, you must show using HIDETASKBAR also.
/// Possible values: YES, NO.
pub fn setHideTaskbar(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "HIDETASKBAR", .{}, arg);
return self.*;
}
///
/// BRINGFRONT [Windows Only] (write-only): makes the dialog the foreground window.
/// Use "YES" to activate it.
/// Useful for multithreaded applications.
pub fn setBringFront(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "BRINGFRONT", .{}, arg);
return self.*;
}
///
/// TRAYIMAGE [Windows and GTK Only]: Name of a IUP image to be used as the
/// tray icon.
/// The Windows SDK recommends that cursors and icons should be implemented as
/// resources rather than created at run time.
/// (GTK 2.10 and GTK < 3.14)
pub fn setTrayImage(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "TRAYIMAGE", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setTrayImageHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TRAYIMAGE", .{}, arg);
return self.*;
}
///
/// ACTIVE, BGCOLOR, FONT, EXPAND, SCREENPOSITION, WID, TIP, CLIENTOFFSET,
/// CLIENTSIZE, RASTERSIZE, ZORDER: also accepted.
/// Note that ACTIVE, BGCOLOR and FONT will also affect all the controls inside
/// the dialog.
pub fn setActive(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "ACTIVE", .{}, arg);
return self.*;
}
pub fn setTipVisible(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "TIPVISIBLE", .{}, arg);
return self.*;
}
pub fn setExpandWeight(self: *Initializer, arg: f64) Initializer {
if (self.last_error) |_| return self.*;
interop.setDoubleAttribute(self.ref, "EXPANDWEIGHT", .{}, arg);
return self.*;
}
///
/// MINSIZE: Minimum size for the dialog in raster units (pixels).
/// The windowing system will not be able to change the size beyond this limit.
/// Default: 1x1.
/// Some systems define a very minimum size greater than this, for instance in
/// Windows the horizontal minimum size includes the window decoration buttons.
/// (since 3.0)
pub fn setMinSize(self: *Initializer, width: ?i32, height: ?i32) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self.ref, "MINSIZE", .{}, value);
return self.*;
}
pub fn setNTheme(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "NTHEME", .{}, arg);
return self.*;
}
///
/// BORDER (non inheritable) (creation only): Shows a resize border around the dialog.
/// Default: "YES".
/// BORDER=NO is useful only when RESIZE=NO, MAXBOX=NO, MINBOX=NO, MENUBOX=NO
/// and TITLE=NULL, if any of these are defined there will be always some border.
pub fn setBorder(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "BORDER", .{}, arg);
return self.*;
}
///
/// CUSTOMFRAMESIMULATE: allows the application to customize the dialog frame
/// elements (the title and its buttons) by using IUP controls for its elements
/// like caption, minimize button, maximize button, and close buttons.
/// The custom frame support is entirely simulated by IUP, no native support
/// for custom frame is used (this seems to have less drawbacks on the
/// application behavior).
/// The application is responsible for leaving space for the borders.
/// One drawback is that menu bars will not work.
/// For the dialog to be able to be moved an IupLabel, or a IupFlatLabel or an
/// IupCanvas must be at the top of the dialog and must have the NAME attribute
/// set to CUSTOMFRAMECAPTION.
/// See the Custom Frame notes bellow.
/// (since 3.28)
pub fn setCustomFramesImulate(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "CUSTOMFRAMESIMULATE", .{}, arg);
return self.*;
}
///
/// SHRINK: Allows changing the elements distribution when the dialog is
/// smaller than the minimum size.
/// Default: NO.
pub fn setShrink(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "SHRINK", .{}, arg);
return self.*;
}
pub fn setClientSize(self: *Initializer, width: ?i32, height: ?i32) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self.ref, "CLIENTSIZE", .{}, value);
return self.*;
}
///
/// TRAYTIP [Windows and GTK Only]: Tray icon's tooltip text.
/// (GTK 2.10 and GTK < 3.14)
pub fn setTrayTip(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TRAYTIP", .{}, arg);
return self.*;
}
pub fn setDragTypes(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "DRAGTYPES", .{}, arg);
return self.*;
}
///
/// TOOLBOX [Windows Only] (creation only): makes the dialog look like a
/// toolbox with a smaller title bar.
/// It is only valid if the PARENTDIALOG or NATIVEPARENT attribute is also defined.
/// Default: NO.
pub fn setToolBox(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "TOOLBOX", .{}, arg);
return self.*;
}
///
/// MDIFRAME (creation only) [Windows Only] (non inheritable): Configure this
/// dialog as a MDI frame.
/// Can be YES or NO.
/// Default: NO.
pub fn setMdiFrame(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "MDIFRAME", .{}, arg);
return self.*;
}
pub fn setFontStyle(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "FONTSTYLE", .{}, arg);
return self.*;
}
///
/// MDICHILD (creation only) [Windows Only]: Configure this dialog to be a MDI child.
/// Can be YES or NO.
/// The PARENTDIALOG attribute must also be defined.
/// Each MDI child is automatically named if it does not have one.
/// Default: NO.
pub fn setMdiChild(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "MDICHILD", .{}, arg);
return self.*;
}
///
/// FULLSCREEN: Makes the dialog occupy the whole screen over any system bars
/// in the main monitor.
/// All dialog details, such as title bar, borders, maximize button, etc, are removed.
/// Possible values: YES, NO.
/// In Motif you may have to click in the dialog to set its focus.
/// In Motif if set to YES when the dialog is hidden, then it can not be
/// changed after it is visible.
pub fn fullScreen(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "FULLSCREEN", .{}, arg);
return self.*;
}
///
/// NATIVEPARENT (creation only): Native handle of a dialog to be used as parent.
/// Used only if PARENTDIALOG is not defined.
pub fn setNativeParent(self: *Initializer, arg: anytype) !Initializer {
if (self.last_error) |_| return self.*;
interop.setHandleAttribute(self.ref, "NATIVEPARENT", .{}, arg);
return self.*;
}
pub fn setNativeParentHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "NATIVEPARENT", .{}, arg);
return self.*;
}
pub fn setFont(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "FONT", .{}, arg);
return self.*;
}
///
/// SIMULATEMODAL (write-only): disable all other visible dialogs, just like
/// when the dialog is made modal.
/// (since 3.21)
pub fn simulateModal(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "SIMULATEMODAL", .{}, arg);
return self.*;
}
///
/// TABIMAGEn (non inheritable): image name to be used in the respective tab.
/// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name.
/// n starts at 0.
/// See also IupImage.
/// In Motif, the image is shown only if TABTITLEn is NULL.
/// In Windows and Motif set the BGCOLOR attribute before setting the image.
/// When set after map will update the TABIMAGE attribute on the respective
/// child (since 3.10).
/// (since 3.0).
/// TABIMAGE (non inheritable) (at children only): Same as TABIMAGEn but set in
/// each child.
/// Works only if set before the child is added to the tabs.
pub fn setTabImage(self: *Initializer, index: i32, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "TABIMAGE", .{index}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setTabImageHandleName(self: *Initializer, index: i32, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TABIMAGE", .{index}, arg);
return self.*;
}
///
/// TABTITLEn (non inheritable): Contains the text to be shown in the
/// respective tab title.
/// n starts at 0.
/// If this value is NULL, it will remain empty.
/// The "&" character can be used to define a mnemonic, the next character will
/// be used as key.
/// Use "&&" to show the "&" character instead on defining a mnemonic.
/// The button can be activated from any control in the dialog using the
/// "Alt+key" combination.
/// (mnemonic support since 3.3).
/// When set after map will update the TABTITLE attribute on the respective
/// child (since 3.10).
/// (since 3.0).
/// TABTITLE (non inheritable) (at children only): Same as TABTITLEn but set in
/// each child.
/// Works only if set before the child is added to the tabs.
pub fn setTabTitle(self: *Initializer, index: i32, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TABTITLE", .{index}, arg);
return self.*;
}
///
/// FOCUS_CB: Called when the dialog or any of its children gets the focus, or
/// when another dialog or any control in another dialog gets the focus.
/// It is called after the common callbacks GETFOCUS_CB and KILL_FOCUS_CB.
/// (since 3.21) int function(Ihandle *ih, int focus); [in C]ih:focus_cb(focus:
/// number) -> (ret: number) [in Lua]
pub fn setFocusCallback(self: *Initializer, callback: ?OnFocusFn) Initializer {
const Handler = CallbackHandler(Self, OnFocusFn, "FOCUS_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// K_ANY K_ANY Action generated when a keyboard event occurs.
/// Callback int function(Ihandle *ih, int c); [in C] ih:k_any(c: number) ->
/// (ret: number) [in Lua] ih: identifier of the element that activated the event.
/// c: identifier of typed key.
/// Please refer to the Keyboard Codes table for a list of possible values.
/// Returns: If IUP_IGNORE is returned the key is ignored and not processed by
/// the control and not propagated.
/// If returns IUP_CONTINUE, the key will be processed and the event will be
/// propagated to the parent of the element receiving it, this is the default behavior.
/// If returns IUP_DEFAULT the key is processed but it is not propagated.
/// IUP_CLOSE will be processed.
/// Notes Keyboard callbacks depend on the keyboard usage of the control with
/// the focus.
/// So if you return IUP_IGNORE the control will usually not process the key.
/// But be aware that sometimes the control process the key in another event so
/// even returning IUP_IGNORE the key can get processed.
/// Although it will not be propagated.
/// IMPORTANT: The callbacks "K_*" of the dialog or native containers depend on
/// the IUP_CONTINUE return value to work while the control is in focus.
/// If the callback does not exists it is automatically propagated to the
/// parent of the element.
/// K_* callbacks All defined keys are also callbacks of any element, called
/// when the respective key is activated.
/// For example: "K_cC" is also a callback activated when the user press
/// Ctrl+C, when the focus is at the element or at a children with focus.
/// This is the way an application can create shortcut keys, also called hot keys.
/// These callbacks are not available in IupLua.
/// Affects All elements with keyboard interaction.
pub fn setKAnyCallback(self: *Initializer, callback: ?OnKAnyFn) Initializer {
const Handler = CallbackHandler(Self, OnKAnyFn, "K_ANY");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// HELP_CB HELP_CB Action generated when the user press F1 at a control.
/// In Motif is also activated by the Help button in some workstations keyboard.
/// Callback void function(Ihandle *ih); [in C] ih:help_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Returns: IUP_CLOSE will be processed.
/// Affects All elements with user interaction.
pub fn setHelpCallback(self: *Initializer, callback: ?OnHelpFn) Initializer {
const Handler = CallbackHandler(Self, OnHelpFn, "HELP_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// CLOSE_CB CLOSE_CB Called just before a dialog is closed when the user
/// clicks the close button of the title bar or an equivalent action.
/// Callback int function(Ihandle *ih); [in C] ih:close_cb() -> (ret: number)
/// [in Lua] ih: identifies the element that activated the event.
/// Returns: if IUP_IGNORE, it prevents the dialog from being closed.
/// If you destroy the dialog in this callback, you must return IUP_IGNORE.
/// IUP_CLOSE will be processed.
/// Affects IupDialog
pub fn setCloseCallback(self: *Initializer, callback: ?OnCloseFn) Initializer {
const Handler = CallbackHandler(Self, OnCloseFn, "CLOSE_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setDropMotionCallback(self: *Initializer, callback: ?OnDropMotionFn) Initializer {
const Handler = CallbackHandler(Self, OnDropMotionFn, "DROPMOTION_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setDragEndCallback(self: *Initializer, callback: ?OnDragEndFn) Initializer {
const Handler = CallbackHandler(Self, OnDragEndFn, "DRAGEND_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setDragBeginCallback(self: *Initializer, callback: ?OnDragBeginFn) Initializer {
const Handler = CallbackHandler(Self, OnDragBeginFn, "DRAGBEGIN_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// MAP_CB MAP_CB Called right after an element is mapped and its attributes
/// updated in IupMap.
/// When the element is a dialog, it is called after the layout is updated.
/// For all other elements is called before the layout is updated, so the
/// element current size will still be 0x0 during MAP_CB (since 3.14).
/// Callback int function(Ihandle *ih); [in C] ih:map_cb() -> (ret: number) [in
/// Lua] ih: identifier of the element that activated the event.
/// Affects All that have a native representation.
pub fn setMapCallback(self: *Initializer, callback: ?OnMapFn) Initializer {
const Handler = CallbackHandler(Self, OnMapFn, "MAP_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// ENTERWINDOW_CB ENTERWINDOW_CB Action generated when the mouse enters the
/// native element.
/// Callback int function(Ihandle *ih); [in C] ih:enterwindow_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// Notes When the cursor is moved from one element to another, the call order
/// in all platforms will be first the LEAVEWINDOW_CB callback of the old
/// control followed by the ENTERWINDOW_CB callback of the new control.
/// (since 3.14) If the mouse button is hold pressed and the cursor moves
/// outside the element the behavior is system dependent.
/// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in
/// GTK the callbacks are called.
/// Affects All controls with user interaction.
/// See Also LEAVEWINDOW_CB
pub fn setEnterWindowCallback(self: *Initializer, callback: ?OnEnterWindowFn) Initializer {
const Handler = CallbackHandler(Self, OnEnterWindowFn, "ENTERWINDOW_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// DESTROY_CB DESTROY_CB Called right before an element is destroyed.
/// Callback int function(Ihandle *ih); [in C] ih:destroy_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Notes If the dialog is visible then it is hidden before it is destroyed.
/// The callback will be called right after it is hidden.
/// The callback will be called before all other destroy procedures.
/// For instance, if the element has children then it is called before the
/// children are destroyed.
/// For language binding implementations use the callback name "LDESTROY_CB" to
/// release memory allocated by the binding for the element.
/// Also the callback will be called before the language callback.
/// Affects All.
pub fn setDestroyCallback(self: *Initializer, callback: ?OnDestroyFn) Initializer {
const Handler = CallbackHandler(Self, OnDestroyFn, "DESTROY_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setDropDataCallback(self: *Initializer, callback: ?OnDropDataFn) Initializer {
const Handler = CallbackHandler(Self, OnDropDataFn, "DROPDATA_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// KILLFOCUS_CB KILLFOCUS_CB Action generated when an element loses keyboard focus.
/// This callback is called before the GETFOCUS_CB of the element that gets the focus.
/// Callback int function(Ihandle *ih); [in C] ih:killfocus_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// Affects All elements with user interaction, except menus.
/// In Windows, there are restrictions when using this callback.
/// From MSDN on WM_KILLFOCUS: "While processing this message, do not make any
/// function calls that display or activate a window.
/// This causes the thread to yield control and can cause the application to
/// stop responding to messages.
/// See Also GETFOCUS_CB, IupGetFocus, IupSetFocus
pub fn setKillFocusCallback(self: *Initializer, callback: ?OnKillFocusFn) Initializer {
const Handler = CallbackHandler(Self, OnKillFocusFn, "KILLFOCUS_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setDragDataCallback(self: *Initializer, callback: ?OnDragDataFn) Initializer {
const Handler = CallbackHandler(Self, OnDragDataFn, "DRAGDATA_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setDragDataSizeCallback(self: *Initializer, callback: ?OnDragDataSizeFn) Initializer {
const Handler = CallbackHandler(Self, OnDragDataSizeFn, "DRAGDATASIZE_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// SHOW_CB SHOW_CB Called right after the dialog is showed, hidden, maximized,
/// minimized or restored from minimized/maximized.
/// This callback is called when those actions were performed by the user or
/// programmatically by the application.
/// Callback int function(Ihandle *ih, int state); [in C] ih:show_cb(state:
/// number) -> (ret: number) [in Lua] ih: identifier of the element that
/// activated the event.
/// state: indicates which of the following situations generated the event:
/// IUP_HIDE (since 3.0) IUP_SHOW IUP_RESTORE (was minimized or maximized)
/// IUP_MINIMIZE IUP_MAXIMIZE (since 3.0) (not received in Motif when activated
/// from the maximize button) Returns: IUP_CLOSE will be processed.
/// Affects IupDialog
pub fn setShowCallback(self: *Initializer, callback: ?OnShowFn) Initializer {
const Handler = CallbackHandler(Self, OnShowFn, "SHOW_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// DROPFILES_CB DROPFILES_CB Action called when a file is "dropped" into the control.
/// When several files are dropped at once, the callback is called several
/// times, once for each file.
/// If defined after the element is mapped then the attribute DROPFILESTARGET
/// must be set to YES.
/// [Windows and GTK Only] (GTK 2.6) Callback int function(Ihandle *ih, const
/// char* filename, int num, int x, int y); [in C] ih:dropfiles_cb(filename:
/// string; num, x, y: number) -> (ret: number) [in Lua] ih: identifier of the
/// element that activated the event.
/// filename: Name of the dropped file.
/// num: Number index of the dropped file.
/// If several files are dropped, num is the index of the dropped file starting
/// from "total-1" to "0".
/// x: X coordinate of the point where the user released the mouse button.
/// y: Y coordinate of the point where the user released the mouse button.
/// Returns: If IUP_IGNORE is returned the callback will NOT be called for the
/// next dropped files, and the processing of dropped files will be interrupted.
/// Affects IupDialog, IupCanvas, IupGLCanvas, IupText, IupList
pub fn setDropFilesCallback(self: *Initializer, callback: ?OnDropFilesFn) Initializer {
const Handler = CallbackHandler(Self, OnDropFilesFn, "DROPFILES_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// RESIZE_CB RESIZE_CB Action generated when the canvas or dialog size is changed.
/// Callback int function(Ihandle *ih, int width, int height); [in C]
/// ih:resize_cb(width, height: number) -> (ret: number) [in Lua] ih:
/// identifier of the element that activated the event.
/// width: the width of the internal element size in pixels not considering the
/// decorations (client size) height: the height of the internal element size
/// in pixels not considering the decorations (client size) Notes For the
/// dialog, this action is also generated when the dialog is mapped, after the
/// map and before the show.
/// When XAUTOHIDE=Yes or YAUTOHIDE=Yes, if the canvas scrollbar is
/// hidden/shown after changing the DX or DY attributes from inside the
/// callback, the size of the drawing area will immediately change, so the
/// parameters with and height will be invalid.
/// To update the parameters consult the DRAWSIZE attribute.
/// Also activate the drawing toolkit only after updating the DX or DY attributes.
/// Affects IupCanvas, IupGLCanvas, IupDialog
pub fn setResizeCallback(self: *Initializer, callback: ?OnResizeFn) Initializer {
const Handler = CallbackHandler(Self, OnResizeFn, "RESIZE_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// UNMAP_CB UNMAP_CB Called right before an element is unmapped.
/// Callback int function(Ihandle *ih); [in C] ih:unmap_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Affects All that have a native representation.
pub fn setUnmapCallback(self: *Initializer, callback: ?OnUnmapFn) Initializer {
const Handler = CallbackHandler(Self, OnUnmapFn, "UNMAP_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// TRAYCLICK_CB [Windows and GTK Only]: Called right after the mouse button is
/// pressed or released over the tray icon.
/// (GTK 2.10) int function(Ihandle *ih, int but, int pressed, int dclick); [in
/// C]elem:trayclick_cb(but, pressed, dclick: number) -> (ret: number) [in Lua]
pub fn setTrayClickCallback(self: *Initializer, callback: ?OnTrayClickFn) Initializer {
const Handler = CallbackHandler(Self, OnTrayClickFn, "TRAYCLICK_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// GETFOCUS_CB GETFOCUS_CB Action generated when an element is given keyboard focus.
/// This callback is called after the KILLFOCUS_CB of the element that loosed
/// the focus.
/// The IupGetFocus function during the callback returns the element that
/// loosed the focus.
/// Callback int function(Ihandle *ih); [in C] ih:getfocus_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that received keyboard focus.
/// Affects All elements with user interaction, except menus.
/// See Also KILLFOCUS_CB, IupGetFocus, IupSetFocus
pub fn setGetFocusCallback(self: *Initializer, callback: ?OnGetFocusFn) Initializer {
const Handler = CallbackHandler(Self, OnGetFocusFn, "GETFOCUS_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setLDestroyCallback(self: *Initializer, callback: ?OnLDestroyFn) Initializer {
const Handler = CallbackHandler(Self, OnLDestroyFn, "LDESTROY_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// LEAVEWINDOW_CB LEAVEWINDOW_CB Action generated when the mouse leaves the
/// native element.
/// Callback int function(Ihandle *ih); [in C] ih:leavewindow_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// Notes When the cursor is moved from one element to another, the call order
/// in all platforms will be first the LEAVEWINDOW_CB callback of the old
/// control followed by the ENTERWINDOW_CB callback of the new control.
/// (since 3.14) If the mouse button is hold pressed and the cursor moves
/// outside the element the behavior is system dependent.
/// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in
/// GTK the callbacks are called.
/// Affects All controls with user interaction.
/// See Also ENTERWINDOW_CB
pub fn setLeaveWindowCallback(self: *Initializer, callback: ?OnLeaveWindowFn) Initializer {
const Handler = CallbackHandler(Self, OnLeaveWindowFn, "LEAVEWINDOW_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setPostMessageCallback(self: *Initializer, callback: ?OnPostMessageFn) Initializer {
const Handler = CallbackHandler(Self, OnPostMessageFn, "POSTMESSAGE_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
};
pub fn setStrAttribute(self: *Self, attribute: [:0]const u8, arg: [:0]const u8) void {
interop.setStrAttribute(self, attribute, .{}, arg);
}
pub fn getStrAttribute(self: *Self, attribute: [:0]const u8) [:0]const u8 {
return interop.getStrAttribute(self, attribute, .{});
}
pub fn setIntAttribute(self: *Self, attribute: [:0]const u8, arg: i32) void {
interop.setIntAttribute(self, attribute, .{}, arg);
}
pub fn getIntAttribute(self: *Self, attribute: [:0]const u8) i32 {
return interop.getIntAttribute(self, attribute, .{});
}
pub fn setBoolAttribute(self: *Self, attribute: [:0]const u8, arg: bool) void {
interop.setBoolAttribute(self, attribute, .{}, arg);
}
pub fn getBoolAttribute(self: *Self, attribute: [:0]const u8) bool {
return interop.getBoolAttribute(self, attribute, .{});
}
pub fn getPtrAttribute(self: *Self, comptime T: type, attribute: [:0]const u8) ?*T {
return interop.getPtrAttribute(T, self, attribute, .{});
}
pub fn setPtrAttribute(self: *Self, comptime T: type, attribute: [:0]const u8, value: ?*T) void {
interop.setPtrAttribute(T, self, attribute, .{}, value);
}
pub fn setHandle(self: *Self, arg: [:0]const u8) void {
interop.setHandle(self, arg);
}
pub fn fromHandleName(handle_name: [:0]const u8) ?*Self {
return interop.fromHandleName(Self, handle_name);
}
///
/// Creates an interface element given its class name and parameters.
/// After creation the element still needs to be attached to a container and mapped to the native system so it can be visible.
pub fn init() Initializer {
var handle = interop.create(Self);
if (handle) |valid| {
return .{
.ref = @ptrCast(*Self, valid),
};
} else {
return .{ .ref = undefined, .last_error = Error.NotInitialized };
}
}
///
/// Displays a dialog in the current position, or changes a control VISIBLE attribute.
/// For dialogs it is equivalent to call IupShowXY using IUP_CURRENT. See IupShowXY for more details.
/// For other controls, to call IupShow is the same as setting VISIBLE=YES.
pub fn show(self: *Self) !void {
try interop.show(self);
}
///
/// Hides an interface element. This function has the same effect as attributing value "NO" to the interface element’s VISIBLE attribute.
/// Once a dialog is hidden, either by means of IupHide or by changing the VISIBLE attribute or by means of a click in the window close button, the elements inside this dialog are not destroyed, so that you can show the dialog again. To destroy dialogs, the IupDestroy function must be called.
pub fn hide(self: *Self) void {
interop.hide(self);
}
///
/// Destroys an interface element and all its children.
/// Only dialogs, timers, popup menus and images should be normally destroyed, but detached elements can also be destroyed.
pub fn deinit(self: *Self) void {
interop.destroy(self);
}
///
/// Creates (maps) the native interface objects corresponding to the given IUP interface elements.
/// It will also called recursively to create the native element of all the children in the element's tree.
/// The element must be already attached to a mapped container, except the dialog. A child can only be mapped if its parent is already mapped.
/// This function is automatically called before the dialog is shown in IupShow, IupShowXY or IupPopup.
/// If the element is a dialog then the abstract layout will be updated even if the dialog is already mapped. If the dialog is visible the elements will be immediately repositioned. Calling IupMap for an already mapped dialog is the same as only calling IupRefresh for the dialog.
/// Calling IupMap for an already mapped element that is not a dialog does nothing.
/// If you add new elements to an already mapped dialog you must call IupMap for that elements. And then call IupRefresh to update the dialog layout.
/// If the WID attribute of an element is NULL, it means the element was not already mapped. Some containers do not have a native element associated, like VBOX and HBOX. In this case their WID is a fake value (void*)(-1).
/// It is useful for the application to call IupMap when the value of the WID attribute must be known, i.e. the native element must exist, before a dialog is made visible.
/// The MAP_CB callback is called at the end of the IupMap function, after all processing, so it can also be used to create other things that depend on the WID attribute. But notice that for non dialog elements it will be called before the dialog layout has been updated, so the element current size will still be 0x0 (since 3.14).
pub fn map(self: *Self) !void {
try interop.map(self);
}
///
/// Adds a tuple of children
pub fn appendChildren(self: *Self, tuple: anytype) !void {
try Impl(Self).appendChildren(self, tuple);
}
///
/// Appends a child on this container
/// child must be an Element or
pub fn appendChild(self: *Self, child: anytype) !void {
try Impl(Self).appendChild(self, child);
}
///
/// Returns a iterator for children elements.
pub fn children(self: *Self) ChildrenIterator {
return ChildrenIterator.init(self);
}
pub fn popup(self: *Self, x: iup.DialogPosX, y: iup.DialogPosY) !void {
try interop.popup(self, x, y);
}
pub fn showXY(self: *Self, x: iup.DialogPosX, y: iup.DialogPosY) !void {
try interop.showXY(self, x, y);
}
///
/// Returns the the child element that has the NAME attribute equals to the given value on the same dialog hierarchy.
/// Works also for children of a menu that is associated with a dialog.
pub fn getDialogChild(self: *Self, byName: [:0]const u8) ?Element {
return interop.getDialogChild(self, byName);
}
///
/// Updates the size and layout of all controls in the same dialog.
/// To be used after changing size attributes, or attributes that affect the size of the control. Can be used for any element inside a dialog, but the layout of the dialog and all controls will be updated. It can change the layout of all the controls inside the dialog because of the dynamic layout positioning.
pub fn refresh(self: *Self) void {
Impl(Self).refresh(self);
}
pub fn getHandleName(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "HANDLENAME", .{});
}
pub fn setHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "HANDLENAME", .{}, arg);
}
pub fn getTipBgColor(self: *Self) ?iup.Rgb {
return interop.getRgb(self, "TIPBGCOLOR", .{});
}
pub fn setTipBgColor(self: *Self, rgb: iup.Rgb) void {
interop.setRgb(self, "TIPBGCOLOR", .{}, rgb);
}
pub fn getTipIcon(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "TIPICON", .{});
}
pub fn setTipIcon(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TIPICON", .{}, arg);
}
///
/// MENU: Name of a menu.
/// Associates a menu to the dialog as a menu bar.
/// The previous menu, if any, is unmapped.
/// Use IupSetHandle or IupSetAttributeHandle to associate a menu to a name.
/// See also IupMenu.
pub fn getMenu(self: *Self) ?*iup.Menu {
if (interop.getHandleAttribute(self, "MENU", .{})) |handle| {
return @ptrCast(*iup.Menu, handle);
} else {
return null;
}
}
///
/// MENU: Name of a menu.
/// Associates a menu to the dialog as a menu bar.
/// The previous menu, if any, is unmapped.
/// Use IupSetHandle or IupSetAttributeHandle to associate a menu to a name.
/// See also IupMenu.
pub fn setMenu(self: *Self, arg: *iup.Menu) void {
interop.setHandleAttribute(self, "MENU", .{}, arg);
}
pub fn setMenuHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "MENU", .{}, arg);
}
pub fn getNoFlush(self: *Self) bool {
return interop.getBoolAttribute(self, "NOFLUSH", .{});
}
pub fn setNoFlush(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "NOFLUSH", .{}, arg);
}
///
/// MAXSIZE: Maximum size for the dialog in raster units (pixels).
/// The windowing system will not be able to change the size beyond this limit.
/// Default: 65535x65535.
/// (since 3.0)
pub fn getMaxSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "MAXSIZE", .{});
return Size.parse(str);
}
///
/// MAXSIZE: Maximum size for the dialog in raster units (pixels).
/// The windowing system will not be able to change the size beyond this limit.
/// Default: 65535x65535.
/// (since 3.0)
pub fn setMaxSize(self: *Self, width: ?i32, height: ?i32) void {
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self, "MAXSIZE", .{}, value);
}
///
/// OPACITYIMAGE [Windows Only]: sets an RGBA image as the dialog background so
/// it is possible to create a non rectangle window with transparency, but it
/// can not have children.
/// Used usually for splash screens.
/// It must be set before map so the native window would be properly
/// initialized when mapped.
/// Works also for GTK but as the SHAPEIMAGE attribute.
/// (since 3.16)
pub fn getOpacityImage(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "OPACITYIMAGE", .{});
}
///
/// OPACITYIMAGE [Windows Only]: sets an RGBA image as the dialog background so
/// it is possible to create a non rectangle window with transparency, but it
/// can not have children.
/// Used usually for splash screens.
/// It must be set before map so the native window would be properly
/// initialized when mapped.
/// Works also for GTK but as the SHAPEIMAGE attribute.
/// (since 3.16)
pub fn setOpacityImage(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "OPACITYIMAGE", .{}, arg);
}
///
/// SHOWNOFOCUS: do not set focus after show.
/// (since 3.30)
pub fn getShowNoFocus(self: *Self) bool {
return interop.getBoolAttribute(self, "SHOWNOFOCUS", .{});
}
///
/// SHOWNOFOCUS: do not set focus after show.
/// (since 3.30)
pub fn setShowNoFocus(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "SHOWNOFOCUS", .{}, arg);
}
pub fn getScreenPosition(self: *Self) iup.XYPos {
var str = interop.getStrAttribute(self, "SCREENPOSITION", .{});
return iup.XYPos.parse(str, ',');
}
///
/// OPACITY [Windows and GTK Only]: sets the dialog transparency alpha value.
/// Valid values range from 0 (completely transparent) to 255 (opaque).
/// In Windows must be set before map so the native window would be properly
/// initialized when mapped (since 3.16).
/// (GTK 2.12)
pub fn getOpacity(self: *Self) i32 {
return interop.getIntAttribute(self, "OPACITY", .{});
}
///
/// OPACITY [Windows and GTK Only]: sets the dialog transparency alpha value.
/// Valid values range from 0 (completely transparent) to 255 (opaque).
/// In Windows must be set before map so the native window would be properly
/// initialized when mapped (since 3.16).
/// (GTK 2.12)
pub fn setOpacity(self: *Self, arg: i32) void {
interop.setIntAttribute(self, "OPACITY", .{}, arg);
}
pub fn getPosition(self: *Self) iup.XYPos {
var str = interop.getStrAttribute(self, "POSITION", .{});
return iup.XYPos.parse(str, ',');
}
pub fn setPosition(self: *Self, x: i32, y: i32) void {
var buffer: [128]u8 = undefined;
var value = iup.XYPos.intIntToString(&buffer, x, y, ',');
interop.setStrAttribute(self, "POSITION", .{}, value);
}
///
/// DROPFILESTARGET [Windows and GTK Only] (non inheritable): Enable or disable
/// the drop of files.
/// Default: NO, but if DROPFILES_CB is defined when the element is mapped then
/// it will be automatically enabled.
pub fn getDropFilesTarget(self: *Self) bool {
return interop.getBoolAttribute(self, "DROPFILESTARGET", .{});
}
///
/// DROPFILESTARGET [Windows and GTK Only] (non inheritable): Enable or disable
/// the drop of files.
/// Default: NO, but if DROPFILES_CB is defined when the element is mapped then
/// it will be automatically enabled.
pub fn setDropFilesTarget(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "DROPFILESTARGET", .{}, arg);
}
///
/// BORDERSIZE (non inheritable) (read only): returns the border size.
/// (since 3.18)
pub fn getBorderSize(self: *Self) i32 {
return interop.getIntAttribute(self, "BORDERSIZE", .{});
}
pub fn getTip(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "TIP", .{});
}
pub fn setTip(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TIP", .{}, arg);
}
pub fn getCanFocus(self: *Self) bool {
return interop.getBoolAttribute(self, "CANFOCUS", .{});
}
pub fn setCanFocus(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "CANFOCUS", .{}, arg);
}
pub fn getDragSourceMove(self: *Self) bool {
return interop.getBoolAttribute(self, "DRAGSOURCEMOVE", .{});
}
pub fn setDragSourceMove(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "DRAGSOURCEMOVE", .{}, arg);
}
///
/// ICON: Dialogs icon.
/// The Windows SDK recommends that cursors and icons should be implemented as
/// resources rather than created at run time.
pub fn getIcon(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "ICON", .{});
}
///
/// ICON: Dialogs icon.
/// The Windows SDK recommends that cursors and icons should be implemented as
/// resources rather than created at run time.
pub fn setIcon(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "ICON", .{}, arg);
}
///
/// VISIBLE: Simply call IupShow or IupHide for the dialog.
pub fn getVisible(self: *Self) bool {
return interop.getBoolAttribute(self, "VISIBLE", .{});
}
///
/// VISIBLE: Simply call IupShow or IupHide for the dialog.
pub fn setVisible(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "VISIBLE", .{}, arg);
}
///
/// CURSOR (non inheritable): Defines a cursor for the dialog.
pub fn getCursor(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "CURSOR", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// CURSOR (non inheritable): Defines a cursor for the dialog.
pub fn setCursor(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "CURSOR", .{}, arg);
}
pub fn setCursorHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "CURSOR", .{}, arg);
}
pub fn zOrder(self: *Self, arg: ?ZOrder) void {
if (arg) |value| switch (value) {
.Top => interop.setStrAttribute(self, "ZORDER", .{}, "TOP"),
.Bottom => interop.setStrAttribute(self, "ZORDER", .{}, "BOTTOM"),
} else {
interop.clearAttribute(self, "ZORDER", .{});
}
}
pub fn getX(self: *Self) i32 {
return interop.getIntAttribute(self, "X", .{});
}
pub fn getY(self: *Self) i32 {
return interop.getIntAttribute(self, "Y", .{});
}
///
/// HIDETITLEBAR [GTK Only] (non inheritable): hides the title bar with al its elements.
/// (since 3.20) (GTK 3.10)
pub fn getHideTitleBar(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "HIDETITLEBAR", .{});
}
///
/// HIDETITLEBAR [GTK Only] (non inheritable): hides the title bar with al its elements.
/// (since 3.20) (GTK 3.10)
pub fn setHideTitleBar(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "HIDETITLEBAR", .{}, arg);
}
pub fn getDragDrop(self: *Self) bool {
return interop.getBoolAttribute(self, "DRAGDROP", .{});
}
pub fn setDragDrop(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "DRAGDROP", .{}, arg);
}
///
/// DIALOGHINT [GTK Only] (creation-only): if enabled sets the window type hint
/// to a dialog hint.
pub fn getDialogHint(self: *Self) bool {
return interop.getBoolAttribute(self, "DIALOGHINT", .{});
}
///
/// DIALOGHINT [GTK Only] (creation-only): if enabled sets the window type hint
/// to a dialog hint.
pub fn setDialogHint(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "DIALOGHINT", .{}, arg);
}
///
/// DIALOGFRAME: Set the common decorations for modal dialogs.
/// This means RESIZE=NO, MINBOX=NO and MAXBOX=NO.
/// In Windows, if the PARENTDIALOG is defined then the MENUBOX is also
/// removed, but the Close button remains.
pub fn getDialogFrame(self: *Self) bool {
return interop.getBoolAttribute(self, "DIALOGFRAME", .{});
}
///
/// DIALOGFRAME: Set the common decorations for modal dialogs.
/// This means RESIZE=NO, MINBOX=NO and MAXBOX=NO.
/// In Windows, if the PARENTDIALOG is defined then the MENUBOX is also
/// removed, but the Close button remains.
pub fn setDialogFrame(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "DIALOGFRAME", .{}, arg);
}
///
/// NACTIVE (non inheritable): same as ACTIVE but does not affects the controls
/// inside the dialog.
/// (since 3.13)
pub fn getNActive(self: *Self) bool {
return interop.getBoolAttribute(self, "NACTIVE", .{});
}
///
/// NACTIVE (non inheritable): same as ACTIVE but does not affects the controls
/// inside the dialog.
/// (since 3.13)
pub fn setNActive(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "NACTIVE", .{}, arg);
}
pub fn getTheme(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "THEME", .{});
}
pub fn setTheme(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "THEME", .{}, arg);
}
///
/// TRAY [Windows and GTK Only]: When set to "YES", displays an icon on the
/// system tray.
/// (GTK 2.10 and GTK < 3.14)
pub fn getTray(self: *Self) bool {
return interop.getBoolAttribute(self, "TRAY", .{});
}
///
/// TRAY [Windows and GTK Only]: When set to "YES", displays an icon on the
/// system tray.
/// (GTK 2.10 and GTK < 3.14)
pub fn setTray(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "TRAY", .{}, arg);
}
///
/// CHILDOFFSET: Allow to specify a position offset for the child.
/// Available for native containers only.
/// It will not affect the natural size, and allows to position controls
/// outside the client area.
/// Format "dxxdy", where dx and dy are integer values corresponding to the
/// horizontal and vertical offsets, respectively, in pixels.
/// Default: 0x0.
/// (since 3.14)
pub fn getChildOffset(self: *Self) Size {
var str = interop.getStrAttribute(self, "CHILDOFFSET", .{});
return Size.parse(str);
}
///
/// CHILDOFFSET: Allow to specify a position offset for the child.
/// Available for native containers only.
/// It will not affect the natural size, and allows to position controls
/// outside the client area.
/// Format "dxxdy", where dx and dy are integer values corresponding to the
/// horizontal and vertical offsets, respectively, in pixels.
/// Default: 0x0.
/// (since 3.14)
pub fn setChildOffset(self: *Self, width: ?i32, height: ?i32) void {
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self, "CHILDOFFSET", .{}, value);
}
///
/// EXPAND (non inheritable): The default value is "YES".
pub fn getExpand(self: *Self) ?Expand {
var ret = interop.getStrAttribute(self, "EXPAND", .{});
if (std.ascii.eqlIgnoreCase("YES", ret)) return .Yes;
if (std.ascii.eqlIgnoreCase("HORIZONTAL", ret)) return .Horizontal;
if (std.ascii.eqlIgnoreCase("VERTICAL", ret)) return .Vertical;
if (std.ascii.eqlIgnoreCase("HORIZONTALFREE", ret)) return .HorizontalFree;
if (std.ascii.eqlIgnoreCase("VERTICALFREE", ret)) return .VerticalFree;
if (std.ascii.eqlIgnoreCase("NO", ret)) return .No;
return null;
}
///
/// EXPAND (non inheritable): The default value is "YES".
pub fn setExpand(self: *Self, arg: ?Expand) void {
if (arg) |value| switch (value) {
.Yes => interop.setStrAttribute(self, "EXPAND", .{}, "YES"),
.Horizontal => interop.setStrAttribute(self, "EXPAND", .{}, "HORIZONTAL"),
.Vertical => interop.setStrAttribute(self, "EXPAND", .{}, "VERTICAL"),
.HorizontalFree => interop.setStrAttribute(self, "EXPAND", .{}, "HORIZONTALFREE"),
.VerticalFree => interop.setStrAttribute(self, "EXPAND", .{}, "VERTICALFREE"),
.No => interop.setStrAttribute(self, "EXPAND", .{}, "NO"),
} else {
interop.clearAttribute(self, "EXPAND", .{});
}
}
///
/// SIZE (non inheritable): Dialogs size.
/// Additionally the following values can also be defined for width and/or
/// height: "FULL": Defines the dialogs width (or height) equal to the screen's
/// width (or height) "HALF": Defines the dialogs width (or height) equal to
/// half the screen's width (or height) "THIRD": Defines the dialogs width (or
/// height) equal to 1/3 the screen's width (or height) "QUARTER": Defines the
/// dialogs width (or height) equal to 1/4 of the screen's width (or height)
/// "EIGHTH": Defines the dialogs width (or height) equal to 1/8 of the
/// screen's width (or height).
/// Values set at SIZE or RASTERSIZE attributes of a dialog are always
/// accepted, regardless of the minimum size required by its children.
/// For a dialog to have the minimum necessary size to fit all elements
/// contained in it, simply define SIZE or RASTERSIZE to NULL.
/// Also if you set SIZE or RASTERSIZE to be used as the initial size of the
/// dialog, its contents will be limited to this size as the minimum size, if
/// you do not want that, then after showing the dialog reset this size to NULL
/// so the dialog can be resized to smaller values.
/// But notice that its contents will still be limited by the Natural size, to
/// also remove that limitation set SHRINK=YES.
/// To only change the User size in pixels, without resetting the Current size,
/// set the USERSIZE attribute (since 3.12).
/// Values set at SIZE or RASTERSIZE attributes of a dialog are always
/// accepted, regardless of the minimum size required by its children.
/// For a dialog to have the minimum necessary size to fit all elements
/// contained in it, simply define SIZE or RASTERSIZE to NULL.
/// Also if you set SIZE or RASTERSIZE to be used as the initial size of the
/// dialog, its contents will be limited to this size as the minimum size, if
/// you do not want that, then after showing the dialog reset this size to NULL
/// so the dialog can be resized to smaller values.
/// But notice that its contents will still be limited by the Natural size, to
/// also remove that limitation set SHRINK=YES.
/// To only change the User size in pixels, without resetting the Current size,
/// set the USERSIZE attribute (since 3.12).
/// Values set at SIZE or RASTERSIZE attributes of a dialog are always
/// accepted, regardless of the minimum size required by its children.
/// For a dialog to have the minimum necessary size to fit all elements
/// contained in it, simply define SIZE or RASTERSIZE to NULL.
/// Also if you set SIZE or RASTERSIZE to be used as the initial size of the
/// dialog, its contents will be limited to this size as the minimum size, if
/// you do not want that, then after showing the dialog reset this size to NULL
/// so the dialog can be resized to smaller values.
/// But notice that its contents will still be limited by the Natural size, to
/// also remove that limitation set SHRINK=YES.
/// To only change the User size in pixels, without resetting the Current size,
/// set the USERSIZE attribute (since 3.12).
pub fn getSize(self: *Self) iup.DialogSize {
var str = interop.getStrAttribute(self, "SIZE", .{});
return iup.DialogSize.parse(str);
}
///
/// SIZE (non inheritable): Dialogs size.
/// Additionally the following values can also be defined for width and/or
/// height: "FULL": Defines the dialogs width (or height) equal to the screen's
/// width (or height) "HALF": Defines the dialogs width (or height) equal to
/// half the screen's width (or height) "THIRD": Defines the dialogs width (or
/// height) equal to 1/3 the screen's width (or height) "QUARTER": Defines the
/// dialogs width (or height) equal to 1/4 of the screen's width (or height)
/// "EIGHTH": Defines the dialogs width (or height) equal to 1/8 of the
/// screen's width (or height).
/// Values set at SIZE or RASTERSIZE attributes of a dialog are always
/// accepted, regardless of the minimum size required by its children.
/// For a dialog to have the minimum necessary size to fit all elements
/// contained in it, simply define SIZE or RASTERSIZE to NULL.
/// Also if you set SIZE or RASTERSIZE to be used as the initial size of the
/// dialog, its contents will be limited to this size as the minimum size, if
/// you do not want that, then after showing the dialog reset this size to NULL
/// so the dialog can be resized to smaller values.
/// But notice that its contents will still be limited by the Natural size, to
/// also remove that limitation set SHRINK=YES.
/// To only change the User size in pixels, without resetting the Current size,
/// set the USERSIZE attribute (since 3.12).
/// Values set at SIZE or RASTERSIZE attributes of a dialog are always
/// accepted, regardless of the minimum size required by its children.
/// For a dialog to have the minimum necessary size to fit all elements
/// contained in it, simply define SIZE or RASTERSIZE to NULL.
/// Also if you set SIZE or RASTERSIZE to be used as the initial size of the
/// dialog, its contents will be limited to this size as the minimum size, if
/// you do not want that, then after showing the dialog reset this size to NULL
/// so the dialog can be resized to smaller values.
/// But notice that its contents will still be limited by the Natural size, to
/// also remove that limitation set SHRINK=YES.
/// To only change the User size in pixels, without resetting the Current size,
/// set the USERSIZE attribute (since 3.12).
/// Values set at SIZE or RASTERSIZE attributes of a dialog are always
/// accepted, regardless of the minimum size required by its children.
/// For a dialog to have the minimum necessary size to fit all elements
/// contained in it, simply define SIZE or RASTERSIZE to NULL.
/// Also if you set SIZE or RASTERSIZE to be used as the initial size of the
/// dialog, its contents will be limited to this size as the minimum size, if
/// you do not want that, then after showing the dialog reset this size to NULL
/// so the dialog can be resized to smaller values.
/// But notice that its contents will still be limited by the Natural size, to
/// also remove that limitation set SHRINK=YES.
/// To only change the User size in pixels, without resetting the Current size,
/// set the USERSIZE attribute (since 3.12).
pub fn setSize(self: *Self, width: ?iup.ScreenSize, height: ?iup.ScreenSize) void {
var buffer: [128]u8 = undefined;
var str = iup.DialogSize.screenSizeToString(&buffer, width, height);
interop.setStrAttribute(self, "SIZE", .{}, str);
}
pub fn getWId(self: *Self) i32 {
return interop.getIntAttribute(self, "WID", .{});
}
pub fn getTipMarkup(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "TIPMARKUP", .{});
}
pub fn setTipMarkup(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TIPMARKUP", .{}, arg);
}
///
/// STARTFOCUS: Name of the element that must receive the focus right after the
/// dialog is shown using IupShow or IupPopup.
/// If not defined then the first control than can receive the focus is
/// selected (same effect of calling IupNextField for the dialog).
/// Updated after SHOW_CB is called and only if the focus was not changed
/// during the callback.
pub fn getStartFocus(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "STARTFOCUS", .{});
}
///
/// STARTFOCUS: Name of the element that must receive the focus right after the
/// dialog is shown using IupShow or IupPopup.
/// If not defined then the first control than can receive the focus is
/// selected (same effect of calling IupNextField for the dialog).
/// Updated after SHOW_CB is called and only if the focus was not changed
/// during the callback.
pub fn setStartFocus(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "STARTFOCUS", .{}, arg);
}
pub fn getFontSize(self: *Self) i32 {
return interop.getIntAttribute(self, "FONTSIZE", .{});
}
pub fn setFontSize(self: *Self, arg: i32) void {
interop.setIntAttribute(self, "FONTSIZE", .{}, arg);
}
pub fn getNaturalSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "NATURALSIZE", .{});
return Size.parse(str);
}
pub fn getDropTypes(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "DROPTYPES", .{});
}
pub fn setDropTypes(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "DROPTYPES", .{}, arg);
}
///
/// TRAYTIPMARKUP [GTK Only]: allows the tip string to contains Pango markup commands.
/// Can be "YES" or "NO".
/// Default: "NO".
/// Must be set before setting the TRAYTIP attribute.
/// (GTK 2.16) (since 3.6)
pub fn getTrayTipMarkup(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "TRAYTIPMARKUP", .{});
}
///
/// TRAYTIPMARKUP [GTK Only]: allows the tip string to contains Pango markup commands.
/// Can be "YES" or "NO".
/// Default: "NO".
/// Must be set before setting the TRAYTIP attribute.
/// (GTK 2.16) (since 3.6)
pub fn setTrayTipMarkup(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TRAYTIPMARKUP", .{}, arg);
}
pub fn getUserSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "USERSIZE", .{});
return Size.parse(str);
}
pub fn setUserSize(self: *Self, width: ?i32, height: ?i32) void {
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self, "USERSIZE", .{}, value);
}
pub fn getTipDelay(self: *Self) i32 {
return interop.getIntAttribute(self, "TIPDELAY", .{});
}
pub fn setTipDelay(self: *Self, arg: i32) void {
interop.setIntAttribute(self, "TIPDELAY", .{}, arg);
}
///
/// CUSTOMFRAME [Windows and GTK Only] (non inheritable): allows the
/// application to customize the dialog frame elements (the title and its
/// buttons) by using IUP controls for its elements like caption, minimize
/// button, maximize button, and close buttons.
/// The custom frame support uses the native system support for custom frames.
/// The application is responsible for leaving space for the borders.
/// One drawback is that menu bars will not work.
/// For the dialog to be able to be moved an IupLabel or an IupCanvas must be
/// at the top of the dialog and must have the NAME attribute set to
/// CUSTOMFRAMECAPTION (since 3.22).
/// Native custom frames are supported only in Windows and in GTK version 3.10,
/// so for older GTK versions we have to simulate the support using CUSTOMFRAMESIMULATE.
/// (since 3.18) (renamed in 3.22) (GTK support since 3.22) See the Custom
/// Frame notes bellow.
pub fn getCustomFrame(self: *Self) bool {
return interop.getBoolAttribute(self, "CUSTOMFRAME", .{});
}
///
/// CUSTOMFRAME [Windows and GTK Only] (non inheritable): allows the
/// application to customize the dialog frame elements (the title and its
/// buttons) by using IUP controls for its elements like caption, minimize
/// button, maximize button, and close buttons.
/// The custom frame support uses the native system support for custom frames.
/// The application is responsible for leaving space for the borders.
/// One drawback is that menu bars will not work.
/// For the dialog to be able to be moved an IupLabel or an IupCanvas must be
/// at the top of the dialog and must have the NAME attribute set to
/// CUSTOMFRAMECAPTION (since 3.22).
/// Native custom frames are supported only in Windows and in GTK version 3.10,
/// so for older GTK versions we have to simulate the support using CUSTOMFRAMESIMULATE.
/// (since 3.18) (renamed in 3.22) (GTK support since 3.22) See the Custom
/// Frame notes bellow.
pub fn setCustomFrame(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "CUSTOMFRAME", .{}, arg);
}
///
/// TITLE (non inheritable): Dialogs title.
/// Default: NULL.
/// If you want to remove the title bar you must also set MENUBOX=NO, MAXBOX=NO
/// and MINBOX=NO, before map.
/// But in Motif and GTK it will hide it only if RESIZE=NO also.
pub fn getTitle(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "TITLE", .{});
}
///
/// TITLE (non inheritable): Dialogs title.
/// Default: NULL.
/// If you want to remove the title bar you must also set MENUBOX=NO, MAXBOX=NO
/// and MINBOX=NO, before map.
/// But in Motif and GTK it will hide it only if RESIZE=NO also.
pub fn setTitle(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TITLE", .{}, arg);
}
///
/// DEFAULTESC: Name of the button activated when the user press Esc when focus
/// is in another control of the dialog.
/// Use IupSetHandle or IupSetAttributeHandle to associate a button to a name.
pub fn getDefaultEsc(self: *Self) ?*iup.Button {
if (interop.getHandleAttribute(self, "DEFAULTESC", .{})) |handle| {
return @ptrCast(*iup.Button, handle);
} else {
return null;
}
}
///
/// DEFAULTESC: Name of the button activated when the user press Esc when focus
/// is in another control of the dialog.
/// Use IupSetHandle or IupSetAttributeHandle to associate a button to a name.
pub fn setDefaultEsc(self: *Self, arg: *iup.Button) void {
interop.setHandleAttribute(self, "DEFAULTESC", .{}, arg);
}
pub fn setDefaultEscHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "DEFAULTESC", .{}, arg);
}
///
/// PLACEMENT: Changes how the dialog will be shown.
/// Values: "FULL", "MAXIMIZED", "MINIMIZED" and "NORMAL".
/// Default: NORMAL.
/// After IupShow/IupPopup the attribute is set back to "NORMAL".
/// FULL is similar to FULLSCREEN but only the dialog client area covers the
/// screen area, menu and decorations will be there but out of the screen.
/// In UNIX there is a chance that the placement won't work correctly, that
/// depends on the Window Manager.
/// In Windows, the SHOWNOACTIVATE attribute can be set to Yes to prevent the
/// window from being activated (since 3.15).
/// In Windows, the SHOWMINIMIZENEXT attribute can be set to Yes to activate
/// the next top-level window in the Z order when minimizing (since 3.15).
pub fn getPlacement(self: *Self) ?Placement {
var ret = interop.getStrAttribute(self, "PLACEMENT", .{});
if (std.ascii.eqlIgnoreCase("MAXIMIZED", ret)) return .Maximized;
if (std.ascii.eqlIgnoreCase("MINIMIZED", ret)) return .Minimized;
if (std.ascii.eqlIgnoreCase("FULL", ret)) return .Full;
return null;
}
///
/// PLACEMENT: Changes how the dialog will be shown.
/// Values: "FULL", "MAXIMIZED", "MINIMIZED" and "NORMAL".
/// Default: NORMAL.
/// After IupShow/IupPopup the attribute is set back to "NORMAL".
/// FULL is similar to FULLSCREEN but only the dialog client area covers the
/// screen area, menu and decorations will be there but out of the screen.
/// In UNIX there is a chance that the placement won't work correctly, that
/// depends on the Window Manager.
/// In Windows, the SHOWNOACTIVATE attribute can be set to Yes to prevent the
/// window from being activated (since 3.15).
/// In Windows, the SHOWMINIMIZENEXT attribute can be set to Yes to activate
/// the next top-level window in the Z order when minimizing (since 3.15).
pub fn setPlacement(self: *Self, arg: ?Placement) void {
if (arg) |value| switch (value) {
.Maximized => interop.setStrAttribute(self, "PLACEMENT", .{}, "MAXIMIZED"),
.Minimized => interop.setStrAttribute(self, "PLACEMENT", .{}, "MINIMIZED"),
.Full => interop.setStrAttribute(self, "PLACEMENT", .{}, "FULL"),
} else {
interop.clearAttribute(self, "PLACEMENT", .{});
}
}
pub fn getPropagateFocus(self: *Self) bool {
return interop.getBoolAttribute(self, "PROPAGATEFOCUS", .{});
}
pub fn setPropagateFocus(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "PROPAGATEFOCUS", .{}, arg);
}
pub fn getBgColor(self: *Self) ?iup.Rgb {
return interop.getRgb(self, "BGCOLOR", .{});
}
pub fn setBgColor(self: *Self, rgb: iup.Rgb) void {
interop.setRgb(self, "BGCOLOR", .{}, rgb);
}
pub fn getDropTarget(self: *Self) bool {
return interop.getBoolAttribute(self, "DROPTARGET", .{});
}
pub fn setDropTarget(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "DROPTARGET", .{}, arg);
}
pub fn getDragSource(self: *Self) bool {
return interop.getBoolAttribute(self, "DRAGSOURCE", .{});
}
pub fn setDragSource(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "DRAGSOURCE", .{}, arg);
}
///
/// MAXIMIZED [Windows and GTK Only] (read-only): indicates if the dialog is maximized.
/// Can be YES or NO.
/// (since 3.12)
pub fn getMaximized(self: *Self) bool {
return interop.getBoolAttribute(self, "MAXIMIZED", .{});
}
pub fn getFloating(self: *Self) ?Floating {
var ret = interop.getStrAttribute(self, "FLOATING", .{});
if (std.ascii.eqlIgnoreCase("YES", ret)) return .Yes;
if (std.ascii.eqlIgnoreCase("IGNORE", ret)) return .Ignore;
if (std.ascii.eqlIgnoreCase("NO", ret)) return .No;
return null;
}
pub fn setFloating(self: *Self, arg: ?Floating) void {
if (arg) |value| switch (value) {
.Yes => interop.setStrAttribute(self, "FLOATING", .{}, "YES"),
.Ignore => interop.setStrAttribute(self, "FLOATING", .{}, "IGNORE"),
.No => interop.setStrAttribute(self, "FLOATING", .{}, "NO"),
} else {
interop.clearAttribute(self, "FLOATING", .{});
}
}
pub fn getNormalizerGroup(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "NORMALIZERGROUP", .{});
}
pub fn setNormalizerGroup(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "NORMALIZERGROUP", .{}, arg);
}
///
/// Values set at SIZE or RASTERSIZE attributes of a dialog are always
/// accepted, regardless of the minimum size required by its children.
/// For a dialog to have the minimum necessary size to fit all elements
/// contained in it, simply define SIZE or RASTERSIZE to NULL.
/// Also if you set SIZE or RASTERSIZE to be used as the initial size of the
/// dialog, its contents will be limited to this size as the minimum size, if
/// you do not want that, then after showing the dialog reset this size to NULL
/// so the dialog can be resized to smaller values.
/// But notice that its contents will still be limited by the Natural size, to
/// also remove that limitation set SHRINK=YES.
/// To only change the User size in pixels, without resetting the Current size,
/// set the USERSIZE attribute (since 3.12).
/// Values set at SIZE or RASTERSIZE attributes of a dialog are always
/// accepted, regardless of the minimum size required by its children.
/// For a dialog to have the minimum necessary size to fit all elements
/// contained in it, simply define SIZE or RASTERSIZE to NULL.
/// Also if you set SIZE or RASTERSIZE to be used as the initial size of the
/// dialog, its contents will be limited to this size as the minimum size, if
/// you do not want that, then after showing the dialog reset this size to NULL
/// so the dialog can be resized to smaller values.
/// But notice that its contents will still be limited by the Natural size, to
/// also remove that limitation set SHRINK=YES.
/// To only change the User size in pixels, without resetting the Current size,
/// set the USERSIZE attribute (since 3.12).
/// Values set at SIZE or RASTERSIZE attributes of a dialog are always
/// accepted, regardless of the minimum size required by its children.
/// For a dialog to have the minimum necessary size to fit all elements
/// contained in it, simply define SIZE or RASTERSIZE to NULL.
/// Also if you set SIZE or RASTERSIZE to be used as the initial size of the
/// dialog, its contents will be limited to this size as the minimum size, if
/// you do not want that, then after showing the dialog reset this size to NULL
/// so the dialog can be resized to smaller values.
/// But notice that its contents will still be limited by the Natural size, to
/// also remove that limitation set SHRINK=YES.
/// To only change the User size in pixels, without resetting the Current size,
/// set the USERSIZE attribute (since 3.12).
pub fn getRasterSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "RASTERSIZE", .{});
return Size.parse(str);
}
///
/// Values set at SIZE or RASTERSIZE attributes of a dialog are always
/// accepted, regardless of the minimum size required by its children.
/// For a dialog to have the minimum necessary size to fit all elements
/// contained in it, simply define SIZE or RASTERSIZE to NULL.
/// Also if you set SIZE or RASTERSIZE to be used as the initial size of the
/// dialog, its contents will be limited to this size as the minimum size, if
/// you do not want that, then after showing the dialog reset this size to NULL
/// so the dialog can be resized to smaller values.
/// But notice that its contents will still be limited by the Natural size, to
/// also remove that limitation set SHRINK=YES.
/// To only change the User size in pixels, without resetting the Current size,
/// set the USERSIZE attribute (since 3.12).
/// Values set at SIZE or RASTERSIZE attributes of a dialog are always
/// accepted, regardless of the minimum size required by its children.
/// For a dialog to have the minimum necessary size to fit all elements
/// contained in it, simply define SIZE or RASTERSIZE to NULL.
/// Also if you set SIZE or RASTERSIZE to be used as the initial size of the
/// dialog, its contents will be limited to this size as the minimum size, if
/// you do not want that, then after showing the dialog reset this size to NULL
/// so the dialog can be resized to smaller values.
/// But notice that its contents will still be limited by the Natural size, to
/// also remove that limitation set SHRINK=YES.
/// To only change the User size in pixels, without resetting the Current size,
/// set the USERSIZE attribute (since 3.12).
/// Values set at SIZE or RASTERSIZE attributes of a dialog are always
/// accepted, regardless of the minimum size required by its children.
/// For a dialog to have the minimum necessary size to fit all elements
/// contained in it, simply define SIZE or RASTERSIZE to NULL.
/// Also if you set SIZE or RASTERSIZE to be used as the initial size of the
/// dialog, its contents will be limited to this size as the minimum size, if
/// you do not want that, then after showing the dialog reset this size to NULL
/// so the dialog can be resized to smaller values.
/// But notice that its contents will still be limited by the Natural size, to
/// also remove that limitation set SHRINK=YES.
/// To only change the User size in pixels, without resetting the Current size,
/// set the USERSIZE attribute (since 3.12).
pub fn setRasterSize(self: *Self, width: ?i32, height: ?i32) void {
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self, "RASTERSIZE", .{}, value);
}
///
/// SHAPEIMAGE [Windows and GTK Only]: sets a RGBA image as the dialog shape so
/// it is possible to create a non rectangle window with children.
/// (GTK 2.12) Only the fully transparent pixels will be transparent.
/// The pixels colors will be ignored, only the alpha channel is used.
/// (since 3.26)
pub fn getShapeImage(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "SHAPEIMAGE", .{});
}
///
/// SHAPEIMAGE [Windows and GTK Only]: sets a RGBA image as the dialog shape so
/// it is possible to create a non rectangle window with children.
/// (GTK 2.12) Only the fully transparent pixels will be transparent.
/// The pixels colors will be ignored, only the alpha channel is used.
/// (since 3.26)
pub fn setShapeImage(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "SHAPEIMAGE", .{}, arg);
}
pub fn getTipFgColor(self: *Self) ?iup.Rgb {
return interop.getRgb(self, "TIPFGCOLOR", .{});
}
pub fn setTipFgColor(self: *Self, rgb: iup.Rgb) void {
interop.setRgb(self, "TIPFGCOLOR", .{}, rgb);
}
pub fn getFontFace(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "FONTFACE", .{});
}
pub fn setFontFace(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "FONTFACE", .{}, arg);
}
///
/// TOPMOST [Windows and GTK Only]: puts the dialog always in front of all
/// other dialogs in all applications.
/// Default: NO.
pub fn topMost(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "TOPMOST", .{}, arg);
}
pub fn getName(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "NAME", .{});
}
pub fn setName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "NAME", .{}, arg);
}
///
/// DEFAULTENTER: Name of the button activated when the user press Enter when
/// focus is in another control of the dialog.
/// Use IupSetHandle or IupSetAttributeHandle to associate a button to a name.
pub fn getDefaultEnter(self: *Self) ?*iup.Button {
if (interop.getHandleAttribute(self, "DEFAULTENTER", .{})) |handle| {
return @ptrCast(*iup.Button, handle);
} else {
return null;
}
}
///
/// DEFAULTENTER: Name of the button activated when the user press Enter when
/// focus is in another control of the dialog.
/// Use IupSetHandle or IupSetAttributeHandle to associate a button to a name.
pub fn setDefaultEnter(self: *Self, arg: *iup.Button) void {
interop.setHandleAttribute(self, "DEFAULTENTER", .{}, arg);
}
pub fn setDefaultEnterHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "DEFAULTENTER", .{}, arg);
}
///
/// MODAL (read-only): Returns the popup state.
/// It is "YES" if the dialog was shown using IupPopup.
/// It is "NO" if IupShow was used or it is not visible.
/// At the first time the dialog is shown, MODAL is not set yet when SHOW_CB is called.
/// (since 3.0)
pub fn getModal(self: *Self) bool {
return interop.getBoolAttribute(self, "MODAL", .{});
}
///
/// BACKGROUND (non inheritable): Dialog background color or image.
/// Can be a non inheritable alternative to BGCOLOR or can be the name of an
/// image to be tiled on the background.
/// See also the screenshots of the sample.c results with normal background,
/// changing the dialog BACKGROUND, the dialog BGCOLOR and the children BGCOLOR.
/// Not working in GTK 3.
/// (since 3.0)
pub fn getBackground(self: *Self) ?iup.Rgb {
return interop.getRgb(self, "BACKGROUND", .{});
}
///
/// BACKGROUND (non inheritable): Dialog background color or image.
/// Can be a non inheritable alternative to BGCOLOR or can be the name of an
/// image to be tiled on the background.
/// See also the screenshots of the sample.c results with normal background,
/// changing the dialog BACKGROUND, the dialog BGCOLOR and the children BGCOLOR.
/// Not working in GTK 3.
/// (since 3.0)
pub fn setBackground(self: *Self, rgb: iup.Rgb) void {
interop.setRgb(self, "BACKGROUND", .{}, rgb);
}
///
/// HIDETASKBAR [Windows and GTK Only] (write-only): Action attribute that when
/// set to "YES", hides the dialog, but does not decrement the visible dialog
/// count, does not call SHOW_CB and does not mark the dialog as hidden inside IUP.
/// It is usually used to hide the dialog and keep the tray icon working
/// without closing the main loop.
/// It has the same effect as setting LOCKLOOP=Yes and normally hiding the dialog.
/// IMPORTANT: when you hide using HIDETASKBAR, you must show using HIDETASKBAR also.
/// Possible values: YES, NO.
pub fn getHideTaskbar(self: *Self) bool {
return interop.getBoolAttribute(self, "HIDETASKBAR", .{});
}
///
/// HIDETASKBAR [Windows and GTK Only] (write-only): Action attribute that when
/// set to "YES", hides the dialog, but does not decrement the visible dialog
/// count, does not call SHOW_CB and does not mark the dialog as hidden inside IUP.
/// It is usually used to hide the dialog and keep the tray icon working
/// without closing the main loop.
/// It has the same effect as setting LOCKLOOP=Yes and normally hiding the dialog.
/// IMPORTANT: when you hide using HIDETASKBAR, you must show using HIDETASKBAR also.
/// Possible values: YES, NO.
pub fn setHideTaskbar(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "HIDETASKBAR", .{}, arg);
}
///
/// BRINGFRONT [Windows Only] (write-only): makes the dialog the foreground window.
/// Use "YES" to activate it.
/// Useful for multithreaded applications.
pub fn getBringFront(self: *Self) bool {
return interop.getBoolAttribute(self, "BRINGFRONT", .{});
}
///
/// BRINGFRONT [Windows Only] (write-only): makes the dialog the foreground window.
/// Use "YES" to activate it.
/// Useful for multithreaded applications.
pub fn setBringFront(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "BRINGFRONT", .{}, arg);
}
///
/// TRAYIMAGE [Windows and GTK Only]: Name of a IUP image to be used as the
/// tray icon.
/// The Windows SDK recommends that cursors and icons should be implemented as
/// resources rather than created at run time.
/// (GTK 2.10 and GTK < 3.14)
pub fn getTrayImage(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "TRAYIMAGE", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// TRAYIMAGE [Windows and GTK Only]: Name of a IUP image to be used as the
/// tray icon.
/// The Windows SDK recommends that cursors and icons should be implemented as
/// resources rather than created at run time.
/// (GTK 2.10 and GTK < 3.14)
pub fn setTrayImage(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "TRAYIMAGE", .{}, arg);
}
pub fn setTrayImageHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TRAYIMAGE", .{}, arg);
}
///
/// ACTIVE, BGCOLOR, FONT, EXPAND, SCREENPOSITION, WID, TIP, CLIENTOFFSET,
/// CLIENTSIZE, RASTERSIZE, ZORDER: also accepted.
/// Note that ACTIVE, BGCOLOR and FONT will also affect all the controls inside
/// the dialog.
pub fn getActive(self: *Self) bool {
return interop.getBoolAttribute(self, "ACTIVE", .{});
}
///
/// ACTIVE, BGCOLOR, FONT, EXPAND, SCREENPOSITION, WID, TIP, CLIENTOFFSET,
/// CLIENTSIZE, RASTERSIZE, ZORDER: also accepted.
/// Note that ACTIVE, BGCOLOR and FONT will also affect all the controls inside
/// the dialog.
pub fn setActive(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "ACTIVE", .{}, arg);
}
pub fn getTipVisible(self: *Self) bool {
return interop.getBoolAttribute(self, "TIPVISIBLE", .{});
}
pub fn setTipVisible(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "TIPVISIBLE", .{}, arg);
}
pub fn getExpandWeight(self: *Self) f64 {
return interop.getDoubleAttribute(self, "EXPANDWEIGHT", .{});
}
pub fn setExpandWeight(self: *Self, arg: f64) void {
interop.setDoubleAttribute(self, "EXPANDWEIGHT", .{}, arg);
}
///
/// MINSIZE: Minimum size for the dialog in raster units (pixels).
/// The windowing system will not be able to change the size beyond this limit.
/// Default: 1x1.
/// Some systems define a very minimum size greater than this, for instance in
/// Windows the horizontal minimum size includes the window decoration buttons.
/// (since 3.0)
pub fn getMinSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "MINSIZE", .{});
return Size.parse(str);
}
///
/// MINSIZE: Minimum size for the dialog in raster units (pixels).
/// The windowing system will not be able to change the size beyond this limit.
/// Default: 1x1.
/// Some systems define a very minimum size greater than this, for instance in
/// Windows the horizontal minimum size includes the window decoration buttons.
/// (since 3.0)
pub fn setMinSize(self: *Self, width: ?i32, height: ?i32) void {
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self, "MINSIZE", .{}, value);
}
///
/// ACTIVEWINDOW [Windows and GTK Only] (read-only): informs if the dialog is
/// the active window (the window with focus).
/// Can be Yes or No.
/// (since 3.4)
pub fn getActiveWindow(self: *Self) bool {
return interop.getBoolAttribute(self, "ACTIVEWINDOW", .{});
}
pub fn getNTheme(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "NTHEME", .{});
}
pub fn setNTheme(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "NTHEME", .{}, arg);
}
///
/// CUSTOMFRAMESIMULATE: allows the application to customize the dialog frame
/// elements (the title and its buttons) by using IUP controls for its elements
/// like caption, minimize button, maximize button, and close buttons.
/// The custom frame support is entirely simulated by IUP, no native support
/// for custom frame is used (this seems to have less drawbacks on the
/// application behavior).
/// The application is responsible for leaving space for the borders.
/// One drawback is that menu bars will not work.
/// For the dialog to be able to be moved an IupLabel, or a IupFlatLabel or an
/// IupCanvas must be at the top of the dialog and must have the NAME attribute
/// set to CUSTOMFRAMECAPTION.
/// See the Custom Frame notes bellow.
/// (since 3.28)
pub fn getCustomFramesImulate(self: *Self) bool {
return interop.getBoolAttribute(self, "CUSTOMFRAMESIMULATE", .{});
}
///
/// CUSTOMFRAMESIMULATE: allows the application to customize the dialog frame
/// elements (the title and its buttons) by using IUP controls for its elements
/// like caption, minimize button, maximize button, and close buttons.
/// The custom frame support is entirely simulated by IUP, no native support
/// for custom frame is used (this seems to have less drawbacks on the
/// application behavior).
/// The application is responsible for leaving space for the borders.
/// One drawback is that menu bars will not work.
/// For the dialog to be able to be moved an IupLabel, or a IupFlatLabel or an
/// IupCanvas must be at the top of the dialog and must have the NAME attribute
/// set to CUSTOMFRAMECAPTION.
/// See the Custom Frame notes bellow.
/// (since 3.28)
pub fn setCustomFramesImulate(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "CUSTOMFRAMESIMULATE", .{}, arg);
}
///
/// SHRINK: Allows changing the elements distribution when the dialog is
/// smaller than the minimum size.
/// Default: NO.
pub fn getShrink(self: *Self) bool {
return interop.getBoolAttribute(self, "SHRINK", .{});
}
///
/// SHRINK: Allows changing the elements distribution when the dialog is
/// smaller than the minimum size.
/// Default: NO.
pub fn setShrink(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "SHRINK", .{}, arg);
}
pub fn getCharSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "CHARSIZE", .{});
return Size.parse(str);
}
pub fn getClientSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "CLIENTSIZE", .{});
return Size.parse(str);
}
pub fn setClientSize(self: *Self, width: ?i32, height: ?i32) void {
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self, "CLIENTSIZE", .{}, value);
}
pub fn getClientOffset(self: *Self) Size {
var str = interop.getStrAttribute(self, "CLIENTOFFSET", .{});
return Size.parse(str);
}
///
/// TRAYTIP [Windows and GTK Only]: Tray icon's tooltip text.
/// (GTK 2.10 and GTK < 3.14)
pub fn getTrayTip(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "TRAYTIP", .{});
}
///
/// TRAYTIP [Windows and GTK Only]: Tray icon's tooltip text.
/// (GTK 2.10 and GTK < 3.14)
pub fn setTrayTip(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TRAYTIP", .{}, arg);
}
pub fn getDragTypes(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "DRAGTYPES", .{});
}
pub fn setDragTypes(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "DRAGTYPES", .{}, arg);
}
pub fn getFontStyle(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "FONTSTYLE", .{});
}
pub fn setFontStyle(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "FONTSTYLE", .{}, arg);
}
///
/// FULLSCREEN: Makes the dialog occupy the whole screen over any system bars
/// in the main monitor.
/// All dialog details, such as title bar, borders, maximize button, etc, are removed.
/// Possible values: YES, NO.
/// In Motif you may have to click in the dialog to set its focus.
/// In Motif if set to YES when the dialog is hidden, then it can not be
/// changed after it is visible.
pub fn fullScreen(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "FULLSCREEN", .{}, arg);
}
pub fn getFont(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "FONT", .{});
}
pub fn setFont(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "FONT", .{}, arg);
}
///
/// SIMULATEMODAL (write-only): disable all other visible dialogs, just like
/// when the dialog is made modal.
/// (since 3.21)
pub fn simulateModal(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "SIMULATEMODAL", .{}, arg);
}
///
/// TABIMAGEn (non inheritable): image name to be used in the respective tab.
/// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name.
/// n starts at 0.
/// See also IupImage.
/// In Motif, the image is shown only if TABTITLEn is NULL.
/// In Windows and Motif set the BGCOLOR attribute before setting the image.
/// When set after map will update the TABIMAGE attribute on the respective
/// child (since 3.10).
/// (since 3.0).
/// TABIMAGE (non inheritable) (at children only): Same as TABIMAGEn but set in
/// each child.
/// Works only if set before the child is added to the tabs.
pub fn getTabImage(self: *Self, index: i32) ?iup.Element {
if (interop.getHandleAttribute(self, "TABIMAGE", .{index})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// TABIMAGEn (non inheritable): image name to be used in the respective tab.
/// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name.
/// n starts at 0.
/// See also IupImage.
/// In Motif, the image is shown only if TABTITLEn is NULL.
/// In Windows and Motif set the BGCOLOR attribute before setting the image.
/// When set after map will update the TABIMAGE attribute on the respective
/// child (since 3.10).
/// (since 3.0).
/// TABIMAGE (non inheritable) (at children only): Same as TABIMAGEn but set in
/// each child.
/// Works only if set before the child is added to the tabs.
pub fn setTabImage(self: *Self, index: i32, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "TABIMAGE", .{index}, arg);
}
pub fn setTabImageHandleName(self: *Self, index: i32, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TABIMAGE", .{index}, arg);
}
///
/// TABTITLEn (non inheritable): Contains the text to be shown in the
/// respective tab title.
/// n starts at 0.
/// If this value is NULL, it will remain empty.
/// The "&" character can be used to define a mnemonic, the next character will
/// be used as key.
/// Use "&&" to show the "&" character instead on defining a mnemonic.
/// The button can be activated from any control in the dialog using the
/// "Alt+key" combination.
/// (mnemonic support since 3.3).
/// When set after map will update the TABTITLE attribute on the respective
/// child (since 3.10).
/// (since 3.0).
/// TABTITLE (non inheritable) (at children only): Same as TABTITLEn but set in
/// each child.
/// Works only if set before the child is added to the tabs.
pub fn getTabTitle(self: *Self, index: i32) [:0]const u8 {
return interop.getStrAttribute(self, "TABTITLE", .{index});
}
///
/// TABTITLEn (non inheritable): Contains the text to be shown in the
/// respective tab title.
/// n starts at 0.
/// If this value is NULL, it will remain empty.
/// The "&" character can be used to define a mnemonic, the next character will
/// be used as key.
/// Use "&&" to show the "&" character instead on defining a mnemonic.
/// The button can be activated from any control in the dialog using the
/// "Alt+key" combination.
/// (mnemonic support since 3.3).
/// When set after map will update the TABTITLE attribute on the respective
/// child (since 3.10).
/// (since 3.0).
/// TABTITLE (non inheritable) (at children only): Same as TABTITLEn but set in
/// each child.
/// Works only if set before the child is added to the tabs.
pub fn setTabTitle(self: *Self, index: i32, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TABTITLE", .{index}, arg);
}
///
/// FOCUS_CB: Called when the dialog or any of its children gets the focus, or
/// when another dialog or any control in another dialog gets the focus.
/// It is called after the common callbacks GETFOCUS_CB and KILL_FOCUS_CB.
/// (since 3.21) int function(Ihandle *ih, int focus); [in C]ih:focus_cb(focus:
/// number) -> (ret: number) [in Lua]
pub fn setFocusCallback(self: *Self, callback: ?OnFocusFn) void {
const Handler = CallbackHandler(Self, OnFocusFn, "FOCUS_CB");
Handler.setCallback(self, callback);
}
///
/// K_ANY K_ANY Action generated when a keyboard event occurs.
/// Callback int function(Ihandle *ih, int c); [in C] ih:k_any(c: number) ->
/// (ret: number) [in Lua] ih: identifier of the element that activated the event.
/// c: identifier of typed key.
/// Please refer to the Keyboard Codes table for a list of possible values.
/// Returns: If IUP_IGNORE is returned the key is ignored and not processed by
/// the control and not propagated.
/// If returns IUP_CONTINUE, the key will be processed and the event will be
/// propagated to the parent of the element receiving it, this is the default behavior.
/// If returns IUP_DEFAULT the key is processed but it is not propagated.
/// IUP_CLOSE will be processed.
/// Notes Keyboard callbacks depend on the keyboard usage of the control with
/// the focus.
/// So if you return IUP_IGNORE the control will usually not process the key.
/// But be aware that sometimes the control process the key in another event so
/// even returning IUP_IGNORE the key can get processed.
/// Although it will not be propagated.
/// IMPORTANT: The callbacks "K_*" of the dialog or native containers depend on
/// the IUP_CONTINUE return value to work while the control is in focus.
/// If the callback does not exists it is automatically propagated to the
/// parent of the element.
/// K_* callbacks All defined keys are also callbacks of any element, called
/// when the respective key is activated.
/// For example: "K_cC" is also a callback activated when the user press
/// Ctrl+C, when the focus is at the element or at a children with focus.
/// This is the way an application can create shortcut keys, also called hot keys.
/// These callbacks are not available in IupLua.
/// Affects All elements with keyboard interaction.
pub fn setKAnyCallback(self: *Self, callback: ?OnKAnyFn) void {
const Handler = CallbackHandler(Self, OnKAnyFn, "K_ANY");
Handler.setCallback(self, callback);
}
///
/// HELP_CB HELP_CB Action generated when the user press F1 at a control.
/// In Motif is also activated by the Help button in some workstations keyboard.
/// Callback void function(Ihandle *ih); [in C] ih:help_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Returns: IUP_CLOSE will be processed.
/// Affects All elements with user interaction.
pub fn setHelpCallback(self: *Self, callback: ?OnHelpFn) void {
const Handler = CallbackHandler(Self, OnHelpFn, "HELP_CB");
Handler.setCallback(self, callback);
}
///
/// CLOSE_CB CLOSE_CB Called just before a dialog is closed when the user
/// clicks the close button of the title bar or an equivalent action.
/// Callback int function(Ihandle *ih); [in C] ih:close_cb() -> (ret: number)
/// [in Lua] ih: identifies the element that activated the event.
/// Returns: if IUP_IGNORE, it prevents the dialog from being closed.
/// If you destroy the dialog in this callback, you must return IUP_IGNORE.
/// IUP_CLOSE will be processed.
/// Affects IupDialog
pub fn setCloseCallback(self: *Self, callback: ?OnCloseFn) void {
const Handler = CallbackHandler(Self, OnCloseFn, "CLOSE_CB");
Handler.setCallback(self, callback);
}
pub fn setDropMotionCallback(self: *Self, callback: ?OnDropMotionFn) void {
const Handler = CallbackHandler(Self, OnDropMotionFn, "DROPMOTION_CB");
Handler.setCallback(self, callback);
}
pub fn setDragEndCallback(self: *Self, callback: ?OnDragEndFn) void {
const Handler = CallbackHandler(Self, OnDragEndFn, "DRAGEND_CB");
Handler.setCallback(self, callback);
}
pub fn setDragBeginCallback(self: *Self, callback: ?OnDragBeginFn) void {
const Handler = CallbackHandler(Self, OnDragBeginFn, "DRAGBEGIN_CB");
Handler.setCallback(self, callback);
}
///
/// MAP_CB MAP_CB Called right after an element is mapped and its attributes
/// updated in IupMap.
/// When the element is a dialog, it is called after the layout is updated.
/// For all other elements is called before the layout is updated, so the
/// element current size will still be 0x0 during MAP_CB (since 3.14).
/// Callback int function(Ihandle *ih); [in C] ih:map_cb() -> (ret: number) [in
/// Lua] ih: identifier of the element that activated the event.
/// Affects All that have a native representation.
pub fn setMapCallback(self: *Self, callback: ?OnMapFn) void {
const Handler = CallbackHandler(Self, OnMapFn, "MAP_CB");
Handler.setCallback(self, callback);
}
///
/// ENTERWINDOW_CB ENTERWINDOW_CB Action generated when the mouse enters the
/// native element.
/// Callback int function(Ihandle *ih); [in C] ih:enterwindow_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// Notes When the cursor is moved from one element to another, the call order
/// in all platforms will be first the LEAVEWINDOW_CB callback of the old
/// control followed by the ENTERWINDOW_CB callback of the new control.
/// (since 3.14) If the mouse button is hold pressed and the cursor moves
/// outside the element the behavior is system dependent.
/// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in
/// GTK the callbacks are called.
/// Affects All controls with user interaction.
/// See Also LEAVEWINDOW_CB
pub fn setEnterWindowCallback(self: *Self, callback: ?OnEnterWindowFn) void {
const Handler = CallbackHandler(Self, OnEnterWindowFn, "ENTERWINDOW_CB");
Handler.setCallback(self, callback);
}
///
/// DESTROY_CB DESTROY_CB Called right before an element is destroyed.
/// Callback int function(Ihandle *ih); [in C] ih:destroy_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Notes If the dialog is visible then it is hidden before it is destroyed.
/// The callback will be called right after it is hidden.
/// The callback will be called before all other destroy procedures.
/// For instance, if the element has children then it is called before the
/// children are destroyed.
/// For language binding implementations use the callback name "LDESTROY_CB" to
/// release memory allocated by the binding for the element.
/// Also the callback will be called before the language callback.
/// Affects All.
pub fn setDestroyCallback(self: *Self, callback: ?OnDestroyFn) void {
const Handler = CallbackHandler(Self, OnDestroyFn, "DESTROY_CB");
Handler.setCallback(self, callback);
}
pub fn setDropDataCallback(self: *Self, callback: ?OnDropDataFn) void {
const Handler = CallbackHandler(Self, OnDropDataFn, "DROPDATA_CB");
Handler.setCallback(self, callback);
}
///
/// KILLFOCUS_CB KILLFOCUS_CB Action generated when an element loses keyboard focus.
/// This callback is called before the GETFOCUS_CB of the element that gets the focus.
/// Callback int function(Ihandle *ih); [in C] ih:killfocus_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// Affects All elements with user interaction, except menus.
/// In Windows, there are restrictions when using this callback.
/// From MSDN on WM_KILLFOCUS: "While processing this message, do not make any
/// function calls that display or activate a window.
/// This causes the thread to yield control and can cause the application to
/// stop responding to messages.
/// See Also GETFOCUS_CB, IupGetFocus, IupSetFocus
pub fn setKillFocusCallback(self: *Self, callback: ?OnKillFocusFn) void {
const Handler = CallbackHandler(Self, OnKillFocusFn, "KILLFOCUS_CB");
Handler.setCallback(self, callback);
}
pub fn setDragDataCallback(self: *Self, callback: ?OnDragDataFn) void {
const Handler = CallbackHandler(Self, OnDragDataFn, "DRAGDATA_CB");
Handler.setCallback(self, callback);
}
pub fn setDragDataSizeCallback(self: *Self, callback: ?OnDragDataSizeFn) void {
const Handler = CallbackHandler(Self, OnDragDataSizeFn, "DRAGDATASIZE_CB");
Handler.setCallback(self, callback);
}
///
/// SHOW_CB SHOW_CB Called right after the dialog is showed, hidden, maximized,
/// minimized or restored from minimized/maximized.
/// This callback is called when those actions were performed by the user or
/// programmatically by the application.
/// Callback int function(Ihandle *ih, int state); [in C] ih:show_cb(state:
/// number) -> (ret: number) [in Lua] ih: identifier of the element that
/// activated the event.
/// state: indicates which of the following situations generated the event:
/// IUP_HIDE (since 3.0) IUP_SHOW IUP_RESTORE (was minimized or maximized)
/// IUP_MINIMIZE IUP_MAXIMIZE (since 3.0) (not received in Motif when activated
/// from the maximize button) Returns: IUP_CLOSE will be processed.
/// Affects IupDialog
pub fn setShowCallback(self: *Self, callback: ?OnShowFn) void {
const Handler = CallbackHandler(Self, OnShowFn, "SHOW_CB");
Handler.setCallback(self, callback);
}
///
/// DROPFILES_CB DROPFILES_CB Action called when a file is "dropped" into the control.
/// When several files are dropped at once, the callback is called several
/// times, once for each file.
/// If defined after the element is mapped then the attribute DROPFILESTARGET
/// must be set to YES.
/// [Windows and GTK Only] (GTK 2.6) Callback int function(Ihandle *ih, const
/// char* filename, int num, int x, int y); [in C] ih:dropfiles_cb(filename:
/// string; num, x, y: number) -> (ret: number) [in Lua] ih: identifier of the
/// element that activated the event.
/// filename: Name of the dropped file.
/// num: Number index of the dropped file.
/// If several files are dropped, num is the index of the dropped file starting
/// from "total-1" to "0".
/// x: X coordinate of the point where the user released the mouse button.
/// y: Y coordinate of the point where the user released the mouse button.
/// Returns: If IUP_IGNORE is returned the callback will NOT be called for the
/// next dropped files, and the processing of dropped files will be interrupted.
/// Affects IupDialog, IupCanvas, IupGLCanvas, IupText, IupList
pub fn setDropFilesCallback(self: *Self, callback: ?OnDropFilesFn) void {
const Handler = CallbackHandler(Self, OnDropFilesFn, "DROPFILES_CB");
Handler.setCallback(self, callback);
}
///
/// RESIZE_CB RESIZE_CB Action generated when the canvas or dialog size is changed.
/// Callback int function(Ihandle *ih, int width, int height); [in C]
/// ih:resize_cb(width, height: number) -> (ret: number) [in Lua] ih:
/// identifier of the element that activated the event.
/// width: the width of the internal element size in pixels not considering the
/// decorations (client size) height: the height of the internal element size
/// in pixels not considering the decorations (client size) Notes For the
/// dialog, this action is also generated when the dialog is mapped, after the
/// map and before the show.
/// When XAUTOHIDE=Yes or YAUTOHIDE=Yes, if the canvas scrollbar is
/// hidden/shown after changing the DX or DY attributes from inside the
/// callback, the size of the drawing area will immediately change, so the
/// parameters with and height will be invalid.
/// To update the parameters consult the DRAWSIZE attribute.
/// Also activate the drawing toolkit only after updating the DX or DY attributes.
/// Affects IupCanvas, IupGLCanvas, IupDialog
pub fn setResizeCallback(self: *Self, callback: ?OnResizeFn) void {
const Handler = CallbackHandler(Self, OnResizeFn, "RESIZE_CB");
Handler.setCallback(self, callback);
}
///
/// UNMAP_CB UNMAP_CB Called right before an element is unmapped.
/// Callback int function(Ihandle *ih); [in C] ih:unmap_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Affects All that have a native representation.
pub fn setUnmapCallback(self: *Self, callback: ?OnUnmapFn) void {
const Handler = CallbackHandler(Self, OnUnmapFn, "UNMAP_CB");
Handler.setCallback(self, callback);
}
///
/// TRAYCLICK_CB [Windows and GTK Only]: Called right after the mouse button is
/// pressed or released over the tray icon.
/// (GTK 2.10) int function(Ihandle *ih, int but, int pressed, int dclick); [in
/// C]elem:trayclick_cb(but, pressed, dclick: number) -> (ret: number) [in Lua]
pub fn setTrayClickCallback(self: *Self, callback: ?OnTrayClickFn) void {
const Handler = CallbackHandler(Self, OnTrayClickFn, "TRAYCLICK_CB");
Handler.setCallback(self, callback);
}
///
/// GETFOCUS_CB GETFOCUS_CB Action generated when an element is given keyboard focus.
/// This callback is called after the KILLFOCUS_CB of the element that loosed
/// the focus.
/// The IupGetFocus function during the callback returns the element that
/// loosed the focus.
/// Callback int function(Ihandle *ih); [in C] ih:getfocus_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that received keyboard focus.
/// Affects All elements with user interaction, except menus.
/// See Also KILLFOCUS_CB, IupGetFocus, IupSetFocus
pub fn setGetFocusCallback(self: *Self, callback: ?OnGetFocusFn) void {
const Handler = CallbackHandler(Self, OnGetFocusFn, "GETFOCUS_CB");
Handler.setCallback(self, callback);
}
pub fn setLDestroyCallback(self: *Self, callback: ?OnLDestroyFn) void {
const Handler = CallbackHandler(Self, OnLDestroyFn, "LDESTROY_CB");
Handler.setCallback(self, callback);
}
///
/// LEAVEWINDOW_CB LEAVEWINDOW_CB Action generated when the mouse leaves the
/// native element.
/// Callback int function(Ihandle *ih); [in C] ih:leavewindow_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// Notes When the cursor is moved from one element to another, the call order
/// in all platforms will be first the LEAVEWINDOW_CB callback of the old
/// control followed by the ENTERWINDOW_CB callback of the new control.
/// (since 3.14) If the mouse button is hold pressed and the cursor moves
/// outside the element the behavior is system dependent.
/// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in
/// GTK the callbacks are called.
/// Affects All controls with user interaction.
/// See Also ENTERWINDOW_CB
pub fn setLeaveWindowCallback(self: *Self, callback: ?OnLeaveWindowFn) void {
const Handler = CallbackHandler(Self, OnLeaveWindowFn, "LEAVEWINDOW_CB");
Handler.setCallback(self, callback);
}
pub fn setPostMessageCallback(self: *Self, callback: ?OnPostMessageFn) void {
const Handler = CallbackHandler(Self, OnPostMessageFn, "POSTMESSAGE_CB");
Handler.setCallback(self, callback);
}
};
test "Dialog HandleName" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setHandleName("Hello").unwrap());
defer item.deinit();
var ret = item.getHandleName();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "Dialog TipBgColor" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setTipBgColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap());
defer item.deinit();
var ret = item.getTipBgColor();
try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11);
}
test "Dialog TipIcon" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setTipIcon("Hello").unwrap());
defer item.deinit();
var ret = item.getTipIcon();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "Dialog NoFlush" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setNoFlush(true).unwrap());
defer item.deinit();
var ret = item.getNoFlush();
try std.testing.expect(ret == true);
}
test "Dialog MaxSize" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setMaxSize(9, 10).unwrap());
defer item.deinit();
var ret = item.getMaxSize();
try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10);
}
test "Dialog OpacityImage" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setOpacityImage("Hello").unwrap());
defer item.deinit();
var ret = item.getOpacityImage();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "Dialog ShowNoFocus" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setShowNoFocus(true).unwrap());
defer item.deinit();
var ret = item.getShowNoFocus();
try std.testing.expect(ret == true);
}
test "Dialog Opacity" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setOpacity(42).unwrap());
defer item.deinit();
var ret = item.getOpacity();
try std.testing.expect(ret == 42);
}
test "Dialog Position" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setPosition(9, 10).unwrap());
defer item.deinit();
var ret = item.getPosition();
try std.testing.expect(ret.x == 9 and ret.y == 10);
}
test "Dialog DropFilesTarget" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setDropFilesTarget(true).unwrap());
defer item.deinit();
var ret = item.getDropFilesTarget();
try std.testing.expect(ret == true);
}
test "Dialog Tip" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setTip("Hello").unwrap());
defer item.deinit();
var ret = item.getTip();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "Dialog CanFocus" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setCanFocus(true).unwrap());
defer item.deinit();
var ret = item.getCanFocus();
try std.testing.expect(ret == true);
}
test "Dialog DragSourceMove" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setDragSourceMove(true).unwrap());
defer item.deinit();
var ret = item.getDragSourceMove();
try std.testing.expect(ret == true);
}
test "Dialog Icon" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setIcon("Hello").unwrap());
defer item.deinit();
var ret = item.getIcon();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "Dialog Visible" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setVisible(true).unwrap());
defer item.deinit();
var ret = item.getVisible();
try std.testing.expect(ret == true);
}
test "Dialog HideTitleBar" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setHideTitleBar("Hello").unwrap());
defer item.deinit();
var ret = item.getHideTitleBar();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "Dialog DragDrop" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setDragDrop(true).unwrap());
defer item.deinit();
var ret = item.getDragDrop();
try std.testing.expect(ret == true);
}
test "Dialog DialogHint" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setDialogHint(true).unwrap());
defer item.deinit();
var ret = item.getDialogHint();
try std.testing.expect(ret == true);
}
test "Dialog DialogFrame" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setDialogFrame(true).unwrap());
defer item.deinit();
var ret = item.getDialogFrame();
try std.testing.expect(ret == true);
}
test "Dialog NActive" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setNActive(true).unwrap());
defer item.deinit();
var ret = item.getNActive();
try std.testing.expect(ret == true);
}
test "Dialog Theme" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setTheme("Hello").unwrap());
defer item.deinit();
var ret = item.getTheme();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "Dialog Tray" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setTray(true).unwrap());
defer item.deinit();
var ret = item.getTray();
try std.testing.expect(ret == true);
}
test "Dialog ChildOffset" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setChildOffset(9, 10).unwrap());
defer item.deinit();
var ret = item.getChildOffset();
try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10);
}
test "Dialog Expand" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setExpand(.Yes).unwrap());
defer item.deinit();
var ret = item.getExpand();
try std.testing.expect(ret != null and ret.? == .Yes);
}
test "Dialog TipMarkup" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setTipMarkup("Hello").unwrap());
defer item.deinit();
var ret = item.getTipMarkup();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "Dialog StartFocus" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setStartFocus("Hello").unwrap());
defer item.deinit();
var ret = item.getStartFocus();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "Dialog FontSize" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setFontSize(42).unwrap());
defer item.deinit();
var ret = item.getFontSize();
try std.testing.expect(ret == 42);
}
test "Dialog DropTypes" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setDropTypes("Hello").unwrap());
defer item.deinit();
var ret = item.getDropTypes();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "Dialog TrayTipMarkup" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setTrayTipMarkup("Hello").unwrap());
defer item.deinit();
var ret = item.getTrayTipMarkup();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "Dialog UserSize" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setUserSize(9, 10).unwrap());
defer item.deinit();
var ret = item.getUserSize();
try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10);
}
test "Dialog TipDelay" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setTipDelay(42).unwrap());
defer item.deinit();
var ret = item.getTipDelay();
try std.testing.expect(ret == 42);
}
test "Dialog CustomFrame" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setCustomFrame(true).unwrap());
defer item.deinit();
var ret = item.getCustomFrame();
try std.testing.expect(ret == true);
}
test "Dialog Title" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setTitle("Hello").unwrap());
defer item.deinit();
var ret = item.getTitle();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "Dialog Placement" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setPlacement(.Maximized).unwrap());
defer item.deinit();
var ret = item.getPlacement();
try std.testing.expect(ret != null and ret.? == .Maximized);
}
test "Dialog PropagateFocus" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setPropagateFocus(true).unwrap());
defer item.deinit();
var ret = item.getPropagateFocus();
try std.testing.expect(ret == true);
}
test "Dialog BgColor" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setBgColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap());
defer item.deinit();
var ret = item.getBgColor();
try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11);
}
test "Dialog DropTarget" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setDropTarget(true).unwrap());
defer item.deinit();
var ret = item.getDropTarget();
try std.testing.expect(ret == true);
}
test "Dialog DragSource" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setDragSource(true).unwrap());
defer item.deinit();
var ret = item.getDragSource();
try std.testing.expect(ret == true);
}
test "Dialog Floating" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setFloating(.Yes).unwrap());
defer item.deinit();
var ret = item.getFloating();
try std.testing.expect(ret != null and ret.? == .Yes);
}
test "Dialog NormalizerGroup" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setNormalizerGroup("Hello").unwrap());
defer item.deinit();
var ret = item.getNormalizerGroup();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "Dialog RasterSize" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setRasterSize(9, 10).unwrap());
defer item.deinit();
var ret = item.getRasterSize();
try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10);
}
test "Dialog ShapeImage" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setShapeImage("Hello").unwrap());
defer item.deinit();
var ret = item.getShapeImage();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "Dialog TipFgColor" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setTipFgColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap());
defer item.deinit();
var ret = item.getTipFgColor();
try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11);
}
test "Dialog FontFace" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setFontFace("Hello").unwrap());
defer item.deinit();
var ret = item.getFontFace();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "Dialog Name" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setName("Hello").unwrap());
defer item.deinit();
var ret = item.getName();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "Dialog Background" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setBackground(.{ .r = 9, .g = 10, .b = 11 }).unwrap());
defer item.deinit();
var ret = item.getBackground();
try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11);
}
test "Dialog HideTaskbar" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setHideTaskbar(true).unwrap());
defer item.deinit();
var ret = item.getHideTaskbar();
try std.testing.expect(ret == true);
}
test "Dialog BringFront" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setBringFront(true).unwrap());
defer item.deinit();
var ret = item.getBringFront();
try std.testing.expect(ret == true);
}
test "Dialog Active" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setActive(true).unwrap());
defer item.deinit();
var ret = item.getActive();
try std.testing.expect(ret == true);
}
test "Dialog TipVisible" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setTipVisible(true).unwrap());
defer item.deinit();
var ret = item.getTipVisible();
try std.testing.expect(ret == true);
}
test "Dialog ExpandWeight" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setExpandWeight(3.14).unwrap());
defer item.deinit();
var ret = item.getExpandWeight();
try std.testing.expect(ret == @as(f64, 3.14));
}
test "Dialog MinSize" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setMinSize(9, 10).unwrap());
defer item.deinit();
var ret = item.getMinSize();
try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10);
}
test "Dialog NTheme" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setNTheme("Hello").unwrap());
defer item.deinit();
var ret = item.getNTheme();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "Dialog CustomFramesImulate" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setCustomFramesImulate(true).unwrap());
defer item.deinit();
var ret = item.getCustomFramesImulate();
try std.testing.expect(ret == true);
}
test "Dialog Shrink" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setShrink(true).unwrap());
defer item.deinit();
var ret = item.getShrink();
try std.testing.expect(ret == true);
}
test "Dialog ClientSize" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setClientSize(9, 10).unwrap());
defer item.deinit();
var ret = item.getClientSize();
try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10);
}
test "Dialog TrayTip" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setTrayTip("Hello").unwrap());
defer item.deinit();
var ret = item.getTrayTip();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "Dialog DragTypes" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setDragTypes("Hello").unwrap());
defer item.deinit();
var ret = item.getDragTypes();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "Dialog FontStyle" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setFontStyle("Hello").unwrap());
defer item.deinit();
var ret = item.getFontStyle();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "Dialog Font" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.Dialog.init().setFont("Hello").unwrap());
defer item.deinit();
var ret = item.getFont();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
} | src/elements/dialog.zig |
const std = @import("std");
const testing = std.testing;
const fs = std.fs;
const main = @import("main.zig");
const utils = @import("utils.zig");
const config = @import("config.zig");
const kvstore = @import("kvstore.zig");
const Console = @import("console.zig").Console;
pub const FilePathEntry = std.BoundedArray(u8, config.MAX_PATH_LEN);
fn debug(comptime fmt: []const u8, args: anytype) void {
std.io.getStdOut().writer().print(fmt, args) catch return;
}
fn err(comptime fmt: []const u8, args: anytype) void {
std.io.getStdErr().writer().print(fmt, args) catch return;
}
pub const AppArguments = struct {
//--colors
colors: Console.ColorConfig = .auto,
//--verbose,-v
verbose: bool = false,
//--verbose-curl
verbose_curl: bool = false,
//-s
silent: bool = false,
//--insecure
ssl_insecure: bool = false,
//--show-response,-d
show_response_data: bool = false,
//--pretty,-p
show_pretty_response_data: bool = false,
//-m allows for concurrent requests for repeated tests
multithreaded: bool = false,
//-e, --early-quit - abort execution upon first non-successful test
early_quit: bool = false,
//-i=<file>
input_vars_file: std.BoundedArray(u8, config.MAX_PATH_LEN) = utils.initBoundedArray(u8, config.MAX_PATH_LEN),
//-b=<file>
playbook_file: std.BoundedArray(u8, config.MAX_PATH_LEN) = utils.initBoundedArray(u8, config.MAX_PATH_LEN),
//-delay=NN
delay: u64 = 0,
// ...
files: std.BoundedArray(FilePathEntry, 128) = utils.initBoundedArray(FilePathEntry, 128),
};
pub fn printHelp(full: bool) void {
debug(
\\{0s} v{1s} - Simple API Tester
\\
\\Usage: {0s} [arguments] [file1.pi file2.pi ... fileN.pi]
\\
\\
, .{ config.APP_NAME, config.APP_VERSION});
if (!full) {
debug(
\\try '{0s} --help' for more information.
\\
\\
, .{ config.APP_NAME});
return;
}
debug(
\\Examples:
\\ {0s} api_is_healthy.pi
\\ {0s} testsuite01/
\\ {0s} -b=myplaybook.book
// \\ {0s} -p=myplaybook.book -s -o=output.log
\\ {0s} -i=generaldefs/.env testsuite01/
\\
\\Arguments:
\\ --colors=auto|on|off Set wether to attempt to use colored output or not
\\ --delay=NN Delay execution of each consecutive step with NN ms
\\ -e, --early-quit Abort upon first non-successful test
\\ -h, --help Show this help and exit
\\ --help-format Show details regarding file formats and exit
\\ -i=file,
\\ --initial-vars=file Provide file with variable-definitions made available
\\ to all tests
\\ --insecure Don't verify SSL certificates
\\ -m, --multithread Activates multithreading - relevant for repeated
\\ tests via playbooks
\\ -p, --pretty Try to format response data based on Content-Type.
\\ Naive support for JSON, XML and HTML
\\ -b=file,
\\ --playbook=file Read tests to perform from playbook-file -- if set,
\\ ignores other tests passed as arguments
\\ -d, --show-response Show response data. Even if -s.
\\ -s, --silent Silent. Suppresses output. Overrules verbose.
\\ -v, --verbose Verbose output
\\ --verbose-curl Verbose output from libcurl
\\ --version Show version and exit
\\
\\ -DKEY=VALUE Define variable, similar to .env-files. Can be set
\\ multiple times
\\
, .{config.APP_NAME});
}
pub fn printFormatHelp() void {
debug(
\\{0s} v{1s} - Simple API Tester - format help
\\ For more details, please see: https://github.com/michaelo/sapt/
\\
\\Variable-files (must have extension .env):
\\ MYVAR=value
\\ USERNAME=Admin
\\ PASSWORD=<PASSWORD>
\\
\\Test-files (must have extension .pi):
\\ > GET https://example.com/
\\ < 200
\\
\\ > POST https://example.com/protected/upload
\\ Authorization: Basic {{{{base64enc({{{{USERNAME}}}}:{{{{PASSWORD}}}})}}}}
\\ Content-Type: application/x-www-form-urlencoded
\\ --
\\ field=value&field2=othervalue
\\ < 200 string_that_must_be_found_to_be_considered_success
\\ # Extraction entries:
\\ # A variable will be created if the rightmost expression is found. '()' is
\\ # a placeholder for the value to extract.
\\ # E.g. if the response is: id=123&result=true, then the following will create
\\ # a variable named "RESULT_ID" with the value "123", which can be reused in
\\ # later tests:
\\ RESULT_ID=id=()&result=true
\\
\\Playbook-files (recommended to have extension .book):
\\ # Import variables from file which can be accessed in any following tests
\\ @../globals/some_env_file.env
\\
\\ # Define variable which can be accessed in any following tests
\\ SOME_VAR=value
\\
\\ # Import/execute test from file
\\ @my_test.pi
\\
\\ # Att: imports are relative to playbook
\\
\\ # In-file test, format just as in .pi-files
\\ > GET https://example.com/
\\ < 200
\\
\\Functions:
\\ sapt has a couple convenience-functions that can be used in tests and variable-definitions
\\ * {{{{base64enc(value)}}}} - base64-encodes the value
\\ * {{{{env(key)}}}} - attempts to look up the environment-variable 'key' from the operating system.
\\
\\
, .{config.APP_NAME, config.APP_VERSION});
}
fn argIs(arg: []const u8, full: []const u8, short: ?[]const u8) bool {
return std.mem.eql(u8, arg, full) or std.mem.eql(u8, arg, short orelse "XXX");
}
fn argHasValue(arg: []const u8, full: []const u8, short: ?[]const u8) ?[]const u8 {
var eq_pos = std.mem.indexOf(u8, arg, "=") orelse return null;
var key = arg[0..eq_pos];
if(argIs(key, full, short)) {
return arg[eq_pos + 1 ..];
} else return null;
}
test "argIs" {
try testing.expect(argIs("--verbose", "--verbose", "-v"));
try testing.expect(argIs("-v", "--verbose", "-v"));
try testing.expect(!argIs("--something-else", "--verbose", "-v"));
try testing.expect(argIs("--verbose", "--verbose", null));
try testing.expect(!argIs("-v", "--verbose", null));
}
test "argHasValue" {
try testing.expect(argHasValue("--playbook=mybook", "--playbook", "-b") != null);
try testing.expect(argHasValue("-b=mybook", "--playbook", "-b") != null);
}
pub fn parseArgs(args: [][]const u8, maybe_variables: ?*kvstore.KvStore) !AppArguments {
var result: AppArguments = .{};
if(args.len < 1) {
return error.NoArguments;
}
for (args) |arg| {
// Flags
if(argIs(arg, "--help", "-h")) {
printHelp(true);
return error.OkExit;
}
if(argIs(arg, "--help-format", null)) {
printFormatHelp();
return error.OkExit;
}
if(argIs(arg, "--version", null)) {
debug("{0s} v{1s}\n", .{config.APP_NAME, config.APP_VERSION});
return error.OkExit;
}
if(argIs(arg, "--multithread", "-m")) {
result.multithreaded = true;
continue;
}
if(argIs(arg, "--early-quit", "-e")) {
result.early_quit = true;
continue;
}
if(argIs(arg, "--pretty", "-p")) {
result.show_pretty_response_data = true;
continue;
}
if(argIs(arg, "--show-response", "-d")) {
result.show_response_data = true;
continue;
}
if(argIs(arg, "--silent", "-s")) {
result.silent = true;
result.verbose = false;
continue;
}
if(!result.silent and argIs(arg, "--verbose", "-v")) {
result.verbose = true;
continue;
}
if(!result.silent and argIs(arg, "--verbose-curl", null)) {
result.verbose_curl = true;
continue;
}
if(argIs(arg, "--insecure", null)) {
result.ssl_insecure = true;
continue;
}
// Value-parameters
if(argHasValue(arg, "--initial-vars", "-i")) |value| {
try result.input_vars_file.appendSlice(value);
continue;
}
if(argHasValue(arg, "--playbook", "-b")) |value| {
try result.playbook_file.appendSlice(value);
continue;
}
if(argHasValue(arg, "--delay", null)) |value| {
result.delay = std.fmt.parseUnsigned(u64, value, 10) catch {
err("WARNING: Could not parse value of {s} as a positive number\n", .{arg});
return error.InvalidArgument;
};
continue;
}
if(argHasValue(arg, "--colors", null)) |value| {
result.colors = std.meta.stringToEnum(Console.ColorConfig, value) orelse return error.InvalidArgument;
continue;
}
if(maybe_variables) |variables| if(std.mem.startsWith(u8, arg, "-D")) {
// Found variable-entry
try variables.addFromBuffer(arg[2..], .KeepFirst);
continue;
};
// Unhandled flag/arg?
if(std.mem.startsWith(u8, arg, "-")) {
err("ERROR: Unknown parameter '{s}'\n", .{arg});
return error.InvalidArgument;
}
// Assume ordinary files
result.files.append(FilePathEntry.fromSlice(arg) catch {
return error.TooLongFilename;
}) catch {
return error.TooManyFiles;
};
}
return result;
}
test "parseArgs colors" {
// Default
{
var myargs = [_][]const u8{"dummyarg"};
var parsed_args = try parseArgs(myargs[0..], null);
try testing.expectEqual(Console.ColorConfig.auto, parsed_args.colors);
}
// Checking all alternatives
{
var myargs = [_][]const u8{"--colors=auto"};
var parsed_args = try parseArgs(myargs[0..], null);
try testing.expectEqual(Console.ColorConfig.auto, parsed_args.colors);
}
{
var myargs = [_][]const u8{"--colors=on"};
var parsed_args = try parseArgs(myargs[0..], null);
try testing.expectEqual(Console.ColorConfig.on, parsed_args.colors);
}
{
var myargs = [_][]const u8{"--colors=off"};
var parsed_args = try parseArgs(myargs[0..], null);
try testing.expectEqual(Console.ColorConfig.off, parsed_args.colors);
}
{
var myargs = [_][]const u8{"--colors=blah"};
try testing.expectError(error.InvalidArgument, parseArgs(myargs[0..], null));
}
}
test "parseArgs verbosity" {
{
var myargs = [_][]const u8{"dummyarg"};
var parsed_args = try parseArgs(myargs[0..], null);
try testing.expect(!parsed_args.verbose);
try testing.expect(!parsed_args.verbose_curl);
}
{
var myargs = [_][]const u8{"-v"};
var parsed_args = try parseArgs(myargs[0..], null);
try testing.expect(parsed_args.verbose);
}
{
var myargs = [_][]const u8{"--verbose"};
var parsed_args = try parseArgs(myargs[0..], null);
try testing.expect(parsed_args.verbose);
}
{
var myargs = [_][]const u8{"--verbose-curl"};
var parsed_args = try parseArgs(myargs[0..], null);
try testing.expect(parsed_args.verbose_curl);
}
}
test "parseArgs multithread" {
{
var myargs = [_][]const u8{"dummyarg"};
var parsed_args = try parseArgs(myargs[0..], null);
try testing.expect(!parsed_args.multithreaded);
}
{
var myargs = [_][]const u8{"-m"};
var parsed_args = try parseArgs(myargs[0..], null);
try testing.expect(parsed_args.multithreaded);
}
{
var myargs = [_][]const u8{"--multithread"};
var parsed_args = try parseArgs(myargs[0..], null);
try testing.expect(parsed_args.multithreaded);
}
}
test "parseArgs playbook" {
{
var myargs = [_][]const u8{"dummyarg"};
var parsed_args = try parseArgs(myargs[0..], null);
try testing.expect(parsed_args.playbook_file.slice().len == 0);
}
{
var myargs = [_][]const u8{"-b=myplaybook"};
var parsed_args = try parseArgs(myargs[0..], null);
try testing.expectEqualStrings("myplaybook", parsed_args.playbook_file.slice());
}
{
var myargs = [_][]const u8{"--playbook=myplaybook"};
var parsed_args = try parseArgs(myargs[0..], null);
try testing.expectEqualStrings("myplaybook", parsed_args.playbook_file.slice());
}
}
test "parseArgs input vars" {
{
var myargs = [_][]const u8{"dummyarg"};
var parsed_args = try parseArgs(myargs[0..], null);
try testing.expect(parsed_args.input_vars_file.slice().len == 0);
}
{
var myargs = [_][]const u8{"-i=myvars.env"};
var parsed_args = try parseArgs(myargs[0..], null);
try testing.expectEqualStrings("myvars.env", parsed_args.input_vars_file.slice());
}
{
var myargs = [_][]const u8{"--initial-vars=myvars.env"};
var parsed_args = try parseArgs(myargs[0..], null);
try testing.expectEqualStrings("myvars.env", parsed_args.input_vars_file.slice());
}
}
test "parseArgs show response" {
{
var myargs = [_][]const u8{"dummyarg"};
var parsed_args = try parseArgs(myargs[0..], null);
try testing.expect(!parsed_args.show_response_data);
}
{
var myargs = [_][]const u8{"-d"};
var parsed_args = try parseArgs(myargs[0..], null);
try testing.expect(parsed_args.show_response_data);
}
{
var myargs = [_][]const u8{"--show-response"};
var parsed_args = try parseArgs(myargs[0..], null);
try testing.expect(parsed_args.show_response_data);
}
}
test "parseArgs pretty" {
{
var myargs = [_][]const u8{"dummyarg"};
var parsed_args = try parseArgs(myargs[0..], null);
try testing.expect(!parsed_args.show_pretty_response_data);
}
{
var myargs = [_][]const u8{"-p"};
var parsed_args = try parseArgs(myargs[0..], null);
try testing.expect(parsed_args.show_pretty_response_data);
}
{
var myargs = [_][]const u8{"--pretty"};
var parsed_args = try parseArgs(myargs[0..], null);
try testing.expect(parsed_args.show_pretty_response_data);
}
}
test "parseArgs early-quit" {
{
var myargs = [_][]const u8{"dummyarg"};
var parsed_args = try parseArgs(myargs[0..], null);
try testing.expect(!parsed_args.early_quit);
}
{
var myargs = [_][]const u8{"-e"};
var parsed_args = try parseArgs(myargs[0..], null);
try testing.expect(parsed_args.early_quit);
}
{
var myargs = [_][]const u8{"--early-quit"};
var parsed_args = try parseArgs(myargs[0..], null);
try testing.expect(parsed_args.early_quit);
}
}
test "parseArgs showHelp" {
{
var myargs = [_][]const u8{"-h"};
try testing.expectError(error.OkExit, parseArgs(myargs[0..], null));
}
{
var myargs = [_][]const u8{"--help"};
try testing.expectError(error.OkExit, parseArgs(myargs[0..], null));
}
}
test "parseArgs files" {
{
var myargs = [_][]const u8{"somefile"};
var parsed_args = try parseArgs(myargs[0..], null);
try testing.expect(parsed_args.files.slice().len == 1);
try testing.expectEqualStrings("somefile", parsed_args.files.get(0).slice());
}
}
test "parseArgs -DKEY=VALUE" {
{
var myargs = [_][]const u8{"-DKEY=VALUE"};
var variables = kvstore.KvStore{};
_ = try parseArgs(myargs[0..], &variables);
try testing.expect(variables.slice().len == 1);
try testing.expectEqualStrings("VALUE", variables.get("KEY").?);
}
}
/// For debug
fn dumpFileList(files: []FilePathEntry) void {
for (files) |itm, idx| {
debug("{d}: {s}\n", .{idx, itm.constSlice()});
}
}
pub fn processInputFileArguments(comptime max_files: usize, files: *std.BoundedArray(FilePathEntry, max_files)) !void {
// Fail on files not matching expected name-pattern
// Expand folders
// Verify that files exists and are readable
var cwd = fs.cwd();
const readFlags = std.fs.File.OpenFlags{ .read = true };
{
var i: usize = 0;
var file: *FilePathEntry = undefined;
while (i < files.slice().len) : (i += 1) {
file = &files.get(i);
// Verify that file/folder exists, otherwise fail
cwd.access(file.constSlice(), readFlags) catch {
debug("Can not access '{s}'\n", .{file.slice()});
return error.NoSuchFileOrFolder;
};
// Try to open as dir
var dir = cwd.openDir(file.constSlice(), .{ .iterate = true }) catch |e| switch (e) {
// Not a dir, that's OK
error.NotDir => continue,
else => return error.UnknownError,
};
defer dir.close();
var d_it = dir.iterate();
var dir_slice_start = i;
while (try d_it.next()) |a_path| {
var stat = try (try dir.openFile(a_path.name, readFlags)).stat();
switch (stat.kind) {
.File => {
var item = utils.initBoundedArray(u8, config.MAX_PATH_LEN);
try item.appendSlice(file.constSlice());
try item.appendSlice("/");
try item.appendSlice(a_path.name);
// Add to files at spot of folder - pushing it further back in the list
try files.insert(i, item);
i+=1;
},
.Directory => {
// debug("Found subdir: {s}\n", .{a_path.name});
// If recursive: process?
},
else => {},
}
}
// Remove folder entry - don't need it
_= files.orderedRemove(i);
i -= 1;
// Ensure folder-entries is sorted
std.sort.sort(FilePathEntry, files.slice()[dir_slice_start..i+1], {}, struct {
fn func(context: void, a: FilePathEntry, b: FilePathEntry) bool {
_ = context;
return std.mem.lessThan(u8, a.constSlice(), b.constSlice());
}
}.func);
}
}
}
test "processInputFileArguments" {
var files: std.BoundedArray(FilePathEntry, 128) = utils.initBoundedArray(FilePathEntry, 128);
try files.append(try FilePathEntry.fromSlice("testdata/01-warnme"));
try processInputFileArguments(128, &files);
// TODO: Verify all elements are parsed and in proper order
// Cases:
// * If file, no need to expand
// * If folder and no -r, expand contents only one leve
// * If folder and -r, expand end recurse
} | src/argparse.zig |
const gllparser = @import("../gllparser/gllparser.zig");
const Error = gllparser.Error;
const Parser = gllparser.Parser;
const ParserContext = gllparser.Context;
const Result = gllparser.Result;
const NodeName = gllparser.NodeName;
const Literal = @import("../parser/literal.zig").Literal;
const LiteralValue = @import("../parser/literal.zig").Value;
const std = @import("std");
const testing = std.testing;
const mem = std.mem;
pub fn Context(comptime Payload: type, comptime Value: type) type {
return *Parser(Payload, Value);
}
/// Wraps the `input.parser`, making it an optional parser producing an optional value.
///
/// The `input.parser` must remain alive for as long as the `Optional` parser will be used.
pub fn Optional(comptime Payload: type, comptime Value: type) type {
return struct {
parser: Parser(Payload, ?Value) = Parser(Payload, ?Value).init(parse, nodeName, deinit, countReferencesTo),
input: Context(Payload, Value),
const Self = @This();
pub fn init(allocator: mem.Allocator, input: Context(Payload, Value)) !*Parser(Payload, ?Value) {
const self = Self{ .input = input };
return try self.parser.heapAlloc(allocator, self);
}
pub fn initStack(input: Context(Payload, Value)) Self {
return Self{ .input = input };
}
pub fn deinit(parser: *Parser(Payload, ?Value), allocator: mem.Allocator, freed: ?*std.AutoHashMap(usize, void)) void {
const self = @fieldParentPtr(Self, "parser", parser);
self.input.deinit(allocator, freed);
}
pub fn countReferencesTo(parser: *const Parser(Payload, ?Value), other: usize, freed: *std.AutoHashMap(usize, void)) usize {
const self = @fieldParentPtr(Self, "parser", parser);
if (@ptrToInt(parser) == other) return 1;
return self.input.countReferencesTo(other, freed);
}
pub fn nodeName(parser: *const Parser(Payload, ?Value), node_name_cache: *std.AutoHashMap(usize, NodeName)) Error!u64 {
const self = @fieldParentPtr(Self, "parser", parser);
var v = std.hash_map.hashString("Optional");
v +%= try self.input.nodeName(node_name_cache);
return v;
}
pub fn parse(parser: *const Parser(Payload, ?Value), in_ctx: *const ParserContext(Payload, ?Value)) callconv(.Async) Error!void {
const self = @fieldParentPtr(Self, "parser", parser);
var ctx = in_ctx.with(self.input);
defer ctx.results.close();
const child_node_name = try ctx.input.nodeName(&in_ctx.memoizer.node_name_cache);
const child_ctx = try in_ctx.initChild(Value, child_node_name, ctx.offset);
defer child_ctx.deinitChild();
if (!child_ctx.existing_results) try ctx.input.parse(&child_ctx);
var sub = child_ctx.subscribe();
while (sub.next()) |next| {
switch (next.result) {
.err => try ctx.results.add(Result(?Value).init(ctx.offset, null)),
else => try ctx.results.add(Result(?Value).init(next.offset, next.result.value).toUnowned()),
}
}
return;
}
};
}
test "optional_some" {
nosuspend {
const allocator = testing.allocator;
const Payload = void;
const ctx = try ParserContext(Payload, ?LiteralValue).init(allocator, "hello world", {});
defer ctx.deinit();
const optional = try Optional(Payload, LiteralValue).init(allocator, (try Literal(Payload).init(allocator, "hello")).ref());
defer optional.deinit(allocator, null);
try optional.parse(&ctx);
var sub = ctx.subscribe();
var r1 = sub.next().?;
try testing.expectEqual(@as(usize, 5), r1.offset);
try testing.expectEqualStrings("hello", r1.result.value.?.value);
try testing.expectEqual(@as(?Result(?LiteralValue), null), sub.next());
}
}
test "optional_none" {
nosuspend {
const allocator = testing.allocator;
const Payload = void;
const ctx = try ParserContext(Payload, ?LiteralValue).init(allocator, "hello world", {});
defer ctx.deinit();
const optional = try Optional(Payload, LiteralValue).init(allocator, (try Literal(Payload).init(allocator, "world")).ref());
defer optional.deinit(allocator, null);
try optional.parse(&ctx);
var sub = ctx.subscribe();
var first = sub.next().?;
try testing.expectEqual(Result(?LiteralValue).init(0, null), first);
try testing.expect(sub.next() == null);
}
} | src/combn/combinator/optional.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const StringHashMap = std.StringHashMap;
const BufMap = std.BufMap;
const Buffer = std.Buffer;
const fixedBufferStream = std.io.fixedBufferStream;
const assert = std.debug.assert;
const OrbitMapParseError = error{FormatError};
const OrbitMap = struct {
alloc: *Allocator,
map: BufMap,
const Self = @This();
pub fn init(allocator: *Allocator) Self {
return Self{
.alloc = allocator,
.map = BufMap.init(alloc),
};
}
pub fn fromStream(allocator: *Allocator, stream: anytype) !Self {
var map = BufMap.init(allocator);
var result = Self{
.alloc = allocator,
.map = map,
};
while (stream.readUntilDelimiterAlloc(allocator, '\n', 1024)) |line| {
var iter = std.mem.split(line, ")");
const orbitee = iter.next() orelse return error.FormatError;
const orbiter = iter.next() orelse return error.FormatError;
try result.insertOrbit(orbitee, orbiter);
} else |e| switch (e) {
error.EndOfStream => {},
else => return e,
}
return result;
}
pub fn insertOrbit(self: *Self, orbitee: []const u8, orbiter: []const u8) !void {
try self.map.set(orbiter, orbitee);
}
pub fn orbitHierarchy(self: *Self, body: []const u8) !ArrayList([]const u8) {
var result = ArrayList([]const u8).init(self.alloc);
var currentBody = body;
while (!std.mem.eql(u8, currentBody, "")) {
try result.insert(0, currentBody);
currentBody = self.map.get(currentBody) orelse "";
}
return result;
}
pub fn distance(self: *Self, orig: []const u8, dest: []const u8) !usize {
const orig_hier = try self.orbitHierarchy(orig);
const dest_hier = try self.orbitHierarchy(dest);
// Find the common planet of both bodies
var common_planet: usize = 0;
for (orig_hier.items) |body, i| {
if (std.mem.eql(u8, body, dest_hier.items[i])) {
common_planet = i;
} else {
break;
}
}
// Return the final distance
const dist_orig_common = orig_hier.items.len - common_planet - 2;
const dist_common_dest = dest_hier.items.len - common_planet - 2;
return dist_orig_common + dist_common_dest;
}
};
test "count orbits" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = &arena.allocator;
defer arena.deinit();
var mem_stream = fixedBufferStream(
\\COM)B
\\B)C
\\C)D
\\D)E
\\E)F
\\B)G
\\G)H
\\D)I
\\E)J
\\J)K
\\K)L
\\K)YOU
\\I)SAN
\\
);
const stream = mem_stream.reader();
var orbit_map = try OrbitMap.fromStream(allocator, stream);
assert((try orbit_map.distance("YOU", "SAN")) == 4);
}
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = &arena.allocator;
defer arena.deinit();
const input_file = try std.fs.cwd().openFile("input06.txt", .{});
var input_stream = input_file.reader();
var orbit_map = try OrbitMap.fromStream(allocator, input_stream);
std.debug.warn("distance between you and santa: {}\n", .{try orbit_map.distance("YOU", "SAN")});
} | zig/06_2.zig |
const std = @import("std");
const c = @import("c.zig");
const msgpack = @import("msgpack.zig");
const blocking_queue = @import("blocking_queue.zig");
const RPCQueue = blocking_queue.BlockingQueue(msgpack.Value);
const RPC_TYPE_REQUEST: u32 = 0;
const RPC_TYPE_RESPONSE: u32 = 1;
const RPC_TYPE_NOTIFICATION: u32 = 2;
const Listener = struct {
input: std.fs.File.Reader, // This is the stdout of the RPC subprocess
event_queue: RPCQueue,
response_queue: RPCQueue,
alloc: *std.mem.Allocator,
fn run(self: *Listener) !void {
var buf: [1024 * 1024]u8 = undefined;
while (true) {
const in = try self.input.read(&buf);
if (in == 0) {
break;
} else if (in == buf.len) {
std.debug.panic("msgpack message is too long\n", .{});
}
var offset: usize = 0;
while (offset != in) {
const v = try msgpack.decode(self.alloc, buf[offset..in]);
if (v.data.Array[0] == .RawString) {
std.debug.print("{s}\n", .{v.data.Array[0].RawString});
return;
}
if (v.data.Array[0].UInt == RPC_TYPE_RESPONSE) {
try self.response_queue.put(v.data);
} else if (v.data.Array[0].UInt == RPC_TYPE_NOTIFICATION) {
try self.event_queue.put(v.data);
c.glfwPostEmptyEvent();
}
offset += v.offset;
}
std.debug.assert(offset == in);
}
try self.event_queue.put(msgpack.Value{ .Int = -1 });
c.glfwPostEmptyEvent();
}
};
pub const RPC = struct {
listener: *Listener,
output: std.fs.File.Writer, // This is the stdin of the RPC subprocess
process: *std.ChildProcess,
thread: std.Thread,
alloc: *std.mem.Allocator,
msgid: u32,
pub fn init(argv: []const []const u8, alloc: *std.mem.Allocator) !RPC {
const child = try std.ChildProcess.init(argv, alloc);
child.stdin_behavior = .Pipe;
child.stdout_behavior = .Pipe;
try child.spawn();
const out = (child.stdin orelse std.debug.panic("Could not get stdout", .{})).writer();
const listener = try alloc.create(Listener);
listener.* = .{
.event_queue = RPCQueue.init(alloc),
.response_queue = RPCQueue.init(alloc),
.input = (child.stdout orelse std.debug.panic("Could not get stdout", .{})).reader(),
.alloc = alloc,
};
const thread = try std.Thread.spawn(.{}, Listener.run, .{listener});
const rpc = .{
.listener = listener,
.output = out,
.process = child,
.alloc = alloc,
.thread = thread,
.msgid = 0,
};
return rpc;
}
pub fn get_event(self: *RPC) ?msgpack.Value {
return self.listener.event_queue.try_get();
}
pub fn release(self: *RPC, value: msgpack.Value) void {
value.destroy(self.alloc);
}
pub fn call_release(self: *RPC, method: []const u8, params: anytype) !void {
self.release(try self.call(method, params));
}
pub fn call(self: *RPC, method: []const u8, params: anytype) !msgpack.Value {
// We'll use an arena for the encoded message
var arena = std.heap.ArenaAllocator.init(self.alloc);
const tmp_alloc: *std.mem.Allocator = &arena.allocator;
defer arena.deinit();
// Push the serialized call to the subprocess's stdin
const p = try msgpack.Value.encode(tmp_alloc, params);
const v = try msgpack.Value.encode(tmp_alloc, .{ RPC_TYPE_REQUEST, self.msgid, method, p });
try v.serialize(self.output);
// Wait for a reply from the worker thread
const response = self.listener.response_queue.get();
defer self.release(response);
// Check that the msgids are correct
std.debug.assert(response.Array[1].UInt == self.msgid);
self.msgid = self.msgid +% 1;
// Check for error responses
const err = response.Array[2];
const result = response.Array[3];
if (err != std.meta.TagType(msgpack.Value).Nil) {
// TODO: handle error here
std.debug.panic("Got error in msgpack-rpc call: {}\n", .{err.Array[1]});
}
// Steal the result from the array, so it's not destroyed
response.Array[3] = .Nil;
// TODO: decode somehow?
return result;
}
pub fn deinit(self: *RPC) void {
self.process.deinit();
self.alloc.destroy(self.listener);
}
pub fn halt(self: *RPC) !std.ChildProcess.Term {
// Manually close stdin, to halt the subprocess on the other side
(self.process.stdin orelse unreachable).close();
self.process.stdin = null;
const term = try self.process.wait();
self.thread.join();
// Flush out the queue to avoid memory leaks
while (self.get_event()) |event| {
self.release(event);
}
return term;
}
}; | src/rpc.zig |
const std = @import("std");
const c = @import("gtk_c.zig");
const g = @import("gtk_lib.zig");
const io = @import("io_native.zig");
const RPC = @import("RPC.zig");
const mem = std.mem;
const ArrayList = std.ArrayList;
const mpack = @import("./mpack.zig");
const dbg = std.debug.print;
const Self = @This();
const io_mode = std.io.Mode.evented;
gpa: std.heap.GeneralPurposeAllocator(.{}),
child: *std.ChildProcess = undefined,
enc_buf: ArrayList(u8) = undefined,
key_buf: ArrayList(u8) = undefined,
buf: [1024]u8 = undefined,
decoder: mpack.Decoder = undefined,
rpc: RPC = undefined,
window: *c.GtkWindow = undefined,
da: *c.GtkWidget = undefined,
cs: ?*c.cairo_surface_t = null,
rows: u16 = 0,
cols: u16 = 0,
layout: *c.PangoLayout = undefined,
//font_name: []u8,
cell_width: u32 = 0,
cell_height: u32 = 0,
// TODO: this fails to build???
// decodeFrame: @Frame(RPC.decodeLoop) = undefined,
df: anyframe->RPC.RPCError!void = undefined,
fn get_self(data: c.gpointer) *Self {
return @ptrCast(*Self, @alignCast(@alignOf(Self), data));
}
fn key_pressed(_: *c.GtkEventControllerKey, keyval: c.guint, keycode: c.guint, mod: c.GdkModifierType, data: c.gpointer) callconv(.C) void {
_ = keycode;
var self = get_self(data);
self.onKeyPress(keyval, mod) catch @panic("We live inside of a dream!");
}
fn onKeyPress(self: *Self, keyval: c.guint, mod: c.guint) !void {
var special: ?[:0]const u8 = switch (keyval) {
c.GDK_KEY_Left => "Left",
c.GDK_KEY_Right => "Right",
else => null,
};
var x: [4]u8 = undefined;
var codepoint = c.gdk_keyval_to_unicode(keyval);
dbg("Hellooooo! {} {} {}\n", .{ keyval, mod, codepoint });
if (codepoint == 0 or codepoint > std.math.maxInt(u21)) {
return;
}
const len = std.unicode.utf8Encode(@intCast(u21, codepoint), x[0..x.len]) catch @panic("aaaah");
var did = false;
// TODO: be insane enough and just reuse enc_buf :]
defer self.key_buf.items.len = 0;
if ((mod & c.GDK_CONTROL_MASK) != 0 or special != null) {
try self.key_buf.appendSlice("<");
did = true;
}
if ((mod & c.GDK_CONTROL_MASK) != 0) {
try self.key_buf.appendSlice("c-");
}
try self.key_buf.appendSlice(x[0..len]);
if (did) {
try self.key_buf.appendSlice(">");
}
try self.doCommit(self.key_buf.items);
}
fn doCommit(self: *Self, str: []const u8) !void {
dbg("aha: {s}\n", .{str});
var encoder = mpack.encoder(self.enc_buf.writer());
try io.unsafe_input(encoder, str);
try self.child.stdin.?.writeAll(self.enc_buf.items);
try self.enc_buf.resize(0);
}
fn commit(_: *c.GtkIMContext, str: [*:0]const u8, data: c.gpointer) callconv(.C) void {
var self = get_self(data);
self.doCommit(str[0..mem.len(str)]) catch @panic("It was a dream!");
}
fn focus_enter(_: *c.GtkEventControllerFocus, data: c.gpointer) callconv(.C) void {
c.g_print("änter\n");
var im_context = @ptrCast(*c.GtkIMContext, @alignCast(@alignOf(c.GtkIMContext), data));
c.gtk_im_context_focus_in(im_context);
}
fn focus_leave(_: *c.GtkEventControllerFocus, data: c.gpointer) callconv(.C) void {
c.g_print("you must leave now\n");
var im_context = @ptrCast(*c.GtkIMContext, @alignCast(@alignOf(c.GtkIMContext), data));
c.gtk_im_context_focus_out(im_context);
}
fn on_stdout(_: ?*c.GIOChannel, cond: c.GIOCondition, data: c.gpointer) callconv(.C) c.gboolean {
_ = cond;
// dbg("DATTA\n", .{});
var self = get_self(data);
if (self.decoder.frame == null) {
dbg("The cow jumped over the moon\n", .{});
nosuspend await self.df catch @panic("mooooh");
return 0;
}
const oldlen = self.decoder.data.len;
if (oldlen > 0 and self.decoder.data.ptr != &self.buf) {
// TODO: avoid move if remaining space is plenty (like > 900)
mem.copy(u8, &self.buf, self.decoder.data);
}
var stdout = &self.child.stdout.?;
var lenny = stdout.read(self.buf[oldlen..]) catch @panic("call for help");
self.decoder.data = self.buf[0 .. oldlen + lenny];
resume self.decoder.frame.?;
while (self.rpc.frame) |frame| {
// NB: this doesn't mean specifically flush,
// but currently it is the only event rpc will return back
// to the main loop
self.flush() catch @panic("le panic");
resume frame;
}
return 1;
}
fn flush(self: *Self) !void {
dbg("le flush\n", .{});
try self.rpc.dumpGrid();
const grid = &self.rpc.grid[0];
// TODO: the right condition for "font[size] changed"
if (self.cell_height == 0) {
try self.set_font("JuliaMono 15");
}
if (self.rows != grid.rows or self.cols != grid.cols) {
dbg("le resize\n", .{});
self.rows = grid.rows;
self.cols = grid.cols;
const width = @intCast(c_int, self.cols * self.cell_width);
const height = @intCast(c_int, self.rows * self.cell_height);
dbg("LE METRICS {} {}", .{ width, height });
c.gtk_drawing_area_set_content_width(g.GTK_DRAWING_AREA(self.da), width);
c.gtk_drawing_area_set_content_height(g.GTK_DRAWING_AREA(self.da), height);
if (self.cs) |cs| {
c.cairo_surface_destroy(cs);
}
const surface = c.gtk_native_get_surface(g.g_cast(c.GtkNative, c.gtk_native_get_type(), self.window));
self.cs = c.gdk_surface_create_similar_surface(surface, c.CAIRO_CONTENT_COLOR, width, height);
}
}
fn pango_pixels_ceil(u: c_int) c_int {
return @divTrunc((u + (c.PANGO_SCALE - 1)), c.PANGO_SCALE);
}
fn set_font(self: *Self, font: [:0]const u8) !void {
// TODO: LEAK ALL THE THINGS!
// TODO: shorten the three-step dance?
const surface = c.gtk_native_get_surface(g.g_cast(c.GtkNative, c.gtk_native_get_type(), self.window));
// TODO: this seems dumb. check what a gtk4 gnome-terminal would do!
const dummy_surface = c.gdk_surface_create_similar_surface(surface, c.CAIRO_CONTENT_COLOR, 500, 500);
dbg("s {}\n", .{@ptrToInt(surface)});
//const cc = c.gdk_surface_create_cairo_context(surface);
// dbg("cc {}\n", .{@ptrToInt(cc)});
var cairo = c.cairo_create(dummy_surface);
dbg("cairso {}\n", .{@ptrToInt(cairo)});
var fontdesc = c.pango_font_description_from_string(font);
var pctx = c.pango_cairo_create_context(cairo);
c.pango_context_set_font_description(pctx, fontdesc);
var metrics = c.pango_context_get_metrics(pctx, fontdesc, c.pango_context_get_language(pctx));
var width = c.pango_font_metrics_get_approximate_char_width(metrics);
var height = c.pango_font_metrics_get_height(metrics);
self.cell_width = @intCast(u32, pango_pixels_ceil(width));
self.cell_height = @intCast(u32, pango_pixels_ceil(height));
dbg("le foont terrible {} {}\n", .{ self.cell_width, self.cell_height });
self.layout = c.pango_layout_new(pctx) orelse return error.AmIAloneInHere;
c.pango_layout_set_font_description(self.layout, fontdesc);
c.pango_layout_set_alignment(self.layout, c.PANGO_ALIGN_LEFT);
}
fn init(self: *Self) !void {
self.child = try io.spawn(&self.gpa.allocator);
self.enc_buf = ArrayList(u8).init(&self.gpa.allocator);
self.key_buf = ArrayList(u8).init(&self.gpa.allocator);
self.decoder = mpack.Decoder{ .data = self.buf[0..0] };
self.rpc = RPC.init(&self.gpa.allocator);
// TODO: this should not be allocated, but @Frame(RPC.decodeLoop) fails at module scope..
var decodeFrame = try self.gpa.allocator.create(@Frame(RPC.decodeLoop));
decodeFrame.* = async self.rpc.decodeLoop(&self.decoder);
self.df = decodeFrame;
var encoder = mpack.encoder(self.enc_buf.writer());
try io.attach_test(&encoder);
try self.child.stdin.?.writeAll(self.enc_buf.items);
try self.enc_buf.resize(0);
var gio = c.g_io_channel_unix_new(self.child.stdout.?.handle);
_ = c.g_io_add_watch(gio, c.G_IO_IN, on_stdout, self);
}
fn activate(app: *c.GtkApplication, data: c.gpointer) callconv(.C) void {
var self = get_self(data);
self.init() catch @panic("heeee");
var window: *c.GtkWidget = c.gtk_application_window_new(app);
self.window = g.GTK_WINDOW(window);
c.gtk_window_set_title(g.GTK_WINDOW(window), "Window");
c.gtk_window_set_default_size(g.GTK_WINDOW(window), 200, 200);
var box: *c.GtkWidget = c.gtk_box_new(c.GTK_ORIENTATION_HORIZONTAL, 0);
c.gtk_window_set_child(g.GTK_WINDOW(window), box);
self.da = c.gtk_drawing_area_new();
c.gtk_drawing_area_set_content_width(g.GTK_DRAWING_AREA(self.da), 500);
c.gtk_drawing_area_set_content_height(g.GTK_DRAWING_AREA(self.da), 500);
var key_ev = c.gtk_event_controller_key_new();
c.gtk_widget_add_controller(window, key_ev);
var im_context = c.gtk_im_multicontext_new();
// ibus on gtk4 has bug :(
// c.gtk_event_controller_key_set_im_context(g.g_cast(c.GtkEventControllerKey, c.gtk_event_controller_key_get_type(), key_ev), im_context);
c.gtk_im_context_set_client_widget(im_context, self.da);
c.gtk_im_context_set_use_preedit(im_context, c.FALSE);
_ = g.g_signal_connect(key_ev, "key-pressed", g.G_CALLBACK(key_pressed), self);
_ = g.g_signal_connect(im_context, "commit", g.G_CALLBACK(commit), self);
var focus_ev = c.gtk_event_controller_focus_new();
c.gtk_widget_add_controller(window, focus_ev);
// TODO: this does not work! (when ALT-TAB)
_ = g.g_signal_connect(focus_ev, "enter", g.G_CALLBACK(focus_enter), im_context);
_ = g.g_signal_connect(focus_ev, "leave", g.G_CALLBACK(focus_leave), im_context);
c.gtk_widget_set_focusable(window, 1);
c.gtk_widget_set_focusable(self.da, 1);
//_ = g.g_signal_connect_swapped(self.da, "clicked", g.G_CALLBACK(c.gtk_window_destroy), window);
c.gtk_box_append(g.GTK_BOX(box), self.da);
c.gtk_widget_show(window);
}
pub fn main() u8 {
var argc = @intCast(c_int, std.os.argv.len);
var argv = @ptrCast([*c][*c]u8, std.os.argv.ptr);
// TODO: can we refer directly to .gpa in further fields?
var self = Self{ .gpa = std.heap.GeneralPurposeAllocator(.{}){} };
var app: *c.GtkApplication = c.gtk_application_new("io.github.bfredl.zignvim", c.G_APPLICATION_FLAGS_NONE);
defer c.g_object_unref(@ptrCast(c.gpointer, app));
_ = g.g_signal_connect(app, "activate", g.G_CALLBACK(activate), &self);
var status = c.g_application_run(g.g_cast(c.GApplication, c.g_application_get_type(), app), argc, argv);
return @intCast(u8, status);
} | src/gtk_main.zig |
const process = @import("proc.zig");
const std = @import("std");
const Allocator = std.mem.Allocator;
pub const CPUFrame = packed struct {
tf_sp: u64, //0
tf_lr: u64, //8
tf_elr: u64, //16
tf_spsr: u32, //24
tf_esr: u32, //28
tf_x: [30]u64, //32
};
pub const Thread = struct {
next: ?*Thread,
prev: ?*Thread,
proc: *process.Process,
tid: u32,
// Kernel Stack PTR
stack_pointer: usize,
// Alignment better done some other way?
kernel_stack: [4096]u8 align(16),
};
pub fn create_default_thread(allocator: *Allocator, parent: *process.Process) !*Thread {
var newThread = try allocator.create(Thread);
newThread.tid = 2;
newThread.proc = parent;
newThread.next = undefined;
newThread.prev = undefined;
return newThread;
}
var thread_list: *Thread = undefined;
fn add_to_thread_list(new_thread: *Thread) void {
new_thread.next = thread_list;
new_thread.prev = undefined;
thread_list = new_thread;
}
pub fn create_initial_thread(allocator: *Allocator, thread_fn: fn () void) !*Thread {
var kernel_proc = process.createProcess(allocator) catch unreachable;
var newThread = try allocator.create(Thread);
newThread.tid = 1;
newThread.proc = kernel_proc;
newThread.next = undefined;
newThread.prev = undefined;
// Stack should start from the END of the array
newThread.stack_pointer = @ptrToInt(&newThread.kernel_stack[newThread.kernel_stack.len - 1]) - @sizeOf(CPUFrame);
var frame = @intToPtr(*CPUFrame, newThread.stack_pointer);
frame.tf_elr = 0;
frame.tf_lr = @ptrToInt(thread_fn);
frame.tf_sp = newThread.stack_pointer;
var spsr: u32 = 0;
spsr |= 1 << 0; // Dunno what this does..
spsr |= 1 << 2; // .M[3:2] = 0b100 --> Return to EL1
spsr |= 1 << 6; // FIQ masked
spsr |= 1 << 7; // IRQ masked
spsr |= 1 << 8; // SError (System Error) masked
spsr |= 1 << 9;
frame.tf_spsr = spsr;
add_to_thread_list(newThread);
return newThread;
}
pub fn current_thread() *Thread {
var thread_id: usize = 0;
//FIXME - I think this works only by accident
thread_id = asm volatile ("mrs %[thread_id], tpidr_el1"
: [thread_id] "=&r" (-> usize),
);
return @intToPtr(*Thread, thread_id);
}
pub fn yield() void {
//NAIVE ROUND ROBIN
var current = current_thread();
var next = current.next orelse thread_list;
switch_to(next);
}
extern fn _ctx_switch_to_initial(sp: usize) void;
pub fn switch_to_initial(thread: *Thread) void {
_ctx_switch_to_initial(@ptrToInt(thread));
}
extern fn _ctx_switch_to(old_thread: usize, new_thread: usize) void;
pub fn switch_to(thread: *Thread) void {
// Switch to new user space proc address space
// Call the platform code for switch_to_thread
// - Update the current ThreadID register value
// - Restore registers + ERET to same level
var current = current_thread();
//TODO: Check they are not the same, otherwise we just instant return
if (current != thread) {
_ctx_switch_to(@ptrToInt(current), @ptrToInt(thread));
}
// uart.write("Switching to process {} thread {}\n", .{thread.proc.pid, thread.tid});
} | kernel/src/thread.zig |
const std = @import("std");
const util = @import("util.zig");
const data = @embedFile("../data/day22.txt");
const Region3 = struct {
on: bool,
x0: i64,
x1: i64,
y0: i64,
y1: i64,
z0: i64,
z1: i64,
};
const Input = struct {
regions: std.ArrayList(Region3),
pub fn init(input_text: []const u8, allocator: std.mem.Allocator) !@This() {
_ = allocator;
var input = Input{
.regions = try std.ArrayList(Region3).initCapacity(std.testing.allocator, 420),
};
errdefer input.deinit();
var lines = std.mem.tokenize(u8, input_text, "\r\n");
while (lines.next()) |line| {
const on = if (line[1] == 'n') true else false;
var nums = std.mem.tokenize(u8, line, "onf xyz=.,");
const x0 = try parseInt(i64, nums.next().?, 10);
const x1 = try parseInt(i64, nums.next().?, 10);
const y0 = try parseInt(i64, nums.next().?, 10);
const y1 = try parseInt(i64, nums.next().?, 10);
const z0 = try parseInt(i64, nums.next().?, 10);
const z1 = try parseInt(i64, nums.next().?, 10);
input.regions.appendAssumeCapacity(Region3{
.on = on,
.x0 = x0,
.x1 = x1,
.y0 = y0,
.y1 = y1,
.z0 = z0,
.z1 = z1,
});
}
return input;
}
pub fn deinit(self: @This()) void {
self.regions.deinit();
}
};
fn intersection(r_old: Region3, r_new: Region3) ?Region3 {
const r = Region3{
.on = !r_old.on,
.x0 = std.math.max(r_old.x0, r_new.x0),
.y0 = std.math.max(r_old.y0, r_new.y0),
.z0 = std.math.max(r_old.z0, r_new.z0),
.x1 = std.math.min(r_old.x1, r_new.x1),
.y1 = std.math.min(r_old.y1, r_new.y1),
.z1 = std.math.min(r_old.z1, r_new.z1),
};
return if (r.x0 > r.x1 or r.y0 > r.y1 or r.z0 > r.z1) null else r;
}
fn volume(r: Region3) i64 {
const v: i64 = (1 + r.x1 - r.x0) * (1 + r.y1 - r.y0) * (1 + r.z1 - r.z0);
assert(v > 0);
return if (r.on) v else -v;
}
fn part1(input: Input) i64 {
var regions = std.ArrayList(Region3).initCapacity(std.testing.allocator, 40000) catch unreachable;
defer regions.deinit();
for (input.regions.items) |r_new| {
if (r_new.x0 > 50 or r_new.y0 > 50 or r_new.z0 > 50 or r_new.x1 < -50 or r_new.y1 < -50 or r_new.z1 < -50) {
continue;
}
const clip = Region3{
.on = r_new.on,
.x0 = std.math.max(r_new.x0, -50),
.y0 = std.math.max(r_new.y0, -50),
.z0 = std.math.max(r_new.z0, -50),
.x1 = std.math.min(r_new.x1, 50),
.y1 = std.math.min(r_new.y1, 50),
.z1 = std.math.min(r_new.z1, 50),
};
var i: usize = regions.items.len -% 1;
while (i < regions.items.len) : (i -%= 1) {
if (intersection(regions.items[i], clip)) |r| {
regions.appendAssumeCapacity(r);
}
}
if (clip.on) {
regions.appendAssumeCapacity(clip);
}
}
var count: i64 = 0;
for (regions.items) |r| {
count += volume(r);
assert(count > 0);
}
return count;
}
fn part2(input: Input) i64 {
var regions = std.ArrayList(Region3).initCapacity(std.testing.allocator, 40000) catch unreachable;
defer regions.deinit();
for (input.regions.items) |r_new| {
var i: usize = regions.items.len -% 1;
while (i < regions.items.len) : (i -%= 1) {
if (intersection(regions.items[i], r_new)) |r| {
regions.appendAssumeCapacity(r);
}
}
if (r_new.on) {
regions.appendAssumeCapacity(r_new);
}
}
var count: i64 = 0;
for (regions.items) |r| {
count += volume(r);
assert(count > 0);
}
return count;
}
const test_data1 =
\\on x=10..12,y=10..12,z=10..12
\\on x=11..13,y=11..13,z=11..13
\\off x=9..11,y=9..11,z=9..11
\\on x=10..10,y=10..10,z=10..10
;
const test_data2 =
\\on x=-20..26,y=-36..17,z=-47..7
\\on x=-20..33,y=-21..23,z=-26..28
\\on x=-22..28,y=-29..23,z=-38..16
\\on x=-46..7,y=-6..46,z=-50..-1
\\on x=-49..1,y=-3..46,z=-24..28
\\on x=2..47,y=-22..22,z=-23..27
\\on x=-27..23,y=-28..26,z=-21..29
\\on x=-39..5,y=-6..47,z=-3..44
\\on x=-30..21,y=-8..43,z=-13..34
\\on x=-22..26,y=-27..20,z=-29..19
\\off x=-48..-32,y=26..41,z=-47..-37
\\on x=-12..35,y=6..50,z=-50..-2
\\off x=-48..-32,y=-32..-16,z=-15..-5
\\on x=-18..26,y=-33..15,z=-7..46
\\off x=-40..-22,y=-38..-28,z=23..41
\\on x=-16..35,y=-41..10,z=-47..6
\\off x=-32..-23,y=11..30,z=-14..3
\\on x=-49..-5,y=-3..45,z=-29..18
\\off x=18..30,y=-20..-8,z=-3..13
\\on x=-41..9,y=-7..43,z=-33..15
\\on x=-54112..-39298,y=-85059..-49293,z=-27449..7877
\\on x=967..23432,y=45373..81175,z=27513..53682
;
const test_data3 =
\\on x=-5..47,y=-31..22,z=-19..33
\\on x=-44..5,y=-27..21,z=-14..35
\\on x=-49..-1,y=-11..42,z=-10..38
\\on x=-20..34,y=-40..6,z=-44..1
\\off x=26..39,y=40..50,z=-2..11
\\on x=-41..5,y=-41..6,z=-36..8
\\off x=-43..-33,y=-45..-28,z=7..25
\\on x=-33..15,y=-32..19,z=-34..11
\\off x=35..47,y=-46..-34,z=-11..5
\\on x=-14..36,y=-6..44,z=-16..29
\\on x=-57795..-6158,y=29564..72030,z=20435..90618
\\on x=36731..105352,y=-21140..28532,z=16094..90401
\\on x=30999..107136,y=-53464..15513,z=8553..71215
\\on x=13528..83982,y=-99403..-27377,z=-24141..23996
\\on x=-72682..-12347,y=18159..111354,z=7391..80950
\\on x=-1060..80757,y=-65301..-20884,z=-103788..-16709
\\on x=-83015..-9461,y=-72160..-8347,z=-81239..-26856
\\on x=-52752..22273,y=-49450..9096,z=54442..119054
\\on x=-29982..40483,y=-108474..-28371,z=-24328..38471
\\on x=-4958..62750,y=40422..118853,z=-7672..65583
\\on x=55694..108686,y=-43367..46958,z=-26781..48729
\\on x=-98497..-18186,y=-63569..3412,z=1232..88485
\\on x=-726..56291,y=-62629..13224,z=18033..85226
\\on x=-110886..-34664,y=-81338..-8658,z=8914..63723
\\on x=-55829..24974,y=-16897..54165,z=-121762..-28058
\\on x=-65152..-11147,y=22489..91432,z=-58782..1780
\\on x=-120100..-32970,y=-46592..27473,z=-11695..61039
\\on x=-18631..37533,y=-124565..-50804,z=-35667..28308
\\on x=-57817..18248,y=49321..117703,z=5745..55881
\\on x=14781..98692,y=-1341..70827,z=15753..70151
\\on x=-34419..55919,y=-19626..40991,z=39015..114138
\\on x=-60785..11593,y=-56135..2999,z=-95368..-26915
\\on x=-32178..58085,y=17647..101866,z=-91405..-8878
\\on x=-53655..12091,y=50097..105568,z=-75335..-4862
\\on x=-111166..-40997,y=-71714..2688,z=5609..50954
\\on x=-16602..70118,y=-98693..-44401,z=5197..76897
\\on x=16383..101554,y=4615..83635,z=-44907..18747
\\off x=-95822..-15171,y=-19987..48940,z=10804..104439
\\on x=-89813..-14614,y=16069..88491,z=-3297..45228
\\on x=41075..99376,y=-20427..49978,z=-52012..13762
\\on x=-21330..50085,y=-17944..62733,z=-112280..-30197
\\on x=-16478..35915,y=36008..118594,z=-7885..47086
\\off x=-98156..-27851,y=-49952..43171,z=-99005..-8456
\\off x=2032..69770,y=-71013..4824,z=7471..94418
\\on x=43670..120875,y=-42068..12382,z=-24787..38892
\\off x=37514..111226,y=-45862..25743,z=-16714..54663
\\off x=25699..97951,y=-30668..59918,z=-15349..69697
\\off x=-44271..17935,y=-9516..60759,z=49131..112598
\\on x=-61695..-5813,y=40978..94975,z=8655..80240
\\off x=-101086..-9439,y=-7088..67543,z=33935..83858
\\off x=18020..114017,y=-48931..32606,z=21474..89843
\\off x=-77139..10506,y=-89994..-18797,z=-80..59318
\\off x=8476..79288,y=-75520..11602,z=-96624..-24783
\\on x=-47488..-1262,y=24338..100707,z=16292..72967
\\off x=-84341..13987,y=2429..92914,z=-90671..-1318
\\off x=-37810..49457,y=-71013..-7894,z=-105357..-13188
\\off x=-27365..46395,y=31009..98017,z=15428..76570
\\off x=-70369..-16548,y=22648..78696,z=-1892..86821
\\on x=-53470..21291,y=-120233..-33476,z=-44150..38147
\\off x=-93533..-4276,y=-16170..68771,z=-104985..-24507
;
const part1_test1_solution: ?i64 = 39;
const part1_test2_solution: ?i64 = 590784;
const part1_solution: ?i64 = 546724;
const part2_test3_solution: ?i64 = 2758514936282235;
const part2_solution: ?i64 = 1346544039176841;
// Just boilerplate below here, nothing to see
fn testPart1() !void {
var test_input1 = try Input.init(test_data1, std.testing.allocator);
defer test_input1.deinit();
if (part1_test1_solution) |solution| {
try std.testing.expectEqual(solution, part1(test_input1));
}
var test_input2 = try Input.init(test_data2, std.testing.allocator);
defer test_input2.deinit();
if (part1_test2_solution) |solution| {
try std.testing.expectEqual(solution, part1(test_input2));
}
var timer = try std.time.Timer.start();
var input = try Input.init(data, std.testing.allocator);
defer input.deinit();
if (part1_solution) |solution| {
try std.testing.expectEqual(solution, part1(input));
print("part1 took {d:9.3}ms\n", .{@intToFloat(f64, timer.lap()) / 1000000.0});
}
}
fn testPart2() !void {
var test_input3 = try Input.init(test_data3, std.testing.allocator);
defer test_input3.deinit();
if (part2_test3_solution) |solution| {
try std.testing.expectEqual(solution, part2(test_input3));
}
var timer = try std.time.Timer.start();
var input = try Input.init(data, std.testing.allocator);
defer input.deinit();
if (part2_solution) |solution| {
try std.testing.expectEqual(solution, part2(input));
print("part2 took {d:9.3}ms\n", .{@intToFloat(f64, timer.lap()) / 1000000.0});
}
}
pub fn main() !void {
try testPart1();
try testPart2();
}
test "part1" {
try testPart1();
}
test "part2" {
try testPart2();
}
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const parseInt = std.fmt.parseInt;
const min = std.math.min;
const max = std.math.max;
const print = std.debug.print;
const expect = std.testing.expect;
const assert = std.debug.assert; | src/day22.zig |
const std = @import("std");
const alka = @import("alka");
const gui = alka.gui;
const m = alka.math;
usingnamespace alka.log;
pub const mlog = std.log.scoped(.app);
pub const log_level: std.log.Level = .info;
const virtualwidth: i32 = 1024;
const virtualheight: i32 = 768;
var vel: f32 = 0;
var dir: f32 = 1;
fn update(dt: f32) !void {
const canvas = try gui.getCanvas(0);
const pos = canvas.transform.getOriginated();
if (pos.x > 1024 - canvas.transform.size.x) {
dir = -1;
} else if (pos.x < 0) {
dir = 1;
}
vel += 100 * dt * dir;
try gui.update(dt);
}
fn fupdate(dt: f32) !void {
var canvas = try gui.getCanvasPtr(0);
var tr = try canvas.getTransformPtr(0);
//canvas.transform.position.x += vel;
//tr.position.x -= vel;
vel = 0;
try gui.fixed(dt);
}
fn draw() !void {
const canvas = try gui.getCanvas(0);
try gui.draw();
try canvas.drawLines(alka.Colour.rgba(255, 0, 0, 255));
}
fn resize(w: i32, h: i32) void {
alka.autoResize(virtualwidth, virtualheight, w, h);
}
fn updateButton(self: *gui.Element, dt: f32) !void {
mlog.info("update: {}", .{self.id.?});
}
fn fixedButton(self: *gui.Element, dt: f32) !void {
mlog.info("fixed update: {}", .{self.id.?});
}
fn drawButton(self: *gui.Element) !void {
try alka.drawRectangleAdv(
self.transform.getRectangleNoOrigin(),
self.transform.origin,
m.deg2radf(self.transform.rotation),
self.colour,
);
}
fn onCreateButton(self: *gui.Element) !void {
mlog.info("onCreate: {}", .{self.id.?});
}
fn onDestroyButton(self: *gui.Element) !void {
mlog.info("onDestroy: {}", .{self.id.?});
}
fn onEnterButton(self: *gui.Element, position: m.Vec2f, relativepos: m.Vec2f) !void {
mlog.notice("onEnter: {d}||{d} {d}||{d}", .{ position.x, position.y, relativepos.x, relativepos.y });
}
fn onHoverButton(self: *gui.Element, position: m.Vec2f, relativepos: m.Vec2f) !void {
mlog.notice("onHover: {d}||{d} {d}||{d}", .{ position.x, position.y, relativepos.x, relativepos.y });
}
fn onClickButton(self: *gui.Element, position: m.Vec2f, relativepos: m.Vec2f, button: alka.input.Mouse) !void {
mlog.notice("onClick[{}]: {d}||{d} {d}||{d}", .{ button, position.x, position.y, relativepos.x, relativepos.y });
}
fn onPressedButton(self: *gui.Element, position: m.Vec2f, relativepos: m.Vec2f, button: alka.input.Mouse) !void {
mlog.notice("onPressed[{}]: {d}||{d} {d}||{d}", .{ button, position.x, position.y, relativepos.x, relativepos.y });
}
fn onDownButton(self: *gui.Element, position: m.Vec2f, relativepos: m.Vec2f, button: alka.input.Mouse) !void {
mlog.notice("onDown[{}]: {d}||{d} {d}||{d}", .{ button, position.x, position.y, relativepos.x, relativepos.y });
}
fn onReleasedButton(self: *gui.Element, position: m.Vec2f, relativepos: m.Vec2f, button: alka.input.Mouse) !void {
mlog.notice("onReleased[{}]: {d}||{d} {d}||{d}", .{ button, position.x, position.y, relativepos.x, relativepos.y });
}
fn onExitButton(self: *gui.Element, position: m.Vec2f, relativepos: m.Vec2f) !void {
mlog.notice("onExit: {d}||{d} {d}||{d}", .{ position.x, position.y, relativepos.x, relativepos.y });
}
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const callbacks = alka.Callbacks{
.update = update,
.fixed = fupdate,
.draw = draw,
.resize = resize,
.close = null,
};
try alka.init(&gpa.allocator, callbacks, 1024, 768, "GUI", 0, true);
alka.autoResize(virtualwidth, virtualheight, 1024, 768);
var inp = alka.getInput();
try inp.bindMouse(.ButtonLeft);
try inp.bindMouse(.ButtonRight);
// init the GUI
try gui.init(alka.getAllocator());
// id, transform, colour
var canvas = try gui.createCanvas(0, m.Transform2D{
.position = m.Vec2f{ .x = 500, .y = 300 },
.origin = m.Vec2f{ .x = 250, .y = 150 },
.size = m.Vec2f{ .x = 500, .y = 300 },
.rotation = 0,
}, alka.Colour.rgba(255, 0, 0, 100));
// id, transform, colour, events
var element = try canvas.createElement(
0,
m.Transform2D{
.position = m.Vec2f{ .x = 100, .y = 200 },
.origin = m.Vec2f{ .x = 25, .y = 25 },
.size = m.Vec2f{ .x = 50, .y = 50 },
.rotation = 0,
},
alka.Colour.rgba(30, 80, 200, 255),
gui.Events{
.onCreate = onCreateButton,
.onDestroy = onDestroyButton,
//.onEnter = onEnterButton,
//.onHover = onHoverButton,
.onClick = onClickButton,
//.onPressed = onPressedButton,
//.onDown = onDownButton,
//.onReleased = onReleasedButton,
//.onExit = onExitButton,
//.update = updateButton,
//.fixed = fixedButton,
.draw = drawButton,
},
);
// id, transform, colour, events
var element2 = try canvas.createElement(
1,
m.Transform2D{
.position = m.Vec2f{ .x = 400, .y = 200 },
.origin = m.Vec2f{ .x = 25, .y = 25 },
.size = m.Vec2f{ .x = 50, .y = 50 },
.rotation = 0,
},
alka.Colour.rgba(255, 255, 255, 255),
gui.Events{
.onCreate = onCreateButton,
.onDestroy = onDestroyButton,
//.onEnter = onEnterButton,
//.onHover = onHoverButton,
//.onClick = onClickButton,
//.onPressed = onPressedButton,
//.onDown = onDownButton,
.onReleased = onReleasedButton,
//.onExit = onExitButton,
//.update = updateButton,
//.fixed = fixedButton,
.draw = drawButton,
},
);
// id
//try canvas.destroyElement(1);
try alka.open();
try alka.update();
try alka.close();
// deinit the GUI
try gui.deinit();
try alka.deinit();
const leaked = gpa.deinit();
if (leaked) return error.Leak;
} | examples/gui.zig |
const std = @import("std");
const ui = @import("ui.zig");
// Deprecated. No longer used due to move away from comptime Config.
/// Comptime config passed into ui.Module.
/// Contains type information about all the widgets that will be used in the module.
pub const Config = struct {
const Self = @This();
Imports: []const Import,
pub fn Layout(comptime self: Self) type {
return ui.LayoutContext(self);
}
pub fn Build(comptime self: Self) type {
return ui.BuildContext(self);
}
pub fn Init(comptime self: Self) type {
return ui.InitContext(self);
}
};
const ImportTag = enum(u2) {
/// Contains the Widget type.
/// This is the recommended way to create an import.
Type = 0,
/// Creates the type with a comptime template function. Currently not used due to compiler bug.
Template = 1,
/// Creates the type with a comptime module.Config, a container type, and the name of the child template function.
/// Currently crashes compiler when storing a comptime function so we store a type and name of fn decl instead.
/// This is currently not used.
ContainerTemplate = 2,
};
pub const Import = struct {
const Self = @This();
// Name used to reference the Widget. No longer used.
name: ?@Type(.EnumLiteral),
// For ContainerTypeTemplate.
container_type: ?type,
container_fn_name: ?[]const u8,
create_fn: ?fn (Config) type,
widget_type: ?type,
tag: ImportTag,
/// This is the recommended way to set an import.
pub fn init(comptime T: type) @This() {
return .{
.name = null,
.container_type = null,
.container_fn_name = null,
.create_fn = null,
.widget_type = T,
.tag = .Type,
};
}
pub fn initTemplate(comptime TemplateFn: fn (Config) type) Self {
return .{
.name = null,
.create_type = null,
.container_fn_name = null,
.create_fn = TemplateFn,
.widget_type = null,
.tag = .Template,
};
}
pub fn initContainerTemplate(comptime Container: type, TemplateFnName: []const u8) Self {
return .{
.name = null,
.container_type = Container,
.container_fn_name = TemplateFnName,
.create_fn = null,
.widget_type = null,
.tag = .ContainerTemplate,
};
}
pub fn initTypes(comptime args: anytype) []const Self {
var res: []const Self = &.{};
inline for (std.meta.fields(@TypeOf(args))) |f| {
const T = @field(args, f.name);
res = res ++ &[_]Self{init(T)};
}
return res;
}
pub fn initTypeSlice(comptime Types: []const type) []const Self {
var res: []const @This() = &.{};
for (Types) |T| {
res = res ++ &[_]@This(){init(T)};
}
return res;
}
}; | ui/src/config.zig |
const std = @import("std");
const assert = std.debug.assert;
const Compilation = @import("Compilation.zig");
const Source = @import("Source.zig");
const LangOpts = @import("LangOpts.zig");
const Tokenizer = @This();
pub const Token = struct {
id: Id,
source: Source.Id,
start: u32,
end: u32,
pub const Id = enum(u8) {
invalid,
nl,
eof,
identifier,
// string literals with prefixes
string_literal,
string_literal_utf_16,
string_literal_utf_8,
string_literal_utf_32,
string_literal_wide,
// <foobar> only generated by preprocessor
macro_string,
// char literals with prefixes
char_literal,
char_literal_utf_16,
char_literal_utf_32,
char_literal_wide,
// float literals with suffixes
float_literal,
float_literal_f,
float_literal_l,
// integer literals with suffixes
integer_literal,
integer_literal_u,
integer_literal_l,
integer_literal_lu,
integer_literal_ll,
integer_literal_llu,
/// Integer literal tokens generated by preprocessor.
one,
zero,
bang,
bang_equal,
pipe,
pipe_pipe,
pipe_equal,
equal,
equal_equal,
l_paren,
r_paren,
l_brace,
r_brace,
l_bracket,
r_bracket,
period,
ellipsis,
caret,
caret_equal,
plus,
plus_plus,
plus_equal,
minus,
minus_minus,
minus_equal,
asterisk,
asterisk_equal,
percent,
percent_equal,
arrow,
colon,
semicolon,
slash,
slash_equal,
comma,
ampersand,
ampersand_ampersand,
ampersand_equal,
question_mark,
angle_bracket_left,
angle_bracket_left_equal,
angle_bracket_angle_bracket_left,
angle_bracket_angle_bracket_left_equal,
angle_bracket_right,
angle_bracket_right_equal,
angle_bracket_angle_bracket_right,
angle_bracket_angle_bracket_right_equal,
tilde,
hash,
hash_hash,
/// Special token to speed up preprocessing, `loc.end` will be an index to the param list.
macro_param,
/// Special token to speed up preprocessing, `loc.end` will be an index to the param list.
stringify_param,
/// Same as stringify_param, but for var args
stringify_va_args,
/// Special token for when empty argument is passed to macro token.
empty_arg,
/// Special token used to prevent ## passed as arguments from being concatenated
hash_hash_from_param,
/// Special token used to expand arguments before other tokens.
identifier_from_param,
keyword_auto,
keyword_break,
keyword_case,
keyword_char,
keyword_const,
keyword_continue,
keyword_default,
keyword_do,
keyword_double,
keyword_else,
keyword_enum,
keyword_extern,
keyword_float,
keyword_for,
keyword_goto,
keyword_if,
keyword_int,
keyword_long,
keyword_register,
keyword_return,
keyword_short,
keyword_signed,
keyword_sizeof,
keyword_static,
keyword_struct,
keyword_switch,
keyword_typedef,
keyword_typeof1,
keyword_typeof2,
keyword_union,
keyword_unsigned,
keyword_void,
keyword_volatile,
keyword_while,
// ISO C99
keyword_bool,
keyword_complex,
keyword_imaginary,
keyword_inline,
keyword_restrict,
// ISO C11
keyword_alignas,
keyword_alignof,
keyword_atomic,
keyword_generic,
keyword_noreturn,
keyword_static_assert,
keyword_thread_local,
// Preprocessor directives
keyword_include,
keyword_define,
keyword_defined,
keyword_undef,
keyword_ifdef,
keyword_ifndef,
keyword_elif,
keyword_endif,
keyword_error,
keyword_pragma,
keyword_line,
keyword_va_args,
// gcc keywords
keyword_const1,
keyword_const2,
keyword_volatile1,
keyword_volatile2,
keyword_restrict1,
keyword_restrict2,
keyword_alignof1,
keyword_alignof2,
keyword_typeof,
/// Return true if token is identifier or keyword.
pub fn isMacroIdentifier(id: Id) bool {
switch (id) {
.keyword_include,
.keyword_define,
.keyword_defined,
.keyword_undef,
.keyword_ifdef,
.keyword_ifndef,
.keyword_elif,
.keyword_endif,
.keyword_error,
.keyword_pragma,
.keyword_line,
.keyword_va_args,
.keyword_auto,
.keyword_break,
.keyword_case,
.keyword_char,
.keyword_const,
.keyword_continue,
.keyword_default,
.keyword_do,
.keyword_double,
.keyword_else,
.keyword_enum,
.keyword_extern,
.keyword_float,
.keyword_for,
.keyword_goto,
.keyword_if,
.keyword_int,
.keyword_long,
.keyword_register,
.keyword_return,
.keyword_short,
.keyword_signed,
.keyword_sizeof,
.keyword_static,
.keyword_struct,
.keyword_switch,
.keyword_typedef,
.keyword_union,
.keyword_unsigned,
.keyword_void,
.keyword_volatile,
.keyword_while,
.keyword_bool,
.keyword_complex,
.keyword_imaginary,
.keyword_inline,
.keyword_restrict,
.keyword_alignas,
.keyword_alignof,
.keyword_atomic,
.keyword_generic,
.keyword_noreturn,
.keyword_static_assert,
.keyword_thread_local,
.identifier,
.keyword_typeof,
.keyword_typeof1,
.keyword_typeof2,
=> return true,
else => return false,
}
}
/// Turn macro keywords into identifiers.
pub fn simplifyMacroKeyword(id: *Id) void {
switch (id.*) {
.keyword_include,
.keyword_define,
.keyword_defined,
.keyword_undef,
.keyword_ifdef,
.keyword_ifndef,
.keyword_elif,
.keyword_endif,
.keyword_error,
.keyword_pragma,
.keyword_line,
.keyword_va_args,
=> id.* = .identifier,
else => {},
}
}
pub fn lexeme(id: Id) ?[]const u8 {
return switch (id) {
.invalid,
.identifier,
.identifier_from_param,
.string_literal,
.string_literal_utf_16,
.string_literal_utf_8,
.string_literal_utf_32,
.string_literal_wide,
.char_literal,
.char_literal_utf_16,
.char_literal_utf_32,
.char_literal_wide,
.float_literal,
.float_literal_f,
.float_literal_l,
.integer_literal,
.integer_literal_u,
.integer_literal_l,
.integer_literal_lu,
.integer_literal_ll,
.integer_literal_llu,
.macro_string,
=> null,
.zero => "0",
.one => "1",
.nl,
.eof,
.macro_param,
.stringify_param,
.stringify_va_args,
.empty_arg,
=> "",
.bang => "!",
.bang_equal => "!=",
.pipe => "|",
.pipe_pipe => "||",
.pipe_equal => "|=",
.equal => "=",
.equal_equal => "==",
.l_paren => "(",
.r_paren => ")",
.l_brace => "{",
.r_brace => "}",
.l_bracket => "[",
.r_bracket => "]",
.period => ".",
.ellipsis => "...",
.caret => "^",
.caret_equal => "^=",
.plus => "+",
.plus_plus => "++",
.plus_equal => "+=",
.minus => "-",
.minus_minus => "--",
.minus_equal => "-=",
.asterisk => "*",
.asterisk_equal => "*=",
.percent => "%",
.percent_equal => "%=",
.arrow => "->",
.colon => ":",
.semicolon => ";",
.slash => "/",
.slash_equal => "/=",
.comma => ",",
.ampersand => "&",
.ampersand_ampersand => "&&",
.ampersand_equal => "&=",
.question_mark => "?",
.angle_bracket_left => "<",
.angle_bracket_left_equal => "<=",
.angle_bracket_angle_bracket_left => "<<",
.angle_bracket_angle_bracket_left_equal => "<<=",
.angle_bracket_right => ">",
.angle_bracket_right_equal => ">=",
.angle_bracket_angle_bracket_right => ">>",
.angle_bracket_angle_bracket_right_equal => ">>=",
.tilde => "~",
.hash => "#",
.hash_hash, .hash_hash_from_param => "##",
.keyword_auto => "auto",
.keyword_break => "break",
.keyword_case => "case",
.keyword_char => "char",
.keyword_const => "const",
.keyword_continue => "continue",
.keyword_default => "default",
.keyword_do => "do",
.keyword_double => "double",
.keyword_else => "else",
.keyword_enum => "enum",
.keyword_extern => "extern",
.keyword_float => "float",
.keyword_for => "for",
.keyword_goto => "goto",
.keyword_if => "if",
.keyword_int => "int",
.keyword_long => "long",
.keyword_register => "register",
.keyword_return => "return",
.keyword_short => "short",
.keyword_signed => "signed",
.keyword_sizeof => "sizeof",
.keyword_static => "static",
.keyword_struct => "struct",
.keyword_switch => "switch",
.keyword_typedef => "typedef",
.keyword_typeof => "typeof",
.keyword_union => "union",
.keyword_unsigned => "unsigned",
.keyword_void => "void",
.keyword_volatile => "volatile",
.keyword_while => "while",
.keyword_bool => "_Bool",
.keyword_complex => "_Complex",
.keyword_imaginary => "_Imaginary",
.keyword_inline => "inline",
.keyword_restrict => "restrict",
.keyword_alignas => "_Alignas",
.keyword_alignof => "_Alignof",
.keyword_atomic => "_Atomic",
.keyword_generic => "_Generic",
.keyword_noreturn => "_Noreturn",
.keyword_static_assert => "_Static_assert",
.keyword_thread_local => "_Thread_local",
.keyword_include => "include",
.keyword_define => "define",
.keyword_defined => "defined",
.keyword_undef => "undef",
.keyword_ifdef => "ifdef",
.keyword_ifndef => "ifndef",
.keyword_elif => "elif",
.keyword_endif => "endif",
.keyword_error => "error",
.keyword_pragma => "pragma",
.keyword_line => "line",
.keyword_va_args => "__VA_ARGS__",
.keyword_const1 => "__const",
.keyword_const2 => "__const__",
.keyword_volatile1 => "__volatile",
.keyword_volatile2 => "__volatile__",
.keyword_restrict1 => "__restrict",
.keyword_restrict2 => "__restrict__",
.keyword_alignof1 => "__alignof",
.keyword_alignof2 => "__alignof__",
.keyword_typeof1 => "__typeof",
.keyword_typeof2 => "__typeof__",
};
}
pub fn symbol(id: Id) []const u8 {
return id.lexeme() orelse switch (id) {
.macro_string, .invalid => unreachable,
.identifier => "an identifier",
.string_literal,
.string_literal_utf_16,
.string_literal_utf_8,
.string_literal_utf_32,
.string_literal_wide,
=> "a string literal",
.char_literal,
.char_literal_utf_16,
.char_literal_utf_32,
.char_literal_wide,
=> "a character literal",
.float_literal,
.float_literal_f,
.float_literal_l,
=> "a float literal",
.integer_literal,
.integer_literal_u,
.integer_literal_l,
.integer_literal_lu,
.integer_literal_ll,
.integer_literal_llu,
=> "an integer literal",
else => unreachable, // handled in lexeme
};
}
};
/// double underscore and underscore + capital letter identifiers
/// belong to the implementation namespace, so we always convert them
/// to keywords.
/// TODO: add `.keyword_asm` here as GNU extension once that is supported.
pub fn getTokenId(comp: *const Compilation, str: []const u8) Token.Id {
const kw = all_kws.get(str) orelse return .identifier;
const standard = comp.langopts.standard;
return switch (kw) {
.keyword_inline => if (standard.isGNU() or standard.atLeast(.c99)) kw else .identifier,
.keyword_restrict => if (standard.atLeast(.c99)) kw else .identifier,
.keyword_typeof => if (standard.isGNU()) kw else .identifier,
else => kw,
};
}
const all_kws = std.ComptimeStringMap(Id, .{
.{ "auto", .keyword_auto },
.{ "break", .keyword_break },
.{ "case", .keyword_case },
.{ "char", .keyword_char },
.{ "const", .keyword_const },
.{ "continue", .keyword_continue },
.{ "default", .keyword_default },
.{ "do", .keyword_do },
.{ "double", .keyword_double },
.{ "else", .keyword_else },
.{ "enum", .keyword_enum },
.{ "extern", .keyword_extern },
.{ "float", .keyword_float },
.{ "for", .keyword_for },
.{ "goto", .keyword_goto },
.{ "if", .keyword_if },
.{ "int", .keyword_int },
.{ "long", .keyword_long },
.{ "register", .keyword_register },
.{ "return", .keyword_return },
.{ "short", .keyword_short },
.{ "signed", .keyword_signed },
.{ "sizeof", .keyword_sizeof },
.{ "static", .keyword_static },
.{ "struct", .keyword_struct },
.{ "switch", .keyword_switch },
.{ "typedef", .keyword_typedef },
.{ "union", .keyword_union },
.{ "unsigned", .keyword_unsigned },
.{ "void", .keyword_void },
.{ "volatile", .keyword_volatile },
.{ "while", .keyword_while },
.{ "__typeof__", .keyword_typeof2 },
.{ "__typeof", .keyword_typeof1 },
// ISO C99
.{ "_Bool", .keyword_bool },
.{ "_Complex", .keyword_complex },
.{ "_Imaginary", .keyword_imaginary },
.{ "inline", .keyword_inline },
.{ "restrict", .keyword_restrict },
// ISO C11
.{ "_Alignas", .keyword_alignas },
.{ "_Alignof", .keyword_alignof },
.{ "_Atomic", .keyword_atomic },
.{ "_Generic", .keyword_generic },
.{ "_Noreturn", .keyword_noreturn },
.{ "_Static_assert", .keyword_static_assert },
.{ "_Thread_local", .keyword_thread_local },
// Preprocessor directives
.{ "include", .keyword_include },
.{ "define", .keyword_define },
.{ "defined", .keyword_defined },
.{ "undef", .keyword_undef },
.{ "ifdef", .keyword_ifdef },
.{ "ifndef", .keyword_ifndef },
.{ "elif", .keyword_elif },
.{ "endif", .keyword_endif },
.{ "error", .keyword_error },
.{ "pragma", .keyword_pragma },
.{ "line", .keyword_line },
.{ "__VA_ARGS__", .keyword_va_args },
// gcc keywords
.{ "__const", .keyword_const1 },
.{ "__const__", .keyword_const2 },
.{ "__volatile", .keyword_volatile1 },
.{ "__volatile__", .keyword_volatile2 },
.{ "__restrict", .keyword_restrict1 },
.{ "__restrict__", .keyword_restrict2 },
.{ "__alignof", .keyword_alignof1 },
.{ "__alignof__", .keyword_alignof2 },
.{ "typeof", .keyword_typeof },
});
};
buf: []const u8,
index: u32 = 0,
source: Source.Id,
comp: *const Compilation,
pub fn next(self: *Tokenizer) Token {
var state: enum {
start,
cr,
back_slash,
back_slash_cr,
u,
u8,
U,
L,
string_literal,
char_literal_start,
char_literal,
escape_sequence,
cr_escape,
octal_escape,
hex_escape,
unicode_escape,
identifier,
equal,
bang,
pipe,
percent,
asterisk,
plus,
angle_bracket_left,
angle_bracket_angle_bracket_left,
angle_bracket_right,
angle_bracket_angle_bracket_right,
caret,
period,
period2,
minus,
slash,
ampersand,
hash,
line_comment,
multi_line_comment,
multi_line_comment_asterisk,
zero,
integer_literal_oct,
integer_literal_binary,
integer_literal_binary_first,
integer_literal_hex,
integer_literal_hex_first,
integer_literal,
integer_suffix,
integer_suffix_u,
integer_suffix_l,
integer_suffix_ll,
integer_suffix_ul,
float_fraction,
float_fraction_hex,
float_exponent,
float_exponent_digits,
float_suffix,
} = .start;
var start = self.index;
var id: Token.Id = .eof;
var string = false;
var counter: u32 = 0;
while (self.index < self.buf.len) : (self.index += 1) {
const c = self.buf[self.index];
switch (state) {
.start => switch (c) {
'\n' => {
id = .nl;
self.index += 1;
break;
},
'\r' => state = .cr,
'"' => {
id = .string_literal;
state = .string_literal;
},
'\'' => {
id = .char_literal;
state = .char_literal_start;
},
'u' => state = .u,
'U' => state = .U,
'L' => state = .L,
'a'...'t', 'v'...'z', 'A'...'K', 'M'...'T', 'V'...'Z', '_', '$' => state = .identifier,
'=' => state = .equal,
'!' => state = .bang,
'|' => state = .pipe,
'(' => {
id = .l_paren;
self.index += 1;
break;
},
')' => {
id = .r_paren;
self.index += 1;
break;
},
'[' => {
id = .l_bracket;
self.index += 1;
break;
},
']' => {
id = .r_bracket;
self.index += 1;
break;
},
';' => {
id = .semicolon;
self.index += 1;
break;
},
',' => {
id = .comma;
self.index += 1;
break;
},
'?' => {
id = .question_mark;
self.index += 1;
break;
},
':' => {
id = .colon;
self.index += 1;
break;
},
'%' => state = .percent,
'*' => state = .asterisk,
'+' => state = .plus,
'<' => state = .angle_bracket_left,
'>' => state = .angle_bracket_right,
'^' => state = .caret,
'{' => {
id = .l_brace;
self.index += 1;
break;
},
'}' => {
id = .r_brace;
self.index += 1;
break;
},
'~' => {
id = .tilde;
self.index += 1;
break;
},
'.' => state = .period,
'-' => state = .minus,
'/' => state = .slash,
'&' => state = .ampersand,
'#' => state = .hash,
'0' => state = .zero,
'1'...'9' => state = .integer_literal,
'\\' => state = .back_slash,
'\t', '\x0B', '\x0C', ' ' => start = self.index + 1,
else => {
id = .invalid;
self.index += 1;
break;
},
},
.cr => switch (c) {
'\n' => {
id = .nl;
self.index += 1;
break;
},
else => {
id = .invalid;
break;
},
},
.back_slash => switch (c) {
'\n' => {
start = self.index + 1;
state = .start;
},
'\r' => state = .back_slash_cr,
'\t', '\x0B', '\x0C', ' ' => {
// TODO warn
},
else => {
id = .invalid;
break;
},
},
.back_slash_cr => switch (c) {
'\n' => {
start = self.index + 1;
state = .start;
},
else => {
id = .invalid;
break;
},
},
.u => switch (c) {
'8' => {
state = .u8;
},
'\'' => {
id = .char_literal_utf_16;
state = .char_literal_start;
},
'\"' => {
id = .string_literal_utf_16;
state = .string_literal;
},
else => {
self.index -= 1;
state = .identifier;
},
},
.u8 => switch (c) {
'\"' => {
id = .string_literal_utf_8;
state = .string_literal;
},
else => {
self.index -= 1;
state = .identifier;
},
},
.U => switch (c) {
'\'' => {
id = .char_literal_utf_32;
state = .char_literal_start;
},
'\"' => {
id = .string_literal_utf_32;
state = .string_literal;
},
else => {
self.index -= 1;
state = .identifier;
},
},
.L => switch (c) {
'\'' => {
id = .char_literal_wide;
state = .char_literal_start;
},
'\"' => {
id = .string_literal_wide;
state = .string_literal;
},
else => {
self.index -= 1;
state = .identifier;
},
},
.string_literal => switch (c) {
'\\' => {
string = true;
state = .escape_sequence;
},
'"' => {
self.index += 1;
break;
},
'\n', '\r' => {
id = .invalid;
break;
},
else => {},
},
.char_literal_start => switch (c) {
'\\' => {
string = false;
state = .escape_sequence;
},
'\'', '\n' => {
id = .invalid;
break;
},
else => {
state = .char_literal;
},
},
.char_literal => switch (c) {
'\\' => {
string = false;
state = .escape_sequence;
},
'\'' => {
self.index += 1;
break;
},
'\n' => {
id = .invalid;
break;
},
else => {},
},
.escape_sequence => switch (c) {
'\'', '"', '?', '\\', 'a', 'b', 'e', 'f', 'n', 'r', 't', 'v', '\n' => {
state = if (string) .string_literal else .char_literal;
},
'\r' => state = .cr_escape,
'0'...'7' => {
counter = 1;
state = .octal_escape;
},
'x' => state = .hex_escape,
'u' => {
counter = 4;
state = .unicode_escape;
},
'U' => {
counter = 8;
state = .unicode_escape;
},
else => {
id = .invalid;
break;
},
},
.cr_escape => switch (c) {
'\n' => {
state = if (string) .string_literal else .char_literal;
},
else => {
id = .invalid;
break;
},
},
.octal_escape => switch (c) {
'0'...'7' => {
counter += 1;
if (counter == 3) {
state = if (string) .string_literal else .char_literal;
}
},
else => {
self.index -= 1;
state = if (string) .string_literal else .char_literal;
},
},
.hex_escape => switch (c) {
'0'...'9', 'a'...'f', 'A'...'F' => {},
else => {
self.index -= 1;
state = if (string) .string_literal else .char_literal;
},
},
.unicode_escape => switch (c) {
'0'...'9', 'a'...'f', 'A'...'F' => {
counter -= 1;
if (counter == 0) {
state = if (string) .string_literal else .char_literal;
}
},
else => {
if (counter != 0) {
id = .invalid;
break;
}
self.index -= 1;
state = if (string) .string_literal else .char_literal;
},
},
.identifier => switch (c) {
'a'...'z', 'A'...'Z', '_', '0'...'9', '$' => {},
else => {
id = Token.getTokenId(self.comp, self.buf[start..self.index]);
break;
},
},
.equal => switch (c) {
'=' => {
id = .equal_equal;
self.index += 1;
break;
},
else => {
id = .equal;
break;
},
},
.bang => switch (c) {
'=' => {
id = .bang_equal;
self.index += 1;
break;
},
else => {
id = .bang;
break;
},
},
.pipe => switch (c) {
'=' => {
id = .pipe_equal;
self.index += 1;
break;
},
'|' => {
id = .pipe_pipe;
self.index += 1;
break;
},
else => {
id = .pipe;
break;
},
},
.percent => switch (c) {
'=' => {
id = .percent_equal;
self.index += 1;
break;
},
else => {
id = .percent;
break;
},
},
.asterisk => switch (c) {
'=' => {
id = .asterisk_equal;
self.index += 1;
break;
},
else => {
id = .asterisk;
break;
},
},
.plus => switch (c) {
'=' => {
id = .plus_equal;
self.index += 1;
break;
},
'+' => {
id = .plus_plus;
self.index += 1;
break;
},
else => {
id = .plus;
break;
},
},
.angle_bracket_left => switch (c) {
'<' => {
state = .angle_bracket_angle_bracket_left;
},
'=' => {
id = .angle_bracket_left_equal;
self.index += 1;
break;
},
else => {
id = .angle_bracket_left;
break;
},
},
.angle_bracket_angle_bracket_left => switch (c) {
'=' => {
id = .angle_bracket_angle_bracket_left_equal;
self.index += 1;
break;
},
else => {
id = .angle_bracket_angle_bracket_left;
break;
},
},
.angle_bracket_right => switch (c) {
'>' => {
state = .angle_bracket_angle_bracket_right;
},
'=' => {
id = .angle_bracket_right_equal;
self.index += 1;
break;
},
else => {
id = .angle_bracket_right;
break;
},
},
.angle_bracket_angle_bracket_right => switch (c) {
'=' => {
id = .angle_bracket_angle_bracket_right_equal;
self.index += 1;
break;
},
else => {
id = .angle_bracket_angle_bracket_right;
break;
},
},
.caret => switch (c) {
'=' => {
id = .caret_equal;
self.index += 1;
break;
},
else => {
id = .caret;
break;
},
},
.period => switch (c) {
'.' => {
state = .period2;
},
'0'...'9' => {
state = .float_fraction;
},
else => {
id = .period;
break;
},
},
.period2 => switch (c) {
'.' => {
id = .ellipsis;
self.index += 1;
break;
},
else => {
id = .period;
self.index -= 1;
break;
},
},
.minus => switch (c) {
'>' => {
id = .arrow;
self.index += 1;
break;
},
'=' => {
id = .minus_equal;
self.index += 1;
break;
},
'-' => {
id = .minus_minus;
self.index += 1;
break;
},
else => {
id = .minus;
break;
},
},
.ampersand => switch (c) {
'&' => {
id = .ampersand_ampersand;
self.index += 1;
break;
},
'=' => {
id = .ampersand_equal;
self.index += 1;
break;
},
else => {
id = .ampersand;
break;
},
},
.hash => switch (c) {
'#' => {
id = .hash_hash;
self.index += 1;
break;
},
else => {
id = .hash;
break;
},
},
.slash => switch (c) {
'/' => {
state = .line_comment;
},
'*' => {
state = .multi_line_comment;
},
'=' => {
id = .slash_equal;
self.index += 1;
break;
},
else => {
id = .slash;
break;
},
},
.line_comment => switch (c) {
'\n' => {
self.index -= 1;
state = .start;
},
else => {},
},
.multi_line_comment => switch (c) {
'*' => state = .multi_line_comment_asterisk,
else => {},
},
.multi_line_comment_asterisk => switch (c) {
'/' => state = .start,
else => state = .multi_line_comment,
},
.zero => switch (c) {
'0'...'9' => state = .integer_literal_oct,
'b', 'B' => state = .integer_literal_binary_first,
'x', 'X' => state = .integer_literal_hex_first,
'.' => state = .float_fraction,
else => {
state = .integer_suffix;
self.index -= 1;
},
},
.integer_literal_oct => switch (c) {
'0'...'7' => {},
else => {
state = .integer_suffix;
self.index -= 1;
},
},
.integer_literal_binary_first => switch (c) {
'0', '1' => state = .integer_literal_binary,
else => {
id = .invalid;
break;
},
},
.integer_literal_binary => switch (c) {
'0', '1' => {},
else => {
state = .integer_suffix;
self.index -= 1;
},
},
.integer_literal_hex_first => switch (c) {
'0'...'9', 'a'...'f', 'A'...'F' => state = .integer_literal_hex,
'.' => state = .float_fraction_hex,
'p', 'P' => state = .float_exponent,
else => {
id = .invalid;
break;
},
},
.integer_literal_hex => switch (c) {
'0'...'9', 'a'...'f', 'A'...'F' => {},
'.' => state = .float_fraction_hex,
'p', 'P' => state = .float_exponent,
else => {
state = .integer_suffix;
self.index -= 1;
},
},
.integer_literal => switch (c) {
'0'...'9' => {},
'.' => state = .float_fraction,
'e', 'E' => state = .float_exponent,
else => {
state = .integer_suffix;
self.index -= 1;
},
},
.integer_suffix => switch (c) {
'u', 'U' => state = .integer_suffix_u,
'l', 'L' => state = .integer_suffix_l,
else => {
id = .integer_literal;
break;
},
},
.integer_suffix_u => switch (c) {
'l', 'L' => state = .integer_suffix_ul,
else => {
id = .integer_literal_u;
break;
},
},
.integer_suffix_l => switch (c) {
'l', 'L' => state = .integer_suffix_ll,
'u', 'U' => {
id = .integer_literal_lu;
self.index += 1;
break;
},
else => {
id = .integer_literal_l;
break;
},
},
.integer_suffix_ll => switch (c) {
'u', 'U' => {
id = .integer_literal_llu;
self.index += 1;
break;
},
else => {
id = .integer_literal_ll;
break;
},
},
.integer_suffix_ul => switch (c) {
'l', 'L' => {
id = .integer_literal_llu;
self.index += 1;
break;
},
else => {
id = .integer_literal_lu;
break;
},
},
.float_fraction => switch (c) {
'0'...'9' => {},
'e', 'E' => state = .float_exponent,
else => {
self.index -= 1;
state = .float_suffix;
},
},
.float_fraction_hex => switch (c) {
'0'...'9', 'a'...'f', 'A'...'F' => {},
'p', 'P' => state = .float_exponent,
else => {
id = .invalid;
break;
},
},
.float_exponent => switch (c) {
'+', '-' => state = .float_exponent_digits,
else => {
self.index -= 1;
state = .float_exponent_digits;
},
},
.float_exponent_digits => switch (c) {
'0'...'9' => counter += 1,
else => {
if (counter == 0) {
id = .invalid;
break;
}
self.index -= 1;
state = .float_suffix;
},
},
.float_suffix => switch (c) {
'l', 'L' => {
id = .float_literal_l;
self.index += 1;
break;
},
'f', 'F' => {
id = .float_literal_f;
self.index += 1;
break;
},
else => {
id = .float_literal;
break;
},
},
}
} else if (self.index == self.buf.len) {
switch (state) {
.start, .line_comment => {},
.u, .u8, .U, .L, .identifier => {
id = Token.getTokenId(self.comp, self.buf[start..self.index]);
},
.cr,
.back_slash,
.back_slash_cr,
.period2,
.string_literal,
.char_literal_start,
.char_literal,
.escape_sequence,
.cr_escape,
.octal_escape,
.hex_escape,
.unicode_escape,
.multi_line_comment,
.multi_line_comment_asterisk,
.float_exponent,
.integer_literal_binary_first,
.integer_literal_hex_first,
=> id = .invalid,
.float_exponent_digits => id = if (counter == 0) .invalid else .float_literal,
.float_fraction,
.float_fraction_hex,
=> id = .float_literal,
.integer_literal_oct,
.integer_literal_binary,
.integer_literal_hex,
.integer_literal,
.integer_suffix,
.zero,
=> id = .integer_literal,
.integer_suffix_u => id = .integer_literal_u,
.integer_suffix_l => id = .integer_literal_l,
.integer_suffix_ll => id = .integer_literal_ll,
.integer_suffix_ul => id = .integer_literal_lu,
.float_suffix => id = .float_literal,
.equal => id = .equal,
.bang => id = .bang,
.minus => id = .minus,
.slash => id = .slash,
.ampersand => id = .ampersand,
.hash => id = .hash,
.period => id = .period,
.pipe => id = .pipe,
.angle_bracket_angle_bracket_right => id = .angle_bracket_angle_bracket_right,
.angle_bracket_right => id = .angle_bracket_right,
.angle_bracket_angle_bracket_left => id = .angle_bracket_angle_bracket_left,
.angle_bracket_left => id = .angle_bracket_left,
.plus => id = .plus,
.percent => id = .percent,
.caret => id = .caret,
.asterisk => id = .asterisk,
}
}
return .{
.id = id,
.start = start,
.end = self.index,
.source = self.source,
};
}
test "operators" {
try expectTokens(
\\ ! != | || |= = ==
\\ ( ) { } [ ] . .. ...
\\ ^ ^= + ++ += - -- -=
\\ * *= % %= -> : ; / /=
\\ , & && &= ? < <= <<
\\ <<= > >= >> >>= ~ # ##
\\
, &.{
.bang,
.bang_equal,
.pipe,
.pipe_pipe,
.pipe_equal,
.equal,
.equal_equal,
.nl,
.l_paren,
.r_paren,
.l_brace,
.r_brace,
.l_bracket,
.r_bracket,
.period,
.period,
.period,
.ellipsis,
.nl,
.caret,
.caret_equal,
.plus,
.plus_plus,
.plus_equal,
.minus,
.minus_minus,
.minus_equal,
.nl,
.asterisk,
.asterisk_equal,
.percent,
.percent_equal,
.arrow,
.colon,
.semicolon,
.slash,
.slash_equal,
.nl,
.comma,
.ampersand,
.ampersand_ampersand,
.ampersand_equal,
.question_mark,
.angle_bracket_left,
.angle_bracket_left_equal,
.angle_bracket_angle_bracket_left,
.nl,
.angle_bracket_angle_bracket_left_equal,
.angle_bracket_right,
.angle_bracket_right_equal,
.angle_bracket_angle_bracket_right,
.angle_bracket_angle_bracket_right_equal,
.tilde,
.hash,
.hash_hash,
.nl,
});
}
test "keywords" {
try expectTokens(
\\auto break case char const continue default do
\\double else enum extern float for goto if int
\\long register return short signed sizeof static
\\struct switch typedef union unsigned void volatile
\\while _Bool _Complex _Imaginary inline restrict _Alignas
\\_Alignof _Atomic _Generic _Noreturn _Static_assert _Thread_local
\\
, &.{
.keyword_auto,
.keyword_break,
.keyword_case,
.keyword_char,
.keyword_const,
.keyword_continue,
.keyword_default,
.keyword_do,
.nl,
.keyword_double,
.keyword_else,
.keyword_enum,
.keyword_extern,
.keyword_float,
.keyword_for,
.keyword_goto,
.keyword_if,
.keyword_int,
.nl,
.keyword_long,
.keyword_register,
.keyword_return,
.keyword_short,
.keyword_signed,
.keyword_sizeof,
.keyword_static,
.nl,
.keyword_struct,
.keyword_switch,
.keyword_typedef,
.keyword_union,
.keyword_unsigned,
.keyword_void,
.keyword_volatile,
.nl,
.keyword_while,
.keyword_bool,
.keyword_complex,
.keyword_imaginary,
.keyword_inline,
.keyword_restrict,
.keyword_alignas,
.nl,
.keyword_alignof,
.keyword_atomic,
.keyword_generic,
.keyword_noreturn,
.keyword_static_assert,
.keyword_thread_local,
.nl,
});
}
test "preprocessor keywords" {
try expectTokens(
\\#include
\\#define
\\#ifdef
\\#ifndef
\\#error
\\#pragma
\\
, &.{
.hash,
.keyword_include,
.nl,
.hash,
.keyword_define,
.nl,
.hash,
.keyword_ifdef,
.nl,
.hash,
.keyword_ifndef,
.nl,
.hash,
.keyword_error,
.nl,
.hash,
.keyword_pragma,
.nl,
});
}
test "line continuation" {
try expectTokens(
\\#define foo \
\\ bar
\\"foo\
\\ bar"
\\#define "foo"
\\ "bar"
\\#define "foo" \
\\ "bar"
, &.{
.hash,
.keyword_define,
.identifier,
.identifier,
.nl,
.string_literal,
.nl,
.hash,
.keyword_define,
.string_literal,
.nl,
.string_literal,
.nl,
.hash,
.keyword_define,
.string_literal,
.string_literal,
});
}
test "string prefix" {
try expectTokens(
\\"foo"
\\u"foo"
\\u8"foo"
\\U"foo"
\\L"foo"
\\'foo'
\\u'foo'
\\U'foo'
\\L'foo'
\\
, &.{
.string_literal,
.nl,
.string_literal_utf_16,
.nl,
.string_literal_utf_8,
.nl,
.string_literal_utf_32,
.nl,
.string_literal_wide,
.nl,
.char_literal,
.nl,
.char_literal_utf_16,
.nl,
.char_literal_utf_32,
.nl,
.char_literal_wide,
.nl,
});
}
test "num suffixes" {
try expectTokens(
\\ 1.0f 1.0L 1.0 .0 1. 0x1p0f 0X1p0
\\ 0l 0lu 0ll 0llu 0
\\ 1u 1ul 1ull 1
\\
, &.{
.float_literal_f,
.float_literal_l,
.float_literal,
.float_literal,
.float_literal,
.float_literal_f,
.float_literal,
.nl,
.integer_literal_l,
.integer_literal_lu,
.integer_literal_ll,
.integer_literal_llu,
.integer_literal,
.nl,
.integer_literal_u,
.integer_literal_lu,
.integer_literal_llu,
.integer_literal,
.nl,
});
}
test "comments" {
try expectTokens(
\\//foo
\\#foo
, &.{
.nl,
.hash,
.identifier,
});
}
fn expectTokens(source: []const u8, expected_tokens: []const Token.Id) !void {
var comp = Compilation.init(std.testing.allocator);
defer comp.deinit();
var tokenizer = Tokenizer{
.buf = source,
.source = .unused,
.comp = &comp,
};
for (expected_tokens) |expected_token_id| {
const token = tokenizer.next();
if (!std.meta.eql(token.id, expected_token_id)) {
std.debug.print("expected {s}, found {s}\n", .{ @tagName(expected_token_id), @tagName(token.id) });
return error.TokensDoNotEqual;
}
}
const last_token = tokenizer.next();
try std.testing.expect(last_token.id == .eof);
} | src/Tokenizer.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const print = std.debug.print;
const boardingPasses = @embedFile("input05.txt");
const BoardingPass = struct { row: u32, column: u32 };
fn getRow(pass: []const u8) u32 {
var final: u32 = 0;
for (pass) |c| {
final <<= 1;
if (c == 'B')
final |= 1;
}
return final;
}
fn getColumn(pass: []const u8) u32 {
var final: u32 = 0;
for (pass) |c| {
final <<= 1;
if (c == 'R')
final |= 1;
}
return final;
}
fn getRowAndColumn(pass: []const u8) BoardingPass {
return BoardingPass{
.row = getRow(pass[0..7]),
.column = getColumn(pass[7..]),
};
}
fn getSeatIds(allocator: *Allocator) !std.ArrayList(u32) {
var seatIds = std.ArrayList(u32).init(allocator);
var lines = std.mem.tokenize(boardingPasses, "\n\r");
while (lines.next()) |pass| {
var boardingPass = getRowAndColumn(pass);
var seatId = boardingPass.row * 8 + boardingPass.column;
try seatIds.append(seatId);
}
return seatIds;
}
fn part1() !void {
print("Part 1:\n", .{});
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
var seatIds = try getSeatIds(&gpa.allocator);
defer seatIds.deinit();
var maxSeatId: u32 = 0;
for (seatIds.items) |seatId| {
if (seatId > maxSeatId)
maxSeatId = seatId;
}
print("Max Seat ID: {}\n", .{maxSeatId});
}
fn part2() !void {
print("\nPart 2:\n", .{});
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
var seatIds = try getSeatIds(&gpa.allocator);
defer seatIds.deinit();
var sortedSeatIds: []u32 = try gpa.allocator.alloc(u32, seatIds.items.len);
defer gpa.allocator.free(sortedSeatIds);
std.mem.copy(u32, sortedSeatIds, seatIds.items);
std.sort.sort(u32, sortedSeatIds, {}, comptime std.sort.asc(u32));
var i: u32 = 1;
while (i < sortedSeatIds.len - 1) : (i += 1) {
const previousSeatId = sortedSeatIds[i - 1];
const seatId = sortedSeatIds[i];
if (seatId != (previousSeatId + 1))
print("My seat id is: {}\n", .{seatId - 1});
}
}
pub fn main() !void {
try part1();
try part2();
} | src/day05.zig |
const std = @import("std");
const pkgs = @import("deps.zig").pkgs;
pub fn build(b: *std.build.Builder) void {
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
// for restricting supported target set are available.
const target = b.standardTargetOptions(.{});
// Standard release options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall.
const mode = b.standardReleaseOptions();
const raylib = b.addStaticLibrary("raylib", null);
raylib.linkLibC();
raylib.setTarget(target);
raylib.setBuildMode(mode);
raylib.addCSourceFiles(&.{
"3rd/raylib/src/core.c",
"3rd/raylib/src/rglfw.c",
"3rd/raylib/src/shapes.c",
"3rd/raylib/src/textures.c",
"3rd/raylib/src/text.c",
"3rd/raylib/src/utils.c",
"3rd/raylib/src/models.c",
"3rd/raylib/src/raudio.c",
}, &.{
"-Wall",
"-Wno-missing-braces",
"-Werror=pointer-arith",
"-fno-strict-aliasing",
"-std=c99",
"-fno-sanitize=undefined",
"-Werror=implicit-function-declaration",
"-DPLATFORM_DESKTOP",
"-DGRAPHICS_API_OPENGL_33",
});
raylib.addIncludeDir("3rd/raylib/src");
raylib.addIncludeDir("3rd/raylib/src/external/glfw/include");
raylib.addIncludeDir("3rd/raylib/src/external/glfw/deps/mingw");
raylib.linkSystemLibrary("opengl32");
raylib.linkSystemLibrary("gdi32");
raylib.linkSystemLibrary("winmm");
const exe = b.addExecutable("ray-zig", "src/main.zig");
exe.setTarget(target);
exe.setBuildMode(mode);
exe.linkLibrary(raylib);
pkgs.addAllTo(exe);
exe.install();
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
} | build.zig |
pub const UI_ANIMATION_SECONDS_EVENTUALLY = @as(i32, -1);
pub const UI_ANIMATION_REPEAT_INDEFINITELY = @as(i32, -1);
pub const UI_ANIMATION_REPEAT_INDEFINITELY_CONCLUDE_AT_END = @as(i32, -1);
pub const UI_ANIMATION_REPEAT_INDEFINITELY_CONCLUDE_AT_START = @as(i32, -2);
pub const UI_ANIMATION_SECONDS_INFINITE = @as(i32, -1);
//--------------------------------------------------------------------------------
// Section: Types (51)
//--------------------------------------------------------------------------------
pub const UI_ANIMATION_KEYFRAME = isize;
const CLSID_UIAnimationManager_Value = Guid.initString("4c1fc63a-695c-47e8-a339-1a194be3d0b8");
pub const CLSID_UIAnimationManager = &CLSID_UIAnimationManager_Value;
const CLSID_UIAnimationManager2_Value = Guid.initString("d25d8842-8884-4a4a-b321-091314379bdd");
pub const CLSID_UIAnimationManager2 = &CLSID_UIAnimationManager2_Value;
const CLSID_UIAnimationTransitionLibrary_Value = Guid.initString("1d6322ad-aa85-4ef5-a828-86d71067d145");
pub const CLSID_UIAnimationTransitionLibrary = &CLSID_UIAnimationTransitionLibrary_Value;
const CLSID_UIAnimationTransitionLibrary2_Value = Guid.initString("812f944a-c5c8-4cd9-b0a6-b3da802f228d");
pub const CLSID_UIAnimationTransitionLibrary2 = &CLSID_UIAnimationTransitionLibrary2_Value;
const CLSID_UIAnimationTransitionFactory_Value = Guid.initString("8a9b1cdd-fcd7-419c-8b44-42fd17db1887");
pub const CLSID_UIAnimationTransitionFactory = &CLSID_UIAnimationTransitionFactory_Value;
const CLSID_UIAnimationTransitionFactory2_Value = Guid.initString("84302f97-7f7b-4040-b190-72ac9d18e420");
pub const CLSID_UIAnimationTransitionFactory2 = &CLSID_UIAnimationTransitionFactory2_Value;
const CLSID_UIAnimationTimer_Value = Guid.initString("bfcd4a0c-06b6-4384-b768-0daa792c380e");
pub const CLSID_UIAnimationTimer = &CLSID_UIAnimationTimer_Value;
pub const UI_ANIMATION_UPDATE_RESULT = enum(i32) {
NO_CHANGE = 0,
VARIABLES_CHANGED = 1,
};
pub const UI_ANIMATION_UPDATE_NO_CHANGE = UI_ANIMATION_UPDATE_RESULT.NO_CHANGE;
pub const UI_ANIMATION_UPDATE_VARIABLES_CHANGED = UI_ANIMATION_UPDATE_RESULT.VARIABLES_CHANGED;
pub const UI_ANIMATION_MANAGER_STATUS = enum(i32) {
IDLE = 0,
BUSY = 1,
};
pub const UI_ANIMATION_MANAGER_IDLE = UI_ANIMATION_MANAGER_STATUS.IDLE;
pub const UI_ANIMATION_MANAGER_BUSY = UI_ANIMATION_MANAGER_STATUS.BUSY;
pub const UI_ANIMATION_MODE = enum(i32) {
DISABLED = 0,
SYSTEM_DEFAULT = 1,
ENABLED = 2,
};
pub const UI_ANIMATION_MODE_DISABLED = UI_ANIMATION_MODE.DISABLED;
pub const UI_ANIMATION_MODE_SYSTEM_DEFAULT = UI_ANIMATION_MODE.SYSTEM_DEFAULT;
pub const UI_ANIMATION_MODE_ENABLED = UI_ANIMATION_MODE.ENABLED;
pub const UI_ANIMATION_REPEAT_MODE = enum(i32) {
NORMAL = 0,
ALTERNATE = 1,
};
pub const UI_ANIMATION_REPEAT_MODE_NORMAL = UI_ANIMATION_REPEAT_MODE.NORMAL;
pub const UI_ANIMATION_REPEAT_MODE_ALTERNATE = UI_ANIMATION_REPEAT_MODE.ALTERNATE;
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAnimationManager_Value = Guid.initString("9169896c-ac8d-4e7d-94e5-67fa4dc2f2e8");
pub const IID_IUIAnimationManager = &IID_IUIAnimationManager_Value;
pub const IUIAnimationManager = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CreateAnimationVariable: fn(
self: *const IUIAnimationManager,
initialValue: f64,
variable: ?*?*IUIAnimationVariable,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ScheduleTransition: fn(
self: *const IUIAnimationManager,
variable: ?*IUIAnimationVariable,
transition: ?*IUIAnimationTransition,
timeNow: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateStoryboard: fn(
self: *const IUIAnimationManager,
storyboard: ?*?*IUIAnimationStoryboard,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FinishAllStoryboards: fn(
self: *const IUIAnimationManager,
completionDeadline: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AbandonAllStoryboards: fn(
self: *const IUIAnimationManager,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Update: fn(
self: *const IUIAnimationManager,
timeNow: f64,
updateResult: ?*UI_ANIMATION_UPDATE_RESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetVariableFromTag: fn(
self: *const IUIAnimationManager,
object: ?*IUnknown,
id: u32,
variable: ?*?*IUIAnimationVariable,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStoryboardFromTag: fn(
self: *const IUIAnimationManager,
object: ?*IUnknown,
id: u32,
storyboard: ?*?*IUIAnimationStoryboard,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStatus: fn(
self: *const IUIAnimationManager,
status: ?*UI_ANIMATION_MANAGER_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetAnimationMode: fn(
self: *const IUIAnimationManager,
mode: UI_ANIMATION_MODE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Pause: fn(
self: *const IUIAnimationManager,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Resume: fn(
self: *const IUIAnimationManager,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetManagerEventHandler: fn(
self: *const IUIAnimationManager,
handler: ?*IUIAnimationManagerEventHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCancelPriorityComparison: fn(
self: *const IUIAnimationManager,
comparison: ?*IUIAnimationPriorityComparison,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetTrimPriorityComparison: fn(
self: *const IUIAnimationManager,
comparison: ?*IUIAnimationPriorityComparison,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCompressPriorityComparison: fn(
self: *const IUIAnimationManager,
comparison: ?*IUIAnimationPriorityComparison,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetConcludePriorityComparison: fn(
self: *const IUIAnimationManager,
comparison: ?*IUIAnimationPriorityComparison,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetDefaultLongestAcceptableDelay: fn(
self: *const IUIAnimationManager,
delay: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Shutdown: fn(
self: *const IUIAnimationManager,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager_CreateAnimationVariable(self: *const T, initialValue: f64, variable: ?*?*IUIAnimationVariable) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager.VTable, self.vtable).CreateAnimationVariable(@ptrCast(*const IUIAnimationManager, self), initialValue, variable);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager_ScheduleTransition(self: *const T, variable: ?*IUIAnimationVariable, transition: ?*IUIAnimationTransition, timeNow: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager.VTable, self.vtable).ScheduleTransition(@ptrCast(*const IUIAnimationManager, self), variable, transition, timeNow);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager_CreateStoryboard(self: *const T, storyboard: ?*?*IUIAnimationStoryboard) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager.VTable, self.vtable).CreateStoryboard(@ptrCast(*const IUIAnimationManager, self), storyboard);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager_FinishAllStoryboards(self: *const T, completionDeadline: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager.VTable, self.vtable).FinishAllStoryboards(@ptrCast(*const IUIAnimationManager, self), completionDeadline);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager_AbandonAllStoryboards(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager.VTable, self.vtable).AbandonAllStoryboards(@ptrCast(*const IUIAnimationManager, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager_Update(self: *const T, timeNow: f64, updateResult: ?*UI_ANIMATION_UPDATE_RESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager.VTable, self.vtable).Update(@ptrCast(*const IUIAnimationManager, self), timeNow, updateResult);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager_GetVariableFromTag(self: *const T, object: ?*IUnknown, id: u32, variable: ?*?*IUIAnimationVariable) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager.VTable, self.vtable).GetVariableFromTag(@ptrCast(*const IUIAnimationManager, self), object, id, variable);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager_GetStoryboardFromTag(self: *const T, object: ?*IUnknown, id: u32, storyboard: ?*?*IUIAnimationStoryboard) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager.VTable, self.vtable).GetStoryboardFromTag(@ptrCast(*const IUIAnimationManager, self), object, id, storyboard);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager_GetStatus(self: *const T, status: ?*UI_ANIMATION_MANAGER_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager.VTable, self.vtable).GetStatus(@ptrCast(*const IUIAnimationManager, self), status);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager_SetAnimationMode(self: *const T, mode: UI_ANIMATION_MODE) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager.VTable, self.vtable).SetAnimationMode(@ptrCast(*const IUIAnimationManager, self), mode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager_Pause(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager.VTable, self.vtable).Pause(@ptrCast(*const IUIAnimationManager, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager_Resume(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager.VTable, self.vtable).Resume(@ptrCast(*const IUIAnimationManager, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager_SetManagerEventHandler(self: *const T, handler: ?*IUIAnimationManagerEventHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager.VTable, self.vtable).SetManagerEventHandler(@ptrCast(*const IUIAnimationManager, self), handler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager_SetCancelPriorityComparison(self: *const T, comparison: ?*IUIAnimationPriorityComparison) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager.VTable, self.vtable).SetCancelPriorityComparison(@ptrCast(*const IUIAnimationManager, self), comparison);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager_SetTrimPriorityComparison(self: *const T, comparison: ?*IUIAnimationPriorityComparison) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager.VTable, self.vtable).SetTrimPriorityComparison(@ptrCast(*const IUIAnimationManager, self), comparison);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager_SetCompressPriorityComparison(self: *const T, comparison: ?*IUIAnimationPriorityComparison) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager.VTable, self.vtable).SetCompressPriorityComparison(@ptrCast(*const IUIAnimationManager, self), comparison);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager_SetConcludePriorityComparison(self: *const T, comparison: ?*IUIAnimationPriorityComparison) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager.VTable, self.vtable).SetConcludePriorityComparison(@ptrCast(*const IUIAnimationManager, self), comparison);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager_SetDefaultLongestAcceptableDelay(self: *const T, delay: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager.VTable, self.vtable).SetDefaultLongestAcceptableDelay(@ptrCast(*const IUIAnimationManager, self), delay);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager_Shutdown(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager.VTable, self.vtable).Shutdown(@ptrCast(*const IUIAnimationManager, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const UI_ANIMATION_ROUNDING_MODE = enum(i32) {
NEAREST = 0,
FLOOR = 1,
CEILING = 2,
};
pub const UI_ANIMATION_ROUNDING_NEAREST = UI_ANIMATION_ROUNDING_MODE.NEAREST;
pub const UI_ANIMATION_ROUNDING_FLOOR = UI_ANIMATION_ROUNDING_MODE.FLOOR;
pub const UI_ANIMATION_ROUNDING_CEILING = UI_ANIMATION_ROUNDING_MODE.CEILING;
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAnimationVariable_Value = Guid.initString("8ceeb155-2849-4ce5-9448-91ff70e1e4d9");
pub const IID_IUIAnimationVariable = &IID_IUIAnimationVariable_Value;
pub const IUIAnimationVariable = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetValue: fn(
self: *const IUIAnimationVariable,
value: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFinalValue: fn(
self: *const IUIAnimationVariable,
finalValue: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPreviousValue: fn(
self: *const IUIAnimationVariable,
previousValue: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetIntegerValue: fn(
self: *const IUIAnimationVariable,
value: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFinalIntegerValue: fn(
self: *const IUIAnimationVariable,
finalValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPreviousIntegerValue: fn(
self: *const IUIAnimationVariable,
previousValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCurrentStoryboard: fn(
self: *const IUIAnimationVariable,
storyboard: ?*?*IUIAnimationStoryboard,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetLowerBound: fn(
self: *const IUIAnimationVariable,
bound: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetUpperBound: fn(
self: *const IUIAnimationVariable,
bound: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetRoundingMode: fn(
self: *const IUIAnimationVariable,
mode: UI_ANIMATION_ROUNDING_MODE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetTag: fn(
self: *const IUIAnimationVariable,
object: ?*IUnknown,
id: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTag: fn(
self: *const IUIAnimationVariable,
object: ?*?*IUnknown,
id: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetVariableChangeHandler: fn(
self: *const IUIAnimationVariable,
handler: ?*IUIAnimationVariableChangeHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetVariableIntegerChangeHandler: fn(
self: *const IUIAnimationVariable,
handler: ?*IUIAnimationVariableIntegerChangeHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable_GetValue(self: *const T, value: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable.VTable, self.vtable).GetValue(@ptrCast(*const IUIAnimationVariable, self), value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable_GetFinalValue(self: *const T, finalValue: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable.VTable, self.vtable).GetFinalValue(@ptrCast(*const IUIAnimationVariable, self), finalValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable_GetPreviousValue(self: *const T, previousValue: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable.VTable, self.vtable).GetPreviousValue(@ptrCast(*const IUIAnimationVariable, self), previousValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable_GetIntegerValue(self: *const T, value: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable.VTable, self.vtable).GetIntegerValue(@ptrCast(*const IUIAnimationVariable, self), value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable_GetFinalIntegerValue(self: *const T, finalValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable.VTable, self.vtable).GetFinalIntegerValue(@ptrCast(*const IUIAnimationVariable, self), finalValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable_GetPreviousIntegerValue(self: *const T, previousValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable.VTable, self.vtable).GetPreviousIntegerValue(@ptrCast(*const IUIAnimationVariable, self), previousValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable_GetCurrentStoryboard(self: *const T, storyboard: ?*?*IUIAnimationStoryboard) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable.VTable, self.vtable).GetCurrentStoryboard(@ptrCast(*const IUIAnimationVariable, self), storyboard);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable_SetLowerBound(self: *const T, bound: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable.VTable, self.vtable).SetLowerBound(@ptrCast(*const IUIAnimationVariable, self), bound);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable_SetUpperBound(self: *const T, bound: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable.VTable, self.vtable).SetUpperBound(@ptrCast(*const IUIAnimationVariable, self), bound);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable_SetRoundingMode(self: *const T, mode: UI_ANIMATION_ROUNDING_MODE) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable.VTable, self.vtable).SetRoundingMode(@ptrCast(*const IUIAnimationVariable, self), mode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable_SetTag(self: *const T, object: ?*IUnknown, id: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable.VTable, self.vtable).SetTag(@ptrCast(*const IUIAnimationVariable, self), object, id);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable_GetTag(self: *const T, object: ?*?*IUnknown, id: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable.VTable, self.vtable).GetTag(@ptrCast(*const IUIAnimationVariable, self), object, id);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable_SetVariableChangeHandler(self: *const T, handler: ?*IUIAnimationVariableChangeHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable.VTable, self.vtable).SetVariableChangeHandler(@ptrCast(*const IUIAnimationVariable, self), handler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable_SetVariableIntegerChangeHandler(self: *const T, handler: ?*IUIAnimationVariableIntegerChangeHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable.VTable, self.vtable).SetVariableIntegerChangeHandler(@ptrCast(*const IUIAnimationVariable, self), handler);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const UI_ANIMATION_STORYBOARD_STATUS = enum(i32) {
BUILDING = 0,
SCHEDULED = 1,
CANCELLED = 2,
PLAYING = 3,
TRUNCATED = 4,
FINISHED = 5,
READY = 6,
INSUFFICIENT_PRIORITY = 7,
};
pub const UI_ANIMATION_STORYBOARD_BUILDING = UI_ANIMATION_STORYBOARD_STATUS.BUILDING;
pub const UI_ANIMATION_STORYBOARD_SCHEDULED = UI_ANIMATION_STORYBOARD_STATUS.SCHEDULED;
pub const UI_ANIMATION_STORYBOARD_CANCELLED = UI_ANIMATION_STORYBOARD_STATUS.CANCELLED;
pub const UI_ANIMATION_STORYBOARD_PLAYING = UI_ANIMATION_STORYBOARD_STATUS.PLAYING;
pub const UI_ANIMATION_STORYBOARD_TRUNCATED = UI_ANIMATION_STORYBOARD_STATUS.TRUNCATED;
pub const UI_ANIMATION_STORYBOARD_FINISHED = UI_ANIMATION_STORYBOARD_STATUS.FINISHED;
pub const UI_ANIMATION_STORYBOARD_READY = UI_ANIMATION_STORYBOARD_STATUS.READY;
pub const UI_ANIMATION_STORYBOARD_INSUFFICIENT_PRIORITY = UI_ANIMATION_STORYBOARD_STATUS.INSUFFICIENT_PRIORITY;
pub const UI_ANIMATION_SCHEDULING_RESULT = enum(i32) {
UNEXPECTED_FAILURE = 0,
INSUFFICIENT_PRIORITY = 1,
ALREADY_SCHEDULED = 2,
SUCCEEDED = 3,
DEFERRED = 4,
};
pub const UI_ANIMATION_SCHEDULING_UNEXPECTED_FAILURE = UI_ANIMATION_SCHEDULING_RESULT.UNEXPECTED_FAILURE;
pub const UI_ANIMATION_SCHEDULING_INSUFFICIENT_PRIORITY = UI_ANIMATION_SCHEDULING_RESULT.INSUFFICIENT_PRIORITY;
pub const UI_ANIMATION_SCHEDULING_ALREADY_SCHEDULED = UI_ANIMATION_SCHEDULING_RESULT.ALREADY_SCHEDULED;
pub const UI_ANIMATION_SCHEDULING_SUCCEEDED = UI_ANIMATION_SCHEDULING_RESULT.SUCCEEDED;
pub const UI_ANIMATION_SCHEDULING_DEFERRED = UI_ANIMATION_SCHEDULING_RESULT.DEFERRED;
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAnimationStoryboard_Value = Guid.initString("a8ff128f-9bf9-4af1-9e67-e5e410defb84");
pub const IID_IUIAnimationStoryboard = &IID_IUIAnimationStoryboard_Value;
pub const IUIAnimationStoryboard = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
AddTransition: fn(
self: *const IUIAnimationStoryboard,
variable: ?*IUIAnimationVariable,
transition: ?*IUIAnimationTransition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddKeyframeAtOffset: fn(
self: *const IUIAnimationStoryboard,
existingKeyframe: UI_ANIMATION_KEYFRAME,
offset: f64,
keyframe: ?*UI_ANIMATION_KEYFRAME,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddKeyframeAfterTransition: fn(
self: *const IUIAnimationStoryboard,
transition: ?*IUIAnimationTransition,
keyframe: ?*UI_ANIMATION_KEYFRAME,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddTransitionAtKeyframe: fn(
self: *const IUIAnimationStoryboard,
variable: ?*IUIAnimationVariable,
transition: ?*IUIAnimationTransition,
startKeyframe: UI_ANIMATION_KEYFRAME,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddTransitionBetweenKeyframes: fn(
self: *const IUIAnimationStoryboard,
variable: ?*IUIAnimationVariable,
transition: ?*IUIAnimationTransition,
startKeyframe: UI_ANIMATION_KEYFRAME,
endKeyframe: UI_ANIMATION_KEYFRAME,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RepeatBetweenKeyframes: fn(
self: *const IUIAnimationStoryboard,
startKeyframe: UI_ANIMATION_KEYFRAME,
endKeyframe: UI_ANIMATION_KEYFRAME,
repetitionCount: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HoldVariable: fn(
self: *const IUIAnimationStoryboard,
variable: ?*IUIAnimationVariable,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetLongestAcceptableDelay: fn(
self: *const IUIAnimationStoryboard,
delay: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Schedule: fn(
self: *const IUIAnimationStoryboard,
timeNow: f64,
schedulingResult: ?*UI_ANIMATION_SCHEDULING_RESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Conclude: fn(
self: *const IUIAnimationStoryboard,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Finish: fn(
self: *const IUIAnimationStoryboard,
completionDeadline: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Abandon: fn(
self: *const IUIAnimationStoryboard,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetTag: fn(
self: *const IUIAnimationStoryboard,
object: ?*IUnknown,
id: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTag: fn(
self: *const IUIAnimationStoryboard,
object: ?*?*IUnknown,
id: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStatus: fn(
self: *const IUIAnimationStoryboard,
status: ?*UI_ANIMATION_STORYBOARD_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetElapsedTime: fn(
self: *const IUIAnimationStoryboard,
elapsedTime: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetStoryboardEventHandler: fn(
self: *const IUIAnimationStoryboard,
handler: ?*IUIAnimationStoryboardEventHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard_AddTransition(self: *const T, variable: ?*IUIAnimationVariable, transition: ?*IUIAnimationTransition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard.VTable, self.vtable).AddTransition(@ptrCast(*const IUIAnimationStoryboard, self), variable, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard_AddKeyframeAtOffset(self: *const T, existingKeyframe: UI_ANIMATION_KEYFRAME, offset: f64, keyframe: ?*UI_ANIMATION_KEYFRAME) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard.VTable, self.vtable).AddKeyframeAtOffset(@ptrCast(*const IUIAnimationStoryboard, self), existingKeyframe, offset, keyframe);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard_AddKeyframeAfterTransition(self: *const T, transition: ?*IUIAnimationTransition, keyframe: ?*UI_ANIMATION_KEYFRAME) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard.VTable, self.vtable).AddKeyframeAfterTransition(@ptrCast(*const IUIAnimationStoryboard, self), transition, keyframe);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard_AddTransitionAtKeyframe(self: *const T, variable: ?*IUIAnimationVariable, transition: ?*IUIAnimationTransition, startKeyframe: UI_ANIMATION_KEYFRAME) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard.VTable, self.vtable).AddTransitionAtKeyframe(@ptrCast(*const IUIAnimationStoryboard, self), variable, transition, startKeyframe);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard_AddTransitionBetweenKeyframes(self: *const T, variable: ?*IUIAnimationVariable, transition: ?*IUIAnimationTransition, startKeyframe: UI_ANIMATION_KEYFRAME, endKeyframe: UI_ANIMATION_KEYFRAME) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard.VTable, self.vtable).AddTransitionBetweenKeyframes(@ptrCast(*const IUIAnimationStoryboard, self), variable, transition, startKeyframe, endKeyframe);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard_RepeatBetweenKeyframes(self: *const T, startKeyframe: UI_ANIMATION_KEYFRAME, endKeyframe: UI_ANIMATION_KEYFRAME, repetitionCount: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard.VTable, self.vtable).RepeatBetweenKeyframes(@ptrCast(*const IUIAnimationStoryboard, self), startKeyframe, endKeyframe, repetitionCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard_HoldVariable(self: *const T, variable: ?*IUIAnimationVariable) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard.VTable, self.vtable).HoldVariable(@ptrCast(*const IUIAnimationStoryboard, self), variable);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard_SetLongestAcceptableDelay(self: *const T, delay: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard.VTable, self.vtable).SetLongestAcceptableDelay(@ptrCast(*const IUIAnimationStoryboard, self), delay);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard_Schedule(self: *const T, timeNow: f64, schedulingResult: ?*UI_ANIMATION_SCHEDULING_RESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard.VTable, self.vtable).Schedule(@ptrCast(*const IUIAnimationStoryboard, self), timeNow, schedulingResult);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard_Conclude(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard.VTable, self.vtable).Conclude(@ptrCast(*const IUIAnimationStoryboard, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard_Finish(self: *const T, completionDeadline: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard.VTable, self.vtable).Finish(@ptrCast(*const IUIAnimationStoryboard, self), completionDeadline);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard_Abandon(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard.VTable, self.vtable).Abandon(@ptrCast(*const IUIAnimationStoryboard, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard_SetTag(self: *const T, object: ?*IUnknown, id: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard.VTable, self.vtable).SetTag(@ptrCast(*const IUIAnimationStoryboard, self), object, id);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard_GetTag(self: *const T, object: ?*?*IUnknown, id: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard.VTable, self.vtable).GetTag(@ptrCast(*const IUIAnimationStoryboard, self), object, id);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard_GetStatus(self: *const T, status: ?*UI_ANIMATION_STORYBOARD_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard.VTable, self.vtable).GetStatus(@ptrCast(*const IUIAnimationStoryboard, self), status);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard_GetElapsedTime(self: *const T, elapsedTime: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard.VTable, self.vtable).GetElapsedTime(@ptrCast(*const IUIAnimationStoryboard, self), elapsedTime);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard_SetStoryboardEventHandler(self: *const T, handler: ?*IUIAnimationStoryboardEventHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard.VTable, self.vtable).SetStoryboardEventHandler(@ptrCast(*const IUIAnimationStoryboard, self), handler);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAnimationTransition_Value = Guid.initString("dc6ce252-f731-41cf-b610-614b6ca049ad");
pub const IID_IUIAnimationTransition = &IID_IUIAnimationTransition_Value;
pub const IUIAnimationTransition = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetInitialValue: fn(
self: *const IUIAnimationTransition,
value: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetInitialVelocity: fn(
self: *const IUIAnimationTransition,
velocity: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsDurationKnown: fn(
self: *const IUIAnimationTransition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDuration: fn(
self: *const IUIAnimationTransition,
duration: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransition_SetInitialValue(self: *const T, value: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransition.VTable, self.vtable).SetInitialValue(@ptrCast(*const IUIAnimationTransition, self), value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransition_SetInitialVelocity(self: *const T, velocity: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransition.VTable, self.vtable).SetInitialVelocity(@ptrCast(*const IUIAnimationTransition, self), velocity);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransition_IsDurationKnown(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransition.VTable, self.vtable).IsDurationKnown(@ptrCast(*const IUIAnimationTransition, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransition_GetDuration(self: *const T, duration: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransition.VTable, self.vtable).GetDuration(@ptrCast(*const IUIAnimationTransition, self), duration);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAnimationManagerEventHandler_Value = Guid.initString("783321ed-78a3-4366-b574-6af607a64788");
pub const IID_IUIAnimationManagerEventHandler = &IID_IUIAnimationManagerEventHandler_Value;
pub const IUIAnimationManagerEventHandler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OnManagerStatusChanged: fn(
self: *const IUIAnimationManagerEventHandler,
newStatus: UI_ANIMATION_MANAGER_STATUS,
previousStatus: UI_ANIMATION_MANAGER_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManagerEventHandler_OnManagerStatusChanged(self: *const T, newStatus: UI_ANIMATION_MANAGER_STATUS, previousStatus: UI_ANIMATION_MANAGER_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManagerEventHandler.VTable, self.vtable).OnManagerStatusChanged(@ptrCast(*const IUIAnimationManagerEventHandler, self), newStatus, previousStatus);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAnimationVariableChangeHandler_Value = Guid.initString("6358b7ba-87d2-42d5-bf71-82e919dd5862");
pub const IID_IUIAnimationVariableChangeHandler = &IID_IUIAnimationVariableChangeHandler_Value;
pub const IUIAnimationVariableChangeHandler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OnValueChanged: fn(
self: *const IUIAnimationVariableChangeHandler,
storyboard: ?*IUIAnimationStoryboard,
variable: ?*IUIAnimationVariable,
newValue: f64,
previousValue: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariableChangeHandler_OnValueChanged(self: *const T, storyboard: ?*IUIAnimationStoryboard, variable: ?*IUIAnimationVariable, newValue: f64, previousValue: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariableChangeHandler.VTable, self.vtable).OnValueChanged(@ptrCast(*const IUIAnimationVariableChangeHandler, self), storyboard, variable, newValue, previousValue);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAnimationVariableIntegerChangeHandler_Value = Guid.initString("bb3e1550-356e-44b0-99da-85ac6017865e");
pub const IID_IUIAnimationVariableIntegerChangeHandler = &IID_IUIAnimationVariableIntegerChangeHandler_Value;
pub const IUIAnimationVariableIntegerChangeHandler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OnIntegerValueChanged: fn(
self: *const IUIAnimationVariableIntegerChangeHandler,
storyboard: ?*IUIAnimationStoryboard,
variable: ?*IUIAnimationVariable,
newValue: i32,
previousValue: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariableIntegerChangeHandler_OnIntegerValueChanged(self: *const T, storyboard: ?*IUIAnimationStoryboard, variable: ?*IUIAnimationVariable, newValue: i32, previousValue: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariableIntegerChangeHandler.VTable, self.vtable).OnIntegerValueChanged(@ptrCast(*const IUIAnimationVariableIntegerChangeHandler, self), storyboard, variable, newValue, previousValue);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAnimationStoryboardEventHandler_Value = Guid.initString("3d5c9008-ec7c-4364-9f8a-9af3c58cbae6");
pub const IID_IUIAnimationStoryboardEventHandler = &IID_IUIAnimationStoryboardEventHandler_Value;
pub const IUIAnimationStoryboardEventHandler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OnStoryboardStatusChanged: fn(
self: *const IUIAnimationStoryboardEventHandler,
storyboard: ?*IUIAnimationStoryboard,
newStatus: UI_ANIMATION_STORYBOARD_STATUS,
previousStatus: UI_ANIMATION_STORYBOARD_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OnStoryboardUpdated: fn(
self: *const IUIAnimationStoryboardEventHandler,
storyboard: ?*IUIAnimationStoryboard,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboardEventHandler_OnStoryboardStatusChanged(self: *const T, storyboard: ?*IUIAnimationStoryboard, newStatus: UI_ANIMATION_STORYBOARD_STATUS, previousStatus: UI_ANIMATION_STORYBOARD_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboardEventHandler.VTable, self.vtable).OnStoryboardStatusChanged(@ptrCast(*const IUIAnimationStoryboardEventHandler, self), storyboard, newStatus, previousStatus);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboardEventHandler_OnStoryboardUpdated(self: *const T, storyboard: ?*IUIAnimationStoryboard) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboardEventHandler.VTable, self.vtable).OnStoryboardUpdated(@ptrCast(*const IUIAnimationStoryboardEventHandler, self), storyboard);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const UI_ANIMATION_PRIORITY_EFFECT = enum(i32) {
FAILURE = 0,
DELAY = 1,
};
pub const UI_ANIMATION_PRIORITY_EFFECT_FAILURE = UI_ANIMATION_PRIORITY_EFFECT.FAILURE;
pub const UI_ANIMATION_PRIORITY_EFFECT_DELAY = UI_ANIMATION_PRIORITY_EFFECT.DELAY;
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAnimationPriorityComparison_Value = Guid.initString("83fa9b74-5f86-4618-bc6a-a2fac19b3f44");
pub const IID_IUIAnimationPriorityComparison = &IID_IUIAnimationPriorityComparison_Value;
pub const IUIAnimationPriorityComparison = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
HasPriority: fn(
self: *const IUIAnimationPriorityComparison,
scheduledStoryboard: ?*IUIAnimationStoryboard,
newStoryboard: ?*IUIAnimationStoryboard,
priorityEffect: UI_ANIMATION_PRIORITY_EFFECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationPriorityComparison_HasPriority(self: *const T, scheduledStoryboard: ?*IUIAnimationStoryboard, newStoryboard: ?*IUIAnimationStoryboard, priorityEffect: UI_ANIMATION_PRIORITY_EFFECT) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationPriorityComparison.VTable, self.vtable).HasPriority(@ptrCast(*const IUIAnimationPriorityComparison, self), scheduledStoryboard, newStoryboard, priorityEffect);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const UI_ANIMATION_SLOPE = enum(i32) {
INCREASING = 0,
DECREASING = 1,
};
pub const UI_ANIMATION_SLOPE_INCREASING = UI_ANIMATION_SLOPE.INCREASING;
pub const UI_ANIMATION_SLOPE_DECREASING = UI_ANIMATION_SLOPE.DECREASING;
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAnimationTransitionLibrary_Value = Guid.initString("ca5a14b1-d24f-48b8-8fe4-c78169ba954e");
pub const IID_IUIAnimationTransitionLibrary = &IID_IUIAnimationTransitionLibrary_Value;
pub const IUIAnimationTransitionLibrary = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CreateInstantaneousTransition: fn(
self: *const IUIAnimationTransitionLibrary,
finalValue: f64,
transition: ?*?*IUIAnimationTransition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateConstantTransition: fn(
self: *const IUIAnimationTransitionLibrary,
duration: f64,
transition: ?*?*IUIAnimationTransition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateDiscreteTransition: fn(
self: *const IUIAnimationTransitionLibrary,
delay: f64,
finalValue: f64,
hold: f64,
transition: ?*?*IUIAnimationTransition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateLinearTransition: fn(
self: *const IUIAnimationTransitionLibrary,
duration: f64,
finalValue: f64,
transition: ?*?*IUIAnimationTransition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateLinearTransitionFromSpeed: fn(
self: *const IUIAnimationTransitionLibrary,
speed: f64,
finalValue: f64,
transition: ?*?*IUIAnimationTransition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateSinusoidalTransitionFromVelocity: fn(
self: *const IUIAnimationTransitionLibrary,
duration: f64,
period: f64,
transition: ?*?*IUIAnimationTransition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateSinusoidalTransitionFromRange: fn(
self: *const IUIAnimationTransitionLibrary,
duration: f64,
minimumValue: f64,
maximumValue: f64,
period: f64,
slope: UI_ANIMATION_SLOPE,
transition: ?*?*IUIAnimationTransition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateAccelerateDecelerateTransition: fn(
self: *const IUIAnimationTransitionLibrary,
duration: f64,
finalValue: f64,
accelerationRatio: f64,
decelerationRatio: f64,
transition: ?*?*IUIAnimationTransition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateReversalTransition: fn(
self: *const IUIAnimationTransitionLibrary,
duration: f64,
transition: ?*?*IUIAnimationTransition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateCubicTransition: fn(
self: *const IUIAnimationTransitionLibrary,
duration: f64,
finalValue: f64,
finalVelocity: f64,
transition: ?*?*IUIAnimationTransition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateSmoothStopTransition: fn(
self: *const IUIAnimationTransitionLibrary,
maximumDuration: f64,
finalValue: f64,
transition: ?*?*IUIAnimationTransition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateParabolicTransitionFromAcceleration: fn(
self: *const IUIAnimationTransitionLibrary,
finalValue: f64,
finalVelocity: f64,
acceleration: f64,
transition: ?*?*IUIAnimationTransition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary_CreateInstantaneousTransition(self: *const T, finalValue: f64, transition: ?*?*IUIAnimationTransition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary.VTable, self.vtable).CreateInstantaneousTransition(@ptrCast(*const IUIAnimationTransitionLibrary, self), finalValue, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary_CreateConstantTransition(self: *const T, duration: f64, transition: ?*?*IUIAnimationTransition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary.VTable, self.vtable).CreateConstantTransition(@ptrCast(*const IUIAnimationTransitionLibrary, self), duration, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary_CreateDiscreteTransition(self: *const T, delay: f64, finalValue: f64, hold: f64, transition: ?*?*IUIAnimationTransition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary.VTable, self.vtable).CreateDiscreteTransition(@ptrCast(*const IUIAnimationTransitionLibrary, self), delay, finalValue, hold, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary_CreateLinearTransition(self: *const T, duration: f64, finalValue: f64, transition: ?*?*IUIAnimationTransition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary.VTable, self.vtable).CreateLinearTransition(@ptrCast(*const IUIAnimationTransitionLibrary, self), duration, finalValue, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary_CreateLinearTransitionFromSpeed(self: *const T, speed: f64, finalValue: f64, transition: ?*?*IUIAnimationTransition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary.VTable, self.vtable).CreateLinearTransitionFromSpeed(@ptrCast(*const IUIAnimationTransitionLibrary, self), speed, finalValue, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary_CreateSinusoidalTransitionFromVelocity(self: *const T, duration: f64, period: f64, transition: ?*?*IUIAnimationTransition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary.VTable, self.vtable).CreateSinusoidalTransitionFromVelocity(@ptrCast(*const IUIAnimationTransitionLibrary, self), duration, period, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary_CreateSinusoidalTransitionFromRange(self: *const T, duration: f64, minimumValue: f64, maximumValue: f64, period: f64, slope: UI_ANIMATION_SLOPE, transition: ?*?*IUIAnimationTransition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary.VTable, self.vtable).CreateSinusoidalTransitionFromRange(@ptrCast(*const IUIAnimationTransitionLibrary, self), duration, minimumValue, maximumValue, period, slope, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary_CreateAccelerateDecelerateTransition(self: *const T, duration: f64, finalValue: f64, accelerationRatio: f64, decelerationRatio: f64, transition: ?*?*IUIAnimationTransition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary.VTable, self.vtable).CreateAccelerateDecelerateTransition(@ptrCast(*const IUIAnimationTransitionLibrary, self), duration, finalValue, accelerationRatio, decelerationRatio, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary_CreateReversalTransition(self: *const T, duration: f64, transition: ?*?*IUIAnimationTransition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary.VTable, self.vtable).CreateReversalTransition(@ptrCast(*const IUIAnimationTransitionLibrary, self), duration, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary_CreateCubicTransition(self: *const T, duration: f64, finalValue: f64, finalVelocity: f64, transition: ?*?*IUIAnimationTransition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary.VTable, self.vtable).CreateCubicTransition(@ptrCast(*const IUIAnimationTransitionLibrary, self), duration, finalValue, finalVelocity, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary_CreateSmoothStopTransition(self: *const T, maximumDuration: f64, finalValue: f64, transition: ?*?*IUIAnimationTransition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary.VTable, self.vtable).CreateSmoothStopTransition(@ptrCast(*const IUIAnimationTransitionLibrary, self), maximumDuration, finalValue, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary_CreateParabolicTransitionFromAcceleration(self: *const T, finalValue: f64, finalVelocity: f64, acceleration: f64, transition: ?*?*IUIAnimationTransition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary.VTable, self.vtable).CreateParabolicTransitionFromAcceleration(@ptrCast(*const IUIAnimationTransitionLibrary, self), finalValue, finalVelocity, acceleration, transition);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const UI_ANIMATION_DEPENDENCIES = enum(u32) {
NONE = 0,
INTERMEDIATE_VALUES = 1,
FINAL_VALUE = 2,
FINAL_VELOCITY = 4,
DURATION = 8,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
INTERMEDIATE_VALUES: u1 = 0,
FINAL_VALUE: u1 = 0,
FINAL_VELOCITY: u1 = 0,
DURATION: u1 = 0,
}) UI_ANIMATION_DEPENDENCIES {
return @intToEnum(UI_ANIMATION_DEPENDENCIES,
(if (o.NONE == 1) @enumToInt(UI_ANIMATION_DEPENDENCIES.NONE) else 0)
| (if (o.INTERMEDIATE_VALUES == 1) @enumToInt(UI_ANIMATION_DEPENDENCIES.INTERMEDIATE_VALUES) else 0)
| (if (o.FINAL_VALUE == 1) @enumToInt(UI_ANIMATION_DEPENDENCIES.FINAL_VALUE) else 0)
| (if (o.FINAL_VELOCITY == 1) @enumToInt(UI_ANIMATION_DEPENDENCIES.FINAL_VELOCITY) else 0)
| (if (o.DURATION == 1) @enumToInt(UI_ANIMATION_DEPENDENCIES.DURATION) else 0)
);
}
};
pub const UI_ANIMATION_DEPENDENCY_NONE = UI_ANIMATION_DEPENDENCIES.NONE;
pub const UI_ANIMATION_DEPENDENCY_INTERMEDIATE_VALUES = UI_ANIMATION_DEPENDENCIES.INTERMEDIATE_VALUES;
pub const UI_ANIMATION_DEPENDENCY_FINAL_VALUE = UI_ANIMATION_DEPENDENCIES.FINAL_VALUE;
pub const UI_ANIMATION_DEPENDENCY_FINAL_VELOCITY = UI_ANIMATION_DEPENDENCIES.FINAL_VELOCITY;
pub const UI_ANIMATION_DEPENDENCY_DURATION = UI_ANIMATION_DEPENDENCIES.DURATION;
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAnimationInterpolator_Value = Guid.initString("7815cbba-ddf7-478c-a46c-7b6c738b7978");
pub const IID_IUIAnimationInterpolator = &IID_IUIAnimationInterpolator_Value;
pub const IUIAnimationInterpolator = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetInitialValueAndVelocity: fn(
self: *const IUIAnimationInterpolator,
initialValue: f64,
initialVelocity: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetDuration: fn(
self: *const IUIAnimationInterpolator,
duration: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDuration: fn(
self: *const IUIAnimationInterpolator,
duration: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFinalValue: fn(
self: *const IUIAnimationInterpolator,
value: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
InterpolateValue: fn(
self: *const IUIAnimationInterpolator,
offset: f64,
value: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
InterpolateVelocity: fn(
self: *const IUIAnimationInterpolator,
offset: f64,
velocity: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDependencies: fn(
self: *const IUIAnimationInterpolator,
initialValueDependencies: ?*UI_ANIMATION_DEPENDENCIES,
initialVelocityDependencies: ?*UI_ANIMATION_DEPENDENCIES,
durationDependencies: ?*UI_ANIMATION_DEPENDENCIES,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationInterpolator_SetInitialValueAndVelocity(self: *const T, initialValue: f64, initialVelocity: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationInterpolator.VTable, self.vtable).SetInitialValueAndVelocity(@ptrCast(*const IUIAnimationInterpolator, self), initialValue, initialVelocity);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationInterpolator_SetDuration(self: *const T, duration: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationInterpolator.VTable, self.vtable).SetDuration(@ptrCast(*const IUIAnimationInterpolator, self), duration);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationInterpolator_GetDuration(self: *const T, duration: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationInterpolator.VTable, self.vtable).GetDuration(@ptrCast(*const IUIAnimationInterpolator, self), duration);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationInterpolator_GetFinalValue(self: *const T, value: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationInterpolator.VTable, self.vtable).GetFinalValue(@ptrCast(*const IUIAnimationInterpolator, self), value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationInterpolator_InterpolateValue(self: *const T, offset: f64, value: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationInterpolator.VTable, self.vtable).InterpolateValue(@ptrCast(*const IUIAnimationInterpolator, self), offset, value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationInterpolator_InterpolateVelocity(self: *const T, offset: f64, velocity: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationInterpolator.VTable, self.vtable).InterpolateVelocity(@ptrCast(*const IUIAnimationInterpolator, self), offset, velocity);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationInterpolator_GetDependencies(self: *const T, initialValueDependencies: ?*UI_ANIMATION_DEPENDENCIES, initialVelocityDependencies: ?*UI_ANIMATION_DEPENDENCIES, durationDependencies: ?*UI_ANIMATION_DEPENDENCIES) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationInterpolator.VTable, self.vtable).GetDependencies(@ptrCast(*const IUIAnimationInterpolator, self), initialValueDependencies, initialVelocityDependencies, durationDependencies);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAnimationTransitionFactory_Value = Guid.initString("fcd91e03-3e3b-45ad-bbb1-6dfc8153743d");
pub const IID_IUIAnimationTransitionFactory = &IID_IUIAnimationTransitionFactory_Value;
pub const IUIAnimationTransitionFactory = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CreateTransition: fn(
self: *const IUIAnimationTransitionFactory,
interpolator: ?*IUIAnimationInterpolator,
transition: ?*?*IUIAnimationTransition,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionFactory_CreateTransition(self: *const T, interpolator: ?*IUIAnimationInterpolator, transition: ?*?*IUIAnimationTransition) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionFactory.VTable, self.vtable).CreateTransition(@ptrCast(*const IUIAnimationTransitionFactory, self), interpolator, transition);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const UI_ANIMATION_IDLE_BEHAVIOR = enum(i32) {
CONTINUE = 0,
DISABLE = 1,
};
pub const UI_ANIMATION_IDLE_BEHAVIOR_CONTINUE = UI_ANIMATION_IDLE_BEHAVIOR.CONTINUE;
pub const UI_ANIMATION_IDLE_BEHAVIOR_DISABLE = UI_ANIMATION_IDLE_BEHAVIOR.DISABLE;
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAnimationTimer_Value = Guid.initString("6b0efad1-a053-41d6-9085-33a689144665");
pub const IID_IUIAnimationTimer = &IID_IUIAnimationTimer_Value;
pub const IUIAnimationTimer = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetTimerUpdateHandler: fn(
self: *const IUIAnimationTimer,
updateHandler: ?*IUIAnimationTimerUpdateHandler,
idleBehavior: UI_ANIMATION_IDLE_BEHAVIOR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetTimerEventHandler: fn(
self: *const IUIAnimationTimer,
handler: ?*IUIAnimationTimerEventHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Enable: fn(
self: *const IUIAnimationTimer,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Disable: fn(
self: *const IUIAnimationTimer,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsEnabled: fn(
self: *const IUIAnimationTimer,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTime: fn(
self: *const IUIAnimationTimer,
seconds: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetFrameRateThreshold: fn(
self: *const IUIAnimationTimer,
framesPerSecond: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTimer_SetTimerUpdateHandler(self: *const T, updateHandler: ?*IUIAnimationTimerUpdateHandler, idleBehavior: UI_ANIMATION_IDLE_BEHAVIOR) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTimer.VTable, self.vtable).SetTimerUpdateHandler(@ptrCast(*const IUIAnimationTimer, self), updateHandler, idleBehavior);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTimer_SetTimerEventHandler(self: *const T, handler: ?*IUIAnimationTimerEventHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTimer.VTable, self.vtable).SetTimerEventHandler(@ptrCast(*const IUIAnimationTimer, self), handler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTimer_Enable(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTimer.VTable, self.vtable).Enable(@ptrCast(*const IUIAnimationTimer, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTimer_Disable(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTimer.VTable, self.vtable).Disable(@ptrCast(*const IUIAnimationTimer, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTimer_IsEnabled(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTimer.VTable, self.vtable).IsEnabled(@ptrCast(*const IUIAnimationTimer, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTimer_GetTime(self: *const T, seconds: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTimer.VTable, self.vtable).GetTime(@ptrCast(*const IUIAnimationTimer, self), seconds);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTimer_SetFrameRateThreshold(self: *const T, framesPerSecond: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTimer.VTable, self.vtable).SetFrameRateThreshold(@ptrCast(*const IUIAnimationTimer, self), framesPerSecond);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAnimationTimerUpdateHandler_Value = Guid.initString("195509b7-5d5e-4e3e-b278-ee3759b367ad");
pub const IID_IUIAnimationTimerUpdateHandler = &IID_IUIAnimationTimerUpdateHandler_Value;
pub const IUIAnimationTimerUpdateHandler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OnUpdate: fn(
self: *const IUIAnimationTimerUpdateHandler,
timeNow: f64,
result: ?*UI_ANIMATION_UPDATE_RESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetTimerClientEventHandler: fn(
self: *const IUIAnimationTimerUpdateHandler,
handler: ?*IUIAnimationTimerClientEventHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ClearTimerClientEventHandler: fn(
self: *const IUIAnimationTimerUpdateHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTimerUpdateHandler_OnUpdate(self: *const T, timeNow: f64, result: ?*UI_ANIMATION_UPDATE_RESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTimerUpdateHandler.VTable, self.vtable).OnUpdate(@ptrCast(*const IUIAnimationTimerUpdateHandler, self), timeNow, result);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTimerUpdateHandler_SetTimerClientEventHandler(self: *const T, handler: ?*IUIAnimationTimerClientEventHandler) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTimerUpdateHandler.VTable, self.vtable).SetTimerClientEventHandler(@ptrCast(*const IUIAnimationTimerUpdateHandler, self), handler);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTimerUpdateHandler_ClearTimerClientEventHandler(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTimerUpdateHandler.VTable, self.vtable).ClearTimerClientEventHandler(@ptrCast(*const IUIAnimationTimerUpdateHandler, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const UI_ANIMATION_TIMER_CLIENT_STATUS = enum(i32) {
IDLE = 0,
BUSY = 1,
};
pub const UI_ANIMATION_TIMER_CLIENT_IDLE = UI_ANIMATION_TIMER_CLIENT_STATUS.IDLE;
pub const UI_ANIMATION_TIMER_CLIENT_BUSY = UI_ANIMATION_TIMER_CLIENT_STATUS.BUSY;
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAnimationTimerClientEventHandler_Value = Guid.initString("bedb4db6-94fa-4bfb-a47f-ef2d9e408c25");
pub const IID_IUIAnimationTimerClientEventHandler = &IID_IUIAnimationTimerClientEventHandler_Value;
pub const IUIAnimationTimerClientEventHandler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OnTimerClientStatusChanged: fn(
self: *const IUIAnimationTimerClientEventHandler,
newStatus: UI_ANIMATION_TIMER_CLIENT_STATUS,
previousStatus: UI_ANIMATION_TIMER_CLIENT_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTimerClientEventHandler_OnTimerClientStatusChanged(self: *const T, newStatus: UI_ANIMATION_TIMER_CLIENT_STATUS, previousStatus: UI_ANIMATION_TIMER_CLIENT_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTimerClientEventHandler.VTable, self.vtable).OnTimerClientStatusChanged(@ptrCast(*const IUIAnimationTimerClientEventHandler, self), newStatus, previousStatus);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IUIAnimationTimerEventHandler_Value = Guid.initString("274a7dea-d771-4095-abbd-8df7abd23ce3");
pub const IID_IUIAnimationTimerEventHandler = &IID_IUIAnimationTimerEventHandler_Value;
pub const IUIAnimationTimerEventHandler = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OnPreUpdate: fn(
self: *const IUIAnimationTimerEventHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OnPostUpdate: fn(
self: *const IUIAnimationTimerEventHandler,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OnRenderingTooSlow: fn(
self: *const IUIAnimationTimerEventHandler,
framesPerSecond: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTimerEventHandler_OnPreUpdate(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTimerEventHandler.VTable, self.vtable).OnPreUpdate(@ptrCast(*const IUIAnimationTimerEventHandler, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTimerEventHandler_OnPostUpdate(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTimerEventHandler.VTable, self.vtable).OnPostUpdate(@ptrCast(*const IUIAnimationTimerEventHandler, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTimerEventHandler_OnRenderingTooSlow(self: *const T, framesPerSecond: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTimerEventHandler.VTable, self.vtable).OnRenderingTooSlow(@ptrCast(*const IUIAnimationTimerEventHandler, self), framesPerSecond);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IUIAnimationManager2_Value = Guid.initString("d8b6f7d4-4109-4d3f-acee-879926968cb1");
pub const IID_IUIAnimationManager2 = &IID_IUIAnimationManager2_Value;
pub const IUIAnimationManager2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CreateAnimationVectorVariable: fn(
self: *const IUIAnimationManager2,
initialValue: [*]const f64,
cDimension: u32,
variable: ?*?*IUIAnimationVariable2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateAnimationVariable: fn(
self: *const IUIAnimationManager2,
initialValue: f64,
variable: ?*?*IUIAnimationVariable2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ScheduleTransition: fn(
self: *const IUIAnimationManager2,
variable: ?*IUIAnimationVariable2,
transition: ?*IUIAnimationTransition2,
timeNow: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateStoryboard: fn(
self: *const IUIAnimationManager2,
storyboard: ?*?*IUIAnimationStoryboard2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FinishAllStoryboards: fn(
self: *const IUIAnimationManager2,
completionDeadline: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AbandonAllStoryboards: fn(
self: *const IUIAnimationManager2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Update: fn(
self: *const IUIAnimationManager2,
timeNow: f64,
updateResult: ?*UI_ANIMATION_UPDATE_RESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetVariableFromTag: fn(
self: *const IUIAnimationManager2,
object: ?*IUnknown,
id: u32,
variable: ?*?*IUIAnimationVariable2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStoryboardFromTag: fn(
self: *const IUIAnimationManager2,
object: ?*IUnknown,
id: u32,
storyboard: ?*?*IUIAnimationStoryboard2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EstimateNextEventTime: fn(
self: *const IUIAnimationManager2,
seconds: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStatus: fn(
self: *const IUIAnimationManager2,
status: ?*UI_ANIMATION_MANAGER_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetAnimationMode: fn(
self: *const IUIAnimationManager2,
mode: UI_ANIMATION_MODE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Pause: fn(
self: *const IUIAnimationManager2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Resume: fn(
self: *const IUIAnimationManager2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetManagerEventHandler: fn(
self: *const IUIAnimationManager2,
handler: ?*IUIAnimationManagerEventHandler2,
fRegisterForNextAnimationEvent: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCancelPriorityComparison: fn(
self: *const IUIAnimationManager2,
comparison: ?*IUIAnimationPriorityComparison2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetTrimPriorityComparison: fn(
self: *const IUIAnimationManager2,
comparison: ?*IUIAnimationPriorityComparison2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCompressPriorityComparison: fn(
self: *const IUIAnimationManager2,
comparison: ?*IUIAnimationPriorityComparison2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetConcludePriorityComparison: fn(
self: *const IUIAnimationManager2,
comparison: ?*IUIAnimationPriorityComparison2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetDefaultLongestAcceptableDelay: fn(
self: *const IUIAnimationManager2,
delay: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Shutdown: fn(
self: *const IUIAnimationManager2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager2_CreateAnimationVectorVariable(self: *const T, initialValue: [*]const f64, cDimension: u32, variable: ?*?*IUIAnimationVariable2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager2.VTable, self.vtable).CreateAnimationVectorVariable(@ptrCast(*const IUIAnimationManager2, self), initialValue, cDimension, variable);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager2_CreateAnimationVariable(self: *const T, initialValue: f64, variable: ?*?*IUIAnimationVariable2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager2.VTable, self.vtable).CreateAnimationVariable(@ptrCast(*const IUIAnimationManager2, self), initialValue, variable);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager2_ScheduleTransition(self: *const T, variable: ?*IUIAnimationVariable2, transition: ?*IUIAnimationTransition2, timeNow: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager2.VTable, self.vtable).ScheduleTransition(@ptrCast(*const IUIAnimationManager2, self), variable, transition, timeNow);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager2_CreateStoryboard(self: *const T, storyboard: ?*?*IUIAnimationStoryboard2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager2.VTable, self.vtable).CreateStoryboard(@ptrCast(*const IUIAnimationManager2, self), storyboard);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager2_FinishAllStoryboards(self: *const T, completionDeadline: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager2.VTable, self.vtable).FinishAllStoryboards(@ptrCast(*const IUIAnimationManager2, self), completionDeadline);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager2_AbandonAllStoryboards(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager2.VTable, self.vtable).AbandonAllStoryboards(@ptrCast(*const IUIAnimationManager2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager2_Update(self: *const T, timeNow: f64, updateResult: ?*UI_ANIMATION_UPDATE_RESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager2.VTable, self.vtable).Update(@ptrCast(*const IUIAnimationManager2, self), timeNow, updateResult);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager2_GetVariableFromTag(self: *const T, object: ?*IUnknown, id: u32, variable: ?*?*IUIAnimationVariable2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager2.VTable, self.vtable).GetVariableFromTag(@ptrCast(*const IUIAnimationManager2, self), object, id, variable);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager2_GetStoryboardFromTag(self: *const T, object: ?*IUnknown, id: u32, storyboard: ?*?*IUIAnimationStoryboard2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager2.VTable, self.vtable).GetStoryboardFromTag(@ptrCast(*const IUIAnimationManager2, self), object, id, storyboard);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager2_EstimateNextEventTime(self: *const T, seconds: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager2.VTable, self.vtable).EstimateNextEventTime(@ptrCast(*const IUIAnimationManager2, self), seconds);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager2_GetStatus(self: *const T, status: ?*UI_ANIMATION_MANAGER_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager2.VTable, self.vtable).GetStatus(@ptrCast(*const IUIAnimationManager2, self), status);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager2_SetAnimationMode(self: *const T, mode: UI_ANIMATION_MODE) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager2.VTable, self.vtable).SetAnimationMode(@ptrCast(*const IUIAnimationManager2, self), mode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager2_Pause(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager2.VTable, self.vtable).Pause(@ptrCast(*const IUIAnimationManager2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager2_Resume(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager2.VTable, self.vtable).Resume(@ptrCast(*const IUIAnimationManager2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager2_SetManagerEventHandler(self: *const T, handler: ?*IUIAnimationManagerEventHandler2, fRegisterForNextAnimationEvent: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager2.VTable, self.vtable).SetManagerEventHandler(@ptrCast(*const IUIAnimationManager2, self), handler, fRegisterForNextAnimationEvent);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager2_SetCancelPriorityComparison(self: *const T, comparison: ?*IUIAnimationPriorityComparison2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager2.VTable, self.vtable).SetCancelPriorityComparison(@ptrCast(*const IUIAnimationManager2, self), comparison);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager2_SetTrimPriorityComparison(self: *const T, comparison: ?*IUIAnimationPriorityComparison2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager2.VTable, self.vtable).SetTrimPriorityComparison(@ptrCast(*const IUIAnimationManager2, self), comparison);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager2_SetCompressPriorityComparison(self: *const T, comparison: ?*IUIAnimationPriorityComparison2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager2.VTable, self.vtable).SetCompressPriorityComparison(@ptrCast(*const IUIAnimationManager2, self), comparison);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager2_SetConcludePriorityComparison(self: *const T, comparison: ?*IUIAnimationPriorityComparison2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager2.VTable, self.vtable).SetConcludePriorityComparison(@ptrCast(*const IUIAnimationManager2, self), comparison);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager2_SetDefaultLongestAcceptableDelay(self: *const T, delay: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager2.VTable, self.vtable).SetDefaultLongestAcceptableDelay(@ptrCast(*const IUIAnimationManager2, self), delay);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManager2_Shutdown(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManager2.VTable, self.vtable).Shutdown(@ptrCast(*const IUIAnimationManager2, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IUIAnimationVariable2_Value = Guid.initString("4914b304-96ab-44d9-9e77-d5109b7e7466");
pub const IID_IUIAnimationVariable2 = &IID_IUIAnimationVariable2_Value;
pub const IUIAnimationVariable2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetDimension: fn(
self: *const IUIAnimationVariable2,
dimension: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetValue: fn(
self: *const IUIAnimationVariable2,
value: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetVectorValue: fn(
self: *const IUIAnimationVariable2,
value: [*]f64,
cDimension: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCurve: fn(
self: *const IUIAnimationVariable2,
animation: ?*IDCompositionAnimation,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetVectorCurve: fn(
self: *const IUIAnimationVariable2,
animation: [*]?*IDCompositionAnimation,
cDimension: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFinalValue: fn(
self: *const IUIAnimationVariable2,
finalValue: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFinalVectorValue: fn(
self: *const IUIAnimationVariable2,
finalValue: [*]f64,
cDimension: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPreviousValue: fn(
self: *const IUIAnimationVariable2,
previousValue: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPreviousVectorValue: fn(
self: *const IUIAnimationVariable2,
previousValue: [*]f64,
cDimension: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetIntegerValue: fn(
self: *const IUIAnimationVariable2,
value: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetIntegerVectorValue: fn(
self: *const IUIAnimationVariable2,
value: [*]i32,
cDimension: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFinalIntegerValue: fn(
self: *const IUIAnimationVariable2,
finalValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFinalIntegerVectorValue: fn(
self: *const IUIAnimationVariable2,
finalValue: [*]i32,
cDimension: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPreviousIntegerValue: fn(
self: *const IUIAnimationVariable2,
previousValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPreviousIntegerVectorValue: fn(
self: *const IUIAnimationVariable2,
previousValue: [*]i32,
cDimension: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCurrentStoryboard: fn(
self: *const IUIAnimationVariable2,
storyboard: ?*?*IUIAnimationStoryboard2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetLowerBound: fn(
self: *const IUIAnimationVariable2,
bound: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetLowerBoundVector: fn(
self: *const IUIAnimationVariable2,
bound: [*]const f64,
cDimension: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetUpperBound: fn(
self: *const IUIAnimationVariable2,
bound: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetUpperBoundVector: fn(
self: *const IUIAnimationVariable2,
bound: [*]const f64,
cDimension: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetRoundingMode: fn(
self: *const IUIAnimationVariable2,
mode: UI_ANIMATION_ROUNDING_MODE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetTag: fn(
self: *const IUIAnimationVariable2,
object: ?*IUnknown,
id: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTag: fn(
self: *const IUIAnimationVariable2,
object: ?*?*IUnknown,
id: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetVariableChangeHandler: fn(
self: *const IUIAnimationVariable2,
handler: ?*IUIAnimationVariableChangeHandler2,
fRegisterForNextAnimationEvent: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetVariableIntegerChangeHandler: fn(
self: *const IUIAnimationVariable2,
handler: ?*IUIAnimationVariableIntegerChangeHandler2,
fRegisterForNextAnimationEvent: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetVariableCurveChangeHandler: fn(
self: *const IUIAnimationVariable2,
handler: ?*IUIAnimationVariableCurveChangeHandler2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable2_GetDimension(self: *const T, dimension: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable2.VTable, self.vtable).GetDimension(@ptrCast(*const IUIAnimationVariable2, self), dimension);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable2_GetValue(self: *const T, value: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable2.VTable, self.vtable).GetValue(@ptrCast(*const IUIAnimationVariable2, self), value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable2_GetVectorValue(self: *const T, value: [*]f64, cDimension: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable2.VTable, self.vtable).GetVectorValue(@ptrCast(*const IUIAnimationVariable2, self), value, cDimension);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable2_GetCurve(self: *const T, animation: ?*IDCompositionAnimation) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable2.VTable, self.vtable).GetCurve(@ptrCast(*const IUIAnimationVariable2, self), animation);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable2_GetVectorCurve(self: *const T, animation: [*]?*IDCompositionAnimation, cDimension: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable2.VTable, self.vtable).GetVectorCurve(@ptrCast(*const IUIAnimationVariable2, self), animation, cDimension);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable2_GetFinalValue(self: *const T, finalValue: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable2.VTable, self.vtable).GetFinalValue(@ptrCast(*const IUIAnimationVariable2, self), finalValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable2_GetFinalVectorValue(self: *const T, finalValue: [*]f64, cDimension: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable2.VTable, self.vtable).GetFinalVectorValue(@ptrCast(*const IUIAnimationVariable2, self), finalValue, cDimension);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable2_GetPreviousValue(self: *const T, previousValue: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable2.VTable, self.vtable).GetPreviousValue(@ptrCast(*const IUIAnimationVariable2, self), previousValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable2_GetPreviousVectorValue(self: *const T, previousValue: [*]f64, cDimension: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable2.VTable, self.vtable).GetPreviousVectorValue(@ptrCast(*const IUIAnimationVariable2, self), previousValue, cDimension);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable2_GetIntegerValue(self: *const T, value: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable2.VTable, self.vtable).GetIntegerValue(@ptrCast(*const IUIAnimationVariable2, self), value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable2_GetIntegerVectorValue(self: *const T, value: [*]i32, cDimension: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable2.VTable, self.vtable).GetIntegerVectorValue(@ptrCast(*const IUIAnimationVariable2, self), value, cDimension);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable2_GetFinalIntegerValue(self: *const T, finalValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable2.VTable, self.vtable).GetFinalIntegerValue(@ptrCast(*const IUIAnimationVariable2, self), finalValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable2_GetFinalIntegerVectorValue(self: *const T, finalValue: [*]i32, cDimension: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable2.VTable, self.vtable).GetFinalIntegerVectorValue(@ptrCast(*const IUIAnimationVariable2, self), finalValue, cDimension);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable2_GetPreviousIntegerValue(self: *const T, previousValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable2.VTable, self.vtable).GetPreviousIntegerValue(@ptrCast(*const IUIAnimationVariable2, self), previousValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable2_GetPreviousIntegerVectorValue(self: *const T, previousValue: [*]i32, cDimension: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable2.VTable, self.vtable).GetPreviousIntegerVectorValue(@ptrCast(*const IUIAnimationVariable2, self), previousValue, cDimension);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable2_GetCurrentStoryboard(self: *const T, storyboard: ?*?*IUIAnimationStoryboard2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable2.VTable, self.vtable).GetCurrentStoryboard(@ptrCast(*const IUIAnimationVariable2, self), storyboard);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable2_SetLowerBound(self: *const T, bound: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable2.VTable, self.vtable).SetLowerBound(@ptrCast(*const IUIAnimationVariable2, self), bound);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable2_SetLowerBoundVector(self: *const T, bound: [*]const f64, cDimension: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable2.VTable, self.vtable).SetLowerBoundVector(@ptrCast(*const IUIAnimationVariable2, self), bound, cDimension);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable2_SetUpperBound(self: *const T, bound: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable2.VTable, self.vtable).SetUpperBound(@ptrCast(*const IUIAnimationVariable2, self), bound);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable2_SetUpperBoundVector(self: *const T, bound: [*]const f64, cDimension: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable2.VTable, self.vtable).SetUpperBoundVector(@ptrCast(*const IUIAnimationVariable2, self), bound, cDimension);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable2_SetRoundingMode(self: *const T, mode: UI_ANIMATION_ROUNDING_MODE) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable2.VTable, self.vtable).SetRoundingMode(@ptrCast(*const IUIAnimationVariable2, self), mode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable2_SetTag(self: *const T, object: ?*IUnknown, id: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable2.VTable, self.vtable).SetTag(@ptrCast(*const IUIAnimationVariable2, self), object, id);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable2_GetTag(self: *const T, object: ?*?*IUnknown, id: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable2.VTable, self.vtable).GetTag(@ptrCast(*const IUIAnimationVariable2, self), object, id);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable2_SetVariableChangeHandler(self: *const T, handler: ?*IUIAnimationVariableChangeHandler2, fRegisterForNextAnimationEvent: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable2.VTable, self.vtable).SetVariableChangeHandler(@ptrCast(*const IUIAnimationVariable2, self), handler, fRegisterForNextAnimationEvent);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable2_SetVariableIntegerChangeHandler(self: *const T, handler: ?*IUIAnimationVariableIntegerChangeHandler2, fRegisterForNextAnimationEvent: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable2.VTable, self.vtable).SetVariableIntegerChangeHandler(@ptrCast(*const IUIAnimationVariable2, self), handler, fRegisterForNextAnimationEvent);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariable2_SetVariableCurveChangeHandler(self: *const T, handler: ?*IUIAnimationVariableCurveChangeHandler2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariable2.VTable, self.vtable).SetVariableCurveChangeHandler(@ptrCast(*const IUIAnimationVariable2, self), handler);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IUIAnimationTransition2_Value = Guid.initString("62ff9123-a85a-4e9b-a218-435a93e268fd");
pub const IID_IUIAnimationTransition2 = &IID_IUIAnimationTransition2_Value;
pub const IUIAnimationTransition2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetDimension: fn(
self: *const IUIAnimationTransition2,
dimension: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetInitialValue: fn(
self: *const IUIAnimationTransition2,
value: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetInitialVectorValue: fn(
self: *const IUIAnimationTransition2,
value: [*]const f64,
cDimension: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetInitialVelocity: fn(
self: *const IUIAnimationTransition2,
velocity: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetInitialVectorVelocity: fn(
self: *const IUIAnimationTransition2,
velocity: [*]const f64,
cDimension: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsDurationKnown: fn(
self: *const IUIAnimationTransition2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDuration: fn(
self: *const IUIAnimationTransition2,
duration: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransition2_GetDimension(self: *const T, dimension: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransition2.VTable, self.vtable).GetDimension(@ptrCast(*const IUIAnimationTransition2, self), dimension);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransition2_SetInitialValue(self: *const T, value: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransition2.VTable, self.vtable).SetInitialValue(@ptrCast(*const IUIAnimationTransition2, self), value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransition2_SetInitialVectorValue(self: *const T, value: [*]const f64, cDimension: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransition2.VTable, self.vtable).SetInitialVectorValue(@ptrCast(*const IUIAnimationTransition2, self), value, cDimension);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransition2_SetInitialVelocity(self: *const T, velocity: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransition2.VTable, self.vtable).SetInitialVelocity(@ptrCast(*const IUIAnimationTransition2, self), velocity);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransition2_SetInitialVectorVelocity(self: *const T, velocity: [*]const f64, cDimension: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransition2.VTable, self.vtable).SetInitialVectorVelocity(@ptrCast(*const IUIAnimationTransition2, self), velocity, cDimension);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransition2_IsDurationKnown(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransition2.VTable, self.vtable).IsDurationKnown(@ptrCast(*const IUIAnimationTransition2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransition2_GetDuration(self: *const T, duration: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransition2.VTable, self.vtable).GetDuration(@ptrCast(*const IUIAnimationTransition2, self), duration);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IUIAnimationManagerEventHandler2_Value = Guid.initString("f6e022ba-bff3-42ec-9033-e073f33e83c3");
pub const IID_IUIAnimationManagerEventHandler2 = &IID_IUIAnimationManagerEventHandler2_Value;
pub const IUIAnimationManagerEventHandler2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OnManagerStatusChanged: fn(
self: *const IUIAnimationManagerEventHandler2,
newStatus: UI_ANIMATION_MANAGER_STATUS,
previousStatus: UI_ANIMATION_MANAGER_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationManagerEventHandler2_OnManagerStatusChanged(self: *const T, newStatus: UI_ANIMATION_MANAGER_STATUS, previousStatus: UI_ANIMATION_MANAGER_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationManagerEventHandler2.VTable, self.vtable).OnManagerStatusChanged(@ptrCast(*const IUIAnimationManagerEventHandler2, self), newStatus, previousStatus);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IUIAnimationVariableChangeHandler2_Value = Guid.initString("63acc8d2-6eae-4bb0-b879-586dd8cfbe42");
pub const IID_IUIAnimationVariableChangeHandler2 = &IID_IUIAnimationVariableChangeHandler2_Value;
pub const IUIAnimationVariableChangeHandler2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OnValueChanged: fn(
self: *const IUIAnimationVariableChangeHandler2,
storyboard: ?*IUIAnimationStoryboard2,
variable: ?*IUIAnimationVariable2,
newValue: [*]f64,
previousValue: [*]f64,
cDimension: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariableChangeHandler2_OnValueChanged(self: *const T, storyboard: ?*IUIAnimationStoryboard2, variable: ?*IUIAnimationVariable2, newValue: [*]f64, previousValue: [*]f64, cDimension: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariableChangeHandler2.VTable, self.vtable).OnValueChanged(@ptrCast(*const IUIAnimationVariableChangeHandler2, self), storyboard, variable, newValue, previousValue, cDimension);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IUIAnimationVariableIntegerChangeHandler2_Value = Guid.initString("829b6cf1-4f3a-4412-ae09-b243eb4c6b58");
pub const IID_IUIAnimationVariableIntegerChangeHandler2 = &IID_IUIAnimationVariableIntegerChangeHandler2_Value;
pub const IUIAnimationVariableIntegerChangeHandler2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OnIntegerValueChanged: fn(
self: *const IUIAnimationVariableIntegerChangeHandler2,
storyboard: ?*IUIAnimationStoryboard2,
variable: ?*IUIAnimationVariable2,
newValue: [*]i32,
previousValue: [*]i32,
cDimension: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariableIntegerChangeHandler2_OnIntegerValueChanged(self: *const T, storyboard: ?*IUIAnimationStoryboard2, variable: ?*IUIAnimationVariable2, newValue: [*]i32, previousValue: [*]i32, cDimension: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariableIntegerChangeHandler2.VTable, self.vtable).OnIntegerValueChanged(@ptrCast(*const IUIAnimationVariableIntegerChangeHandler2, self), storyboard, variable, newValue, previousValue, cDimension);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IUIAnimationVariableCurveChangeHandler2_Value = Guid.initString("72895e91-0145-4c21-9192-5aab40eddf80");
pub const IID_IUIAnimationVariableCurveChangeHandler2 = &IID_IUIAnimationVariableCurveChangeHandler2_Value;
pub const IUIAnimationVariableCurveChangeHandler2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OnCurveChanged: fn(
self: *const IUIAnimationVariableCurveChangeHandler2,
variable: ?*IUIAnimationVariable2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationVariableCurveChangeHandler2_OnCurveChanged(self: *const T, variable: ?*IUIAnimationVariable2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationVariableCurveChangeHandler2.VTable, self.vtable).OnCurveChanged(@ptrCast(*const IUIAnimationVariableCurveChangeHandler2, self), variable);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IUIAnimationStoryboardEventHandler2_Value = Guid.initString("bac5f55a-ba7c-414c-b599-fbf850f553c6");
pub const IID_IUIAnimationStoryboardEventHandler2 = &IID_IUIAnimationStoryboardEventHandler2_Value;
pub const IUIAnimationStoryboardEventHandler2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OnStoryboardStatusChanged: fn(
self: *const IUIAnimationStoryboardEventHandler2,
storyboard: ?*IUIAnimationStoryboard2,
newStatus: UI_ANIMATION_STORYBOARD_STATUS,
previousStatus: UI_ANIMATION_STORYBOARD_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OnStoryboardUpdated: fn(
self: *const IUIAnimationStoryboardEventHandler2,
storyboard: ?*IUIAnimationStoryboard2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboardEventHandler2_OnStoryboardStatusChanged(self: *const T, storyboard: ?*IUIAnimationStoryboard2, newStatus: UI_ANIMATION_STORYBOARD_STATUS, previousStatus: UI_ANIMATION_STORYBOARD_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboardEventHandler2.VTable, self.vtable).OnStoryboardStatusChanged(@ptrCast(*const IUIAnimationStoryboardEventHandler2, self), storyboard, newStatus, previousStatus);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboardEventHandler2_OnStoryboardUpdated(self: *const T, storyboard: ?*IUIAnimationStoryboard2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboardEventHandler2.VTable, self.vtable).OnStoryboardUpdated(@ptrCast(*const IUIAnimationStoryboardEventHandler2, self), storyboard);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IUIAnimationLoopIterationChangeHandler2_Value = Guid.initString("2d3b15a4-4762-47ab-a030-b23221df3ae0");
pub const IID_IUIAnimationLoopIterationChangeHandler2 = &IID_IUIAnimationLoopIterationChangeHandler2_Value;
pub const IUIAnimationLoopIterationChangeHandler2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OnLoopIterationChanged: fn(
self: *const IUIAnimationLoopIterationChangeHandler2,
storyboard: ?*IUIAnimationStoryboard2,
id: usize,
newIterationCount: u32,
oldIterationCount: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationLoopIterationChangeHandler2_OnLoopIterationChanged(self: *const T, storyboard: ?*IUIAnimationStoryboard2, id: usize, newIterationCount: u32, oldIterationCount: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationLoopIterationChangeHandler2.VTable, self.vtable).OnLoopIterationChanged(@ptrCast(*const IUIAnimationLoopIterationChangeHandler2, self), storyboard, id, newIterationCount, oldIterationCount);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IUIAnimationPriorityComparison2_Value = Guid.initString("5b6d7a37-4621-467c-8b05-70131de62ddb");
pub const IID_IUIAnimationPriorityComparison2 = &IID_IUIAnimationPriorityComparison2_Value;
pub const IUIAnimationPriorityComparison2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
HasPriority: fn(
self: *const IUIAnimationPriorityComparison2,
scheduledStoryboard: ?*IUIAnimationStoryboard2,
newStoryboard: ?*IUIAnimationStoryboard2,
priorityEffect: UI_ANIMATION_PRIORITY_EFFECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationPriorityComparison2_HasPriority(self: *const T, scheduledStoryboard: ?*IUIAnimationStoryboard2, newStoryboard: ?*IUIAnimationStoryboard2, priorityEffect: UI_ANIMATION_PRIORITY_EFFECT) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationPriorityComparison2.VTable, self.vtable).HasPriority(@ptrCast(*const IUIAnimationPriorityComparison2, self), scheduledStoryboard, newStoryboard, priorityEffect);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IUIAnimationTransitionLibrary2_Value = Guid.initString("03cfae53-9580-4ee3-b363-2ece51b4af6a");
pub const IID_IUIAnimationTransitionLibrary2 = &IID_IUIAnimationTransitionLibrary2_Value;
pub const IUIAnimationTransitionLibrary2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CreateInstantaneousTransition: fn(
self: *const IUIAnimationTransitionLibrary2,
finalValue: f64,
transition: ?*?*IUIAnimationTransition2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateInstantaneousVectorTransition: fn(
self: *const IUIAnimationTransitionLibrary2,
finalValue: [*]const f64,
cDimension: u32,
transition: ?*?*IUIAnimationTransition2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateConstantTransition: fn(
self: *const IUIAnimationTransitionLibrary2,
duration: f64,
transition: ?*?*IUIAnimationTransition2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateDiscreteTransition: fn(
self: *const IUIAnimationTransitionLibrary2,
delay: f64,
finalValue: f64,
hold: f64,
transition: ?*?*IUIAnimationTransition2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateDiscreteVectorTransition: fn(
self: *const IUIAnimationTransitionLibrary2,
delay: f64,
finalValue: [*]const f64,
cDimension: u32,
hold: f64,
transition: ?*?*IUIAnimationTransition2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateLinearTransition: fn(
self: *const IUIAnimationTransitionLibrary2,
duration: f64,
finalValue: f64,
transition: ?*?*IUIAnimationTransition2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateLinearVectorTransition: fn(
self: *const IUIAnimationTransitionLibrary2,
duration: f64,
finalValue: [*]const f64,
cDimension: u32,
transition: ?*?*IUIAnimationTransition2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateLinearTransitionFromSpeed: fn(
self: *const IUIAnimationTransitionLibrary2,
speed: f64,
finalValue: f64,
transition: ?*?*IUIAnimationTransition2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateLinearVectorTransitionFromSpeed: fn(
self: *const IUIAnimationTransitionLibrary2,
speed: f64,
finalValue: [*]const f64,
cDimension: u32,
transition: ?*?*IUIAnimationTransition2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateSinusoidalTransitionFromVelocity: fn(
self: *const IUIAnimationTransitionLibrary2,
duration: f64,
period: f64,
transition: ?*?*IUIAnimationTransition2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateSinusoidalTransitionFromRange: fn(
self: *const IUIAnimationTransitionLibrary2,
duration: f64,
minimumValue: f64,
maximumValue: f64,
period: f64,
slope: UI_ANIMATION_SLOPE,
transition: ?*?*IUIAnimationTransition2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateAccelerateDecelerateTransition: fn(
self: *const IUIAnimationTransitionLibrary2,
duration: f64,
finalValue: f64,
accelerationRatio: f64,
decelerationRatio: f64,
transition: ?*?*IUIAnimationTransition2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateReversalTransition: fn(
self: *const IUIAnimationTransitionLibrary2,
duration: f64,
transition: ?*?*IUIAnimationTransition2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateCubicTransition: fn(
self: *const IUIAnimationTransitionLibrary2,
duration: f64,
finalValue: f64,
finalVelocity: f64,
transition: ?*?*IUIAnimationTransition2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateCubicVectorTransition: fn(
self: *const IUIAnimationTransitionLibrary2,
duration: f64,
finalValue: [*]const f64,
finalVelocity: [*]const f64,
cDimension: u32,
transition: ?*?*IUIAnimationTransition2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateSmoothStopTransition: fn(
self: *const IUIAnimationTransitionLibrary2,
maximumDuration: f64,
finalValue: f64,
transition: ?*?*IUIAnimationTransition2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateParabolicTransitionFromAcceleration: fn(
self: *const IUIAnimationTransitionLibrary2,
finalValue: f64,
finalVelocity: f64,
acceleration: f64,
transition: ?*?*IUIAnimationTransition2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateCubicBezierLinearTransition: fn(
self: *const IUIAnimationTransitionLibrary2,
duration: f64,
finalValue: f64,
x1: f64,
y1: f64,
x2: f64,
y2: f64,
ppTransition: ?*?*IUIAnimationTransition2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateCubicBezierLinearVectorTransition: fn(
self: *const IUIAnimationTransitionLibrary2,
duration: f64,
finalValue: [*]const f64,
cDimension: u32,
x1: f64,
y1: f64,
x2: f64,
y2: f64,
ppTransition: ?*?*IUIAnimationTransition2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary2_CreateInstantaneousTransition(self: *const T, finalValue: f64, transition: ?*?*IUIAnimationTransition2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary2.VTable, self.vtable).CreateInstantaneousTransition(@ptrCast(*const IUIAnimationTransitionLibrary2, self), finalValue, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary2_CreateInstantaneousVectorTransition(self: *const T, finalValue: [*]const f64, cDimension: u32, transition: ?*?*IUIAnimationTransition2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary2.VTable, self.vtable).CreateInstantaneousVectorTransition(@ptrCast(*const IUIAnimationTransitionLibrary2, self), finalValue, cDimension, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary2_CreateConstantTransition(self: *const T, duration: f64, transition: ?*?*IUIAnimationTransition2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary2.VTable, self.vtable).CreateConstantTransition(@ptrCast(*const IUIAnimationTransitionLibrary2, self), duration, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary2_CreateDiscreteTransition(self: *const T, delay: f64, finalValue: f64, hold: f64, transition: ?*?*IUIAnimationTransition2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary2.VTable, self.vtable).CreateDiscreteTransition(@ptrCast(*const IUIAnimationTransitionLibrary2, self), delay, finalValue, hold, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary2_CreateDiscreteVectorTransition(self: *const T, delay: f64, finalValue: [*]const f64, cDimension: u32, hold: f64, transition: ?*?*IUIAnimationTransition2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary2.VTable, self.vtable).CreateDiscreteVectorTransition(@ptrCast(*const IUIAnimationTransitionLibrary2, self), delay, finalValue, cDimension, hold, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary2_CreateLinearTransition(self: *const T, duration: f64, finalValue: f64, transition: ?*?*IUIAnimationTransition2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary2.VTable, self.vtable).CreateLinearTransition(@ptrCast(*const IUIAnimationTransitionLibrary2, self), duration, finalValue, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary2_CreateLinearVectorTransition(self: *const T, duration: f64, finalValue: [*]const f64, cDimension: u32, transition: ?*?*IUIAnimationTransition2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary2.VTable, self.vtable).CreateLinearVectorTransition(@ptrCast(*const IUIAnimationTransitionLibrary2, self), duration, finalValue, cDimension, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary2_CreateLinearTransitionFromSpeed(self: *const T, speed: f64, finalValue: f64, transition: ?*?*IUIAnimationTransition2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary2.VTable, self.vtable).CreateLinearTransitionFromSpeed(@ptrCast(*const IUIAnimationTransitionLibrary2, self), speed, finalValue, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary2_CreateLinearVectorTransitionFromSpeed(self: *const T, speed: f64, finalValue: [*]const f64, cDimension: u32, transition: ?*?*IUIAnimationTransition2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary2.VTable, self.vtable).CreateLinearVectorTransitionFromSpeed(@ptrCast(*const IUIAnimationTransitionLibrary2, self), speed, finalValue, cDimension, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary2_CreateSinusoidalTransitionFromVelocity(self: *const T, duration: f64, period: f64, transition: ?*?*IUIAnimationTransition2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary2.VTable, self.vtable).CreateSinusoidalTransitionFromVelocity(@ptrCast(*const IUIAnimationTransitionLibrary2, self), duration, period, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary2_CreateSinusoidalTransitionFromRange(self: *const T, duration: f64, minimumValue: f64, maximumValue: f64, period: f64, slope: UI_ANIMATION_SLOPE, transition: ?*?*IUIAnimationTransition2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary2.VTable, self.vtable).CreateSinusoidalTransitionFromRange(@ptrCast(*const IUIAnimationTransitionLibrary2, self), duration, minimumValue, maximumValue, period, slope, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary2_CreateAccelerateDecelerateTransition(self: *const T, duration: f64, finalValue: f64, accelerationRatio: f64, decelerationRatio: f64, transition: ?*?*IUIAnimationTransition2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary2.VTable, self.vtable).CreateAccelerateDecelerateTransition(@ptrCast(*const IUIAnimationTransitionLibrary2, self), duration, finalValue, accelerationRatio, decelerationRatio, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary2_CreateReversalTransition(self: *const T, duration: f64, transition: ?*?*IUIAnimationTransition2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary2.VTable, self.vtable).CreateReversalTransition(@ptrCast(*const IUIAnimationTransitionLibrary2, self), duration, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary2_CreateCubicTransition(self: *const T, duration: f64, finalValue: f64, finalVelocity: f64, transition: ?*?*IUIAnimationTransition2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary2.VTable, self.vtable).CreateCubicTransition(@ptrCast(*const IUIAnimationTransitionLibrary2, self), duration, finalValue, finalVelocity, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary2_CreateCubicVectorTransition(self: *const T, duration: f64, finalValue: [*]const f64, finalVelocity: [*]const f64, cDimension: u32, transition: ?*?*IUIAnimationTransition2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary2.VTable, self.vtable).CreateCubicVectorTransition(@ptrCast(*const IUIAnimationTransitionLibrary2, self), duration, finalValue, finalVelocity, cDimension, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary2_CreateSmoothStopTransition(self: *const T, maximumDuration: f64, finalValue: f64, transition: ?*?*IUIAnimationTransition2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary2.VTable, self.vtable).CreateSmoothStopTransition(@ptrCast(*const IUIAnimationTransitionLibrary2, self), maximumDuration, finalValue, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary2_CreateParabolicTransitionFromAcceleration(self: *const T, finalValue: f64, finalVelocity: f64, acceleration: f64, transition: ?*?*IUIAnimationTransition2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary2.VTable, self.vtable).CreateParabolicTransitionFromAcceleration(@ptrCast(*const IUIAnimationTransitionLibrary2, self), finalValue, finalVelocity, acceleration, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary2_CreateCubicBezierLinearTransition(self: *const T, duration: f64, finalValue: f64, x1: f64, y1: f64, x2: f64, y2: f64, ppTransition: ?*?*IUIAnimationTransition2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary2.VTable, self.vtable).CreateCubicBezierLinearTransition(@ptrCast(*const IUIAnimationTransitionLibrary2, self), duration, finalValue, x1, y1, x2, y2, ppTransition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionLibrary2_CreateCubicBezierLinearVectorTransition(self: *const T, duration: f64, finalValue: [*]const f64, cDimension: u32, x1: f64, y1: f64, x2: f64, y2: f64, ppTransition: ?*?*IUIAnimationTransition2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionLibrary2.VTable, self.vtable).CreateCubicBezierLinearVectorTransition(@ptrCast(*const IUIAnimationTransitionLibrary2, self), duration, finalValue, cDimension, x1, y1, x2, y2, ppTransition);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IUIAnimationPrimitiveInterpolation_Value = Guid.initString("bab20d63-4361-45da-a24f-ab8508846b5b");
pub const IID_IUIAnimationPrimitiveInterpolation = &IID_IUIAnimationPrimitiveInterpolation_Value;
pub const IUIAnimationPrimitiveInterpolation = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
AddCubic: fn(
self: *const IUIAnimationPrimitiveInterpolation,
dimension: u32,
beginOffset: f64,
constantCoefficient: f32,
linearCoefficient: f32,
quadraticCoefficient: f32,
cubicCoefficient: f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddSinusoidal: fn(
self: *const IUIAnimationPrimitiveInterpolation,
dimension: u32,
beginOffset: f64,
bias: f32,
amplitude: f32,
frequency: f32,
phase: f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationPrimitiveInterpolation_AddCubic(self: *const T, dimension: u32, beginOffset: f64, constantCoefficient: f32, linearCoefficient: f32, quadraticCoefficient: f32, cubicCoefficient: f32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationPrimitiveInterpolation.VTable, self.vtable).AddCubic(@ptrCast(*const IUIAnimationPrimitiveInterpolation, self), dimension, beginOffset, constantCoefficient, linearCoefficient, quadraticCoefficient, cubicCoefficient);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationPrimitiveInterpolation_AddSinusoidal(self: *const T, dimension: u32, beginOffset: f64, bias: f32, amplitude: f32, frequency: f32, phase: f32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationPrimitiveInterpolation.VTable, self.vtable).AddSinusoidal(@ptrCast(*const IUIAnimationPrimitiveInterpolation, self), dimension, beginOffset, bias, amplitude, frequency, phase);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IUIAnimationInterpolator2_Value = Guid.initString("ea76aff8-ea22-4a23-a0ef-a6a966703518");
pub const IID_IUIAnimationInterpolator2 = &IID_IUIAnimationInterpolator2_Value;
pub const IUIAnimationInterpolator2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetDimension: fn(
self: *const IUIAnimationInterpolator2,
dimension: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetInitialValueAndVelocity: fn(
self: *const IUIAnimationInterpolator2,
initialValue: [*]f64,
initialVelocity: [*]f64,
cDimension: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetDuration: fn(
self: *const IUIAnimationInterpolator2,
duration: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDuration: fn(
self: *const IUIAnimationInterpolator2,
duration: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFinalValue: fn(
self: *const IUIAnimationInterpolator2,
value: [*]f64,
cDimension: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
InterpolateValue: fn(
self: *const IUIAnimationInterpolator2,
offset: f64,
value: [*]f64,
cDimension: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
InterpolateVelocity: fn(
self: *const IUIAnimationInterpolator2,
offset: f64,
velocity: [*]f64,
cDimension: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPrimitiveInterpolation: fn(
self: *const IUIAnimationInterpolator2,
interpolation: ?*IUIAnimationPrimitiveInterpolation,
cDimension: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDependencies: fn(
self: *const IUIAnimationInterpolator2,
initialValueDependencies: ?*UI_ANIMATION_DEPENDENCIES,
initialVelocityDependencies: ?*UI_ANIMATION_DEPENDENCIES,
durationDependencies: ?*UI_ANIMATION_DEPENDENCIES,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationInterpolator2_GetDimension(self: *const T, dimension: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationInterpolator2.VTable, self.vtable).GetDimension(@ptrCast(*const IUIAnimationInterpolator2, self), dimension);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationInterpolator2_SetInitialValueAndVelocity(self: *const T, initialValue: [*]f64, initialVelocity: [*]f64, cDimension: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationInterpolator2.VTable, self.vtable).SetInitialValueAndVelocity(@ptrCast(*const IUIAnimationInterpolator2, self), initialValue, initialVelocity, cDimension);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationInterpolator2_SetDuration(self: *const T, duration: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationInterpolator2.VTable, self.vtable).SetDuration(@ptrCast(*const IUIAnimationInterpolator2, self), duration);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationInterpolator2_GetDuration(self: *const T, duration: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationInterpolator2.VTable, self.vtable).GetDuration(@ptrCast(*const IUIAnimationInterpolator2, self), duration);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationInterpolator2_GetFinalValue(self: *const T, value: [*]f64, cDimension: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationInterpolator2.VTable, self.vtable).GetFinalValue(@ptrCast(*const IUIAnimationInterpolator2, self), value, cDimension);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationInterpolator2_InterpolateValue(self: *const T, offset: f64, value: [*]f64, cDimension: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationInterpolator2.VTable, self.vtable).InterpolateValue(@ptrCast(*const IUIAnimationInterpolator2, self), offset, value, cDimension);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationInterpolator2_InterpolateVelocity(self: *const T, offset: f64, velocity: [*]f64, cDimension: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationInterpolator2.VTable, self.vtable).InterpolateVelocity(@ptrCast(*const IUIAnimationInterpolator2, self), offset, velocity, cDimension);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationInterpolator2_GetPrimitiveInterpolation(self: *const T, interpolation: ?*IUIAnimationPrimitiveInterpolation, cDimension: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationInterpolator2.VTable, self.vtable).GetPrimitiveInterpolation(@ptrCast(*const IUIAnimationInterpolator2, self), interpolation, cDimension);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationInterpolator2_GetDependencies(self: *const T, initialValueDependencies: ?*UI_ANIMATION_DEPENDENCIES, initialVelocityDependencies: ?*UI_ANIMATION_DEPENDENCIES, durationDependencies: ?*UI_ANIMATION_DEPENDENCIES) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationInterpolator2.VTable, self.vtable).GetDependencies(@ptrCast(*const IUIAnimationInterpolator2, self), initialValueDependencies, initialVelocityDependencies, durationDependencies);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IUIAnimationTransitionFactory2_Value = Guid.initString("937d4916-c1a6-42d5-88d8-30344d6efe31");
pub const IID_IUIAnimationTransitionFactory2 = &IID_IUIAnimationTransitionFactory2_Value;
pub const IUIAnimationTransitionFactory2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CreateTransition: fn(
self: *const IUIAnimationTransitionFactory2,
interpolator: ?*IUIAnimationInterpolator2,
transition: ?*?*IUIAnimationTransition2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationTransitionFactory2_CreateTransition(self: *const T, interpolator: ?*IUIAnimationInterpolator2, transition: ?*?*IUIAnimationTransition2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationTransitionFactory2.VTable, self.vtable).CreateTransition(@ptrCast(*const IUIAnimationTransitionFactory2, self), interpolator, transition);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IUIAnimationStoryboard2_Value = Guid.initString("ae289cd2-12d4-4945-9419-9e41be034df2");
pub const IID_IUIAnimationStoryboard2 = &IID_IUIAnimationStoryboard2_Value;
pub const IUIAnimationStoryboard2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
AddTransition: fn(
self: *const IUIAnimationStoryboard2,
variable: ?*IUIAnimationVariable2,
transition: ?*IUIAnimationTransition2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddKeyframeAtOffset: fn(
self: *const IUIAnimationStoryboard2,
existingKeyframe: UI_ANIMATION_KEYFRAME,
offset: f64,
keyframe: ?*UI_ANIMATION_KEYFRAME,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddKeyframeAfterTransition: fn(
self: *const IUIAnimationStoryboard2,
transition: ?*IUIAnimationTransition2,
keyframe: ?*UI_ANIMATION_KEYFRAME,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddTransitionAtKeyframe: fn(
self: *const IUIAnimationStoryboard2,
variable: ?*IUIAnimationVariable2,
transition: ?*IUIAnimationTransition2,
startKeyframe: UI_ANIMATION_KEYFRAME,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddTransitionBetweenKeyframes: fn(
self: *const IUIAnimationStoryboard2,
variable: ?*IUIAnimationVariable2,
transition: ?*IUIAnimationTransition2,
startKeyframe: UI_ANIMATION_KEYFRAME,
endKeyframe: UI_ANIMATION_KEYFRAME,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RepeatBetweenKeyframes: fn(
self: *const IUIAnimationStoryboard2,
startKeyframe: UI_ANIMATION_KEYFRAME,
endKeyframe: UI_ANIMATION_KEYFRAME,
cRepetition: f64,
repeatMode: UI_ANIMATION_REPEAT_MODE,
pIterationChangeHandler: ?*IUIAnimationLoopIterationChangeHandler2,
id: usize,
fRegisterForNextAnimationEvent: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HoldVariable: fn(
self: *const IUIAnimationStoryboard2,
variable: ?*IUIAnimationVariable2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetLongestAcceptableDelay: fn(
self: *const IUIAnimationStoryboard2,
delay: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetSkipDuration: fn(
self: *const IUIAnimationStoryboard2,
secondsDuration: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Schedule: fn(
self: *const IUIAnimationStoryboard2,
timeNow: f64,
schedulingResult: ?*UI_ANIMATION_SCHEDULING_RESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Conclude: fn(
self: *const IUIAnimationStoryboard2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Finish: fn(
self: *const IUIAnimationStoryboard2,
completionDeadline: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Abandon: fn(
self: *const IUIAnimationStoryboard2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetTag: fn(
self: *const IUIAnimationStoryboard2,
object: ?*IUnknown,
id: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTag: fn(
self: *const IUIAnimationStoryboard2,
object: ?*?*IUnknown,
id: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStatus: fn(
self: *const IUIAnimationStoryboard2,
status: ?*UI_ANIMATION_STORYBOARD_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetElapsedTime: fn(
self: *const IUIAnimationStoryboard2,
elapsedTime: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetStoryboardEventHandler: fn(
self: *const IUIAnimationStoryboard2,
handler: ?*IUIAnimationStoryboardEventHandler2,
fRegisterStatusChangeForNextAnimationEvent: BOOL,
fRegisterUpdateForNextAnimationEvent: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard2_AddTransition(self: *const T, variable: ?*IUIAnimationVariable2, transition: ?*IUIAnimationTransition2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard2.VTable, self.vtable).AddTransition(@ptrCast(*const IUIAnimationStoryboard2, self), variable, transition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard2_AddKeyframeAtOffset(self: *const T, existingKeyframe: UI_ANIMATION_KEYFRAME, offset: f64, keyframe: ?*UI_ANIMATION_KEYFRAME) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard2.VTable, self.vtable).AddKeyframeAtOffset(@ptrCast(*const IUIAnimationStoryboard2, self), existingKeyframe, offset, keyframe);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard2_AddKeyframeAfterTransition(self: *const T, transition: ?*IUIAnimationTransition2, keyframe: ?*UI_ANIMATION_KEYFRAME) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard2.VTable, self.vtable).AddKeyframeAfterTransition(@ptrCast(*const IUIAnimationStoryboard2, self), transition, keyframe);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard2_AddTransitionAtKeyframe(self: *const T, variable: ?*IUIAnimationVariable2, transition: ?*IUIAnimationTransition2, startKeyframe: UI_ANIMATION_KEYFRAME) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard2.VTable, self.vtable).AddTransitionAtKeyframe(@ptrCast(*const IUIAnimationStoryboard2, self), variable, transition, startKeyframe);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard2_AddTransitionBetweenKeyframes(self: *const T, variable: ?*IUIAnimationVariable2, transition: ?*IUIAnimationTransition2, startKeyframe: UI_ANIMATION_KEYFRAME, endKeyframe: UI_ANIMATION_KEYFRAME) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard2.VTable, self.vtable).AddTransitionBetweenKeyframes(@ptrCast(*const IUIAnimationStoryboard2, self), variable, transition, startKeyframe, endKeyframe);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard2_RepeatBetweenKeyframes(self: *const T, startKeyframe: UI_ANIMATION_KEYFRAME, endKeyframe: UI_ANIMATION_KEYFRAME, cRepetition: f64, repeatMode: UI_ANIMATION_REPEAT_MODE, pIterationChangeHandler: ?*IUIAnimationLoopIterationChangeHandler2, id: usize, fRegisterForNextAnimationEvent: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard2.VTable, self.vtable).RepeatBetweenKeyframes(@ptrCast(*const IUIAnimationStoryboard2, self), startKeyframe, endKeyframe, cRepetition, repeatMode, pIterationChangeHandler, id, fRegisterForNextAnimationEvent);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard2_HoldVariable(self: *const T, variable: ?*IUIAnimationVariable2) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard2.VTable, self.vtable).HoldVariable(@ptrCast(*const IUIAnimationStoryboard2, self), variable);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard2_SetLongestAcceptableDelay(self: *const T, delay: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard2.VTable, self.vtable).SetLongestAcceptableDelay(@ptrCast(*const IUIAnimationStoryboard2, self), delay);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard2_SetSkipDuration(self: *const T, secondsDuration: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard2.VTable, self.vtable).SetSkipDuration(@ptrCast(*const IUIAnimationStoryboard2, self), secondsDuration);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard2_Schedule(self: *const T, timeNow: f64, schedulingResult: ?*UI_ANIMATION_SCHEDULING_RESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard2.VTable, self.vtable).Schedule(@ptrCast(*const IUIAnimationStoryboard2, self), timeNow, schedulingResult);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard2_Conclude(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard2.VTable, self.vtable).Conclude(@ptrCast(*const IUIAnimationStoryboard2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard2_Finish(self: *const T, completionDeadline: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard2.VTable, self.vtable).Finish(@ptrCast(*const IUIAnimationStoryboard2, self), completionDeadline);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard2_Abandon(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard2.VTable, self.vtable).Abandon(@ptrCast(*const IUIAnimationStoryboard2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard2_SetTag(self: *const T, object: ?*IUnknown, id: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard2.VTable, self.vtable).SetTag(@ptrCast(*const IUIAnimationStoryboard2, self), object, id);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard2_GetTag(self: *const T, object: ?*?*IUnknown, id: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard2.VTable, self.vtable).GetTag(@ptrCast(*const IUIAnimationStoryboard2, self), object, id);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard2_GetStatus(self: *const T, status: ?*UI_ANIMATION_STORYBOARD_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard2.VTable, self.vtable).GetStatus(@ptrCast(*const IUIAnimationStoryboard2, self), status);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard2_GetElapsedTime(self: *const T, elapsedTime: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard2.VTable, self.vtable).GetElapsedTime(@ptrCast(*const IUIAnimationStoryboard2, self), elapsedTime);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IUIAnimationStoryboard2_SetStoryboardEventHandler(self: *const T, handler: ?*IUIAnimationStoryboardEventHandler2, fRegisterStatusChangeForNextAnimationEvent: BOOL, fRegisterUpdateForNextAnimationEvent: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IUIAnimationStoryboard2.VTable, self.vtable).SetStoryboardEventHandler(@ptrCast(*const IUIAnimationStoryboard2, self), handler, fRegisterStatusChangeForNextAnimationEvent, fRegisterUpdateForNextAnimationEvent);
}
};}
pub usingnamespace MethodMixin(@This());
};
//--------------------------------------------------------------------------------
// Section: Functions (0)
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (0)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
},
.wide => struct {
},
.unspecified => if (@import("builtin").is_test) struct {
} else struct {
},
};
//--------------------------------------------------------------------------------
// Section: Imports (5)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const BOOL = @import("../foundation.zig").BOOL;
const HRESULT = @import("../foundation.zig").HRESULT;
const IDCompositionAnimation = @import("../graphics/direct_composition.zig").IDCompositionAnimation;
const IUnknown = @import("../system/com.zig").IUnknown;
test {
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
} | win32/ui/animation.zig |
const assert = @import("std").debug.assert;
const cgp_gv: *u64 = &gv;
var gv: u64 = 123;
test "change const cgp_gv, correct compiler error" {
var lv: u64 = 47;
//lcgp_gv = &lv; // compiler correctly generated "error: cannot assign to constant"
}
test "change const clp_lv, correct compiler error" {
var lv: u64 = 456;
const clp_lv: *u64 = &lv;
//clp_lv = &lv; // compiler correctly generated "error: cannot assign to constant"
}
test "Initialize clp_lv after declaration, correct compiler error" {
const clp_lv: *u64 = undefined; // This could be expected to be a compiler error but
// in zig typically ignores many errors if entities
// are not used. So this is probably WAI.
//clp_lv = &gv; // compiler correctly generated "error: cannot assign to constant"
}
test "local variable and const clp_lv initialization" {
var lv: u64 = 456;
const clp_lv: *u64 = &lv;
assert(&lv == clp_lv);
assert(lv == 456);
assert(clp_lv.* == 456);
}
test "local variable mutation and const clp_lv.* should see mutation" {
var lv: u64 = 456;
const clp_lv: *u64 = &lv;
lv = 4567;
assert(&lv == clp_lv);
assert(lv == 4567);
assert(&lv == clp_lv);
assert(clp_lv.* == 4567);
}
test "local variable and const clp_gv initialization" {
const clp_gv: *u64 = &gv;
assert(&gv == clp_gv);
assert(gv == 123);
assert(clp_gv.* == 123);
}
test "test global variable and const ptr alias initialization" {
assert(&gv == cgp_gv);
assert(gv == 123);
assert(cgp_gv.* == 123);
}
test "test global variable mutation" {
gv = 1234;
assert(&gv == cgp_gv);
assert(gv == 1234);
}
test "global const cgp_gv.* mutation should modify gv." {
cgp_gv.* = 12345;
assert(&gv == cgp_gv);
assert(gv == 12345);
}
test "test const cgp_gv.* changed." {
assert(cgp_gv.* == 12345);
gv = 1234;
assert(&gv == cgp_gv);
assert(cgp_gv.* == 1234);
}
test "gv mutation via cgp_gv.*" {
assert(cgp_gv.* == 1234);
cgp_gv.* = 12345;
assert(&gv == cgp_gv);
assert(gv == 12345);
assert(cgp_gv.* == gv);
assert(cgp_gv.* == 12345);
}
test "gv mutation via clp_gv.*" {
const clp_gv: *u64 = &gv;
assert(cgp_gv.* == 12345);
clp_gv.* = 123456;
assert(gv == 123456);
assert(clp_gv.* == gv);
assert(clp_gv.* == 123456);
} | const_ptr.zig |
const std = @import("std");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator;
const HashMap = std.HashMap;
const AutoContext = std.hash_map.AutoContext;
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var global_allocator = gpa.allocator();
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
const args = try get_args();
const size = args[0];
const n = args[1];
const mod = size * 10;
var rng0 = LCG.init(0);
var rng1 = LCG.init(1);
var lru = try LRU(u32, u32).init(size, global_allocator);
defer lru.deinit();
var missed: usize = 0;
var hit: usize = 0;
var i: u32 = 0;
while (i < n) : (i += 1) {
const n0 = rng0.next() % mod;
try lru.put(n0, n0);
const n1 = rng1.next() % mod;
if (lru.get(n1) == null) {
missed += 1;
} else {
hit += 1;
}
}
try stdout.print("{d}\n{d}\n", .{ hit, missed });
}
fn get_args() ![2]u32 {
var arg_it = std.process.args();
_ = arg_it.skip();
var arg = arg_it.next() orelse return [_]u32{ 100, 100 };
const size = try std.fmt.parseInt(u32, arg, 10);
arg = arg_it.next() orelse return [_]u32{ size, 100 };
const n = try std.fmt.parseInt(u32, arg, 10);
return [_]u32{ size, n };
}
const LCG = struct {
seed: u32,
pub fn init(seed: u32) LCG {
return LCG{ .seed = seed };
}
pub fn next(self: *LCG) u32 {
const A: u32 = comptime 1103515245;
const C: u32 = comptime 12345;
const M: u32 = comptime 1 << 31;
self.seed = (A * self.seed + C) % M;
return self.seed;
}
};
fn LinkedList(comptime T: type) type {
return struct {
pub const Node = struct {
prev: ?*Node = null,
next: ?*Node = null,
data: T,
};
allocator: Allocator,
head: ?*Node = null,
tail: ?*Node = null,
len: usize = 0,
const Self = @This();
pub fn init(allocator: Allocator) !*Self {
var list = try allocator.create(Self);
list.allocator = allocator;
return list;
}
pub fn deinit(self: *Self) void {
var ptr = self.head;
while (ptr != null) {
var tmp = ptr.?;
ptr = tmp.next;
self.allocator.destroy(tmp);
}
self.allocator.destroy(self);
}
pub fn add(self: *Self, data: T) !*Node {
var node = try self.allocator.create(Node);
node.data = data;
self.__add_node(node);
self.len += 1;
return node;
}
fn __add_node(self: *Self, node: *Node) void {
if (self.head == null) {
self.head = node;
node.prev = null;
} else if (self.tail != null) {
node.prev = self.tail;
self.tail.?.next = node;
}
self.tail = node;
node.next = null;
}
fn __remove(self: *Self, node: *Node) void {
if (self.head == node) {
self.head = node.next;
}
if (self.tail == node) {
self.tail = node.prev;
}
if (node.prev != null) {
node.prev.?.next = node.next;
}
if (node.next != null) {
node.next.?.prev = node.prev;
}
}
pub fn move_to_end(self: *Self, node: *Node) void {
self.__remove(node);
self.__add_node(node);
}
};
}
fn Pair(comptime K: type, comptime V: type) type {
return struct {
k: K,
v: V,
};
}
fn LRU(
comptime K: type,
comptime V: type,
) type {
const PairType = Pair(K, V);
const ListType = LinkedList(PairType);
const MapType = HashMap(K, *ListType.Node, AutoContext(K), 1.0);
return struct {
allocator: Allocator,
size: u32,
keys: MapType,
entries: *ListType,
const Self = @This();
pub fn init(size: u32, allocator: Allocator) !*Self {
var lru = try allocator.create(Self);
lru.allocator = allocator;
lru.size = size;
lru.keys = MapType.init(allocator);
try lru.keys.ensureTotalCapacity(size);
lru.entries = try ListType.init(allocator);
return lru;
}
pub fn deinit(self: *Self) void {
self.keys.deinit();
self.entries.deinit();
self.allocator.destroy(self);
}
pub fn get(self: *Self, key: K) ?V {
var node = self.keys.get(key);
if (node == null) {
return null;
}
self.entries.move_to_end(node.?);
return node.?.data.v;
}
pub fn put(self: *Self, key: K, value: V) !void {
var node = self.keys.get(key);
if (node != null) {
node.?.data.v = value;
self.entries.move_to_end(node.?);
} else if (self.entries.len == self.size) {
var head = self.entries.head.?;
_ = self.keys.remove(head.data.k);
head.data.k = key;
head.data.v = value;
self.entries.move_to_end(head);
try self.keys.put(key, head);
} else {
try self.keys.put(key, try self.entries.add(.{ .k = key, .v = value }));
}
}
};
} | bench/algorithm/lru/1.zig |
const std = @import("std");
const uart = @import("./uart.zig");
const heap = @import("./heap.zig");
pub const Timer = @import("./rupt/timer.zig");
pub const PLIC = @import("./rupt/plic.zig");
const debug = @import("build_options").log_rupt;
/// Initialize all necessary values. Must be called as early as possible
/// after UART is available.
pub fn init() void {
const k_trap_stack = heap.allocPages(10) catch @panic("Kernel OOM while trying to allocate kernel trap stack in rupt.init()");
kframe.trap_stack = &(k_trap_stack[k_trap_stack.len - 1]);
if (comptime debug)
uart.print("init interrupts...\n", .{});
Timer.init();
PLIC.init();
}
const TrapFrame = extern struct {
regs: [31]usize, // byte 0-247
trap_stack: *u8, // byte 248-255
hartid: usize, // byte 256-263
};
export var kframe linksection(".bss") = TrapFrame{
.regs = [_]usize{0} ** 31,
.trap_stack = undefined,
.hartid = 0,
};
fn asyncInterrupt(comptime n: u63) u64 {
return (1 << 63) + @as(usize, n);
}
fn syncInterrupt(comptime n: u63) u64 {
return (0 << 63) + @as(usize, n);
}
/// This *ought* to be a non-exhaustive enum because the spec allows
/// implementation-defined interrupts, but why would I bother with that.
pub const InterruptCause = enum(u64) {
// Asynchronous Interrupts
user_software = asyncInterrupt(0),
supervisor_software = asyncInterrupt(1),
// asyncInterrupt(2) reserved
machine_software = asyncInterrupt(3),
user_timer = asyncInterrupt(4),
supervisor_timer = asyncInterrupt(5),
// asyncInterrupt(6) reserved
machine_timer = asyncInterrupt(7),
user_external = asyncInterrupt(8),
supervisor_external = asyncInterrupt(9),
// asyncInterrupt(10) reserved
machine_external = asyncInterrupt(11),
// Synchronous Interrupts
instruction_address_misaligned = syncInterrupt(0),
instruction_access_faul = syncInterrupt(1),
illegal_instruction = syncInterrupt(2),
breakpoint = syncInterrupt(3),
load_address_misaligned = syncInterrupt(4),
load_access_fault = syncInterrupt(5),
store_amo_address_misaligned = syncInterrupt(6),
store_amo_access_fault = syncInterrupt(7),
environment_call_from_user = syncInterrupt(8),
environment_call_from_supervisor = syncInterrupt(9),
// syncInterrupt(10) reserved
environment_call_from_machine = syncInterrupt(11),
instruction_page_fault = syncInterrupt(12),
load_page_fault = syncInterrupt(13),
// syncInterrupt(14) reserved
store_amo_page_fault = syncInterrupt(15),
};
/// The interrupt vector that the processor jumps to
export fn rupt() align(4) callconv(.Naked) void {
comptime {
std.debug.assert(@sizeOf(TrapFrame) == 264); // when this fails, adjust the code below!
}
// atomically swap trap frame address into t6
asm volatile ("csrrw t6, mscratch, t6");
// save first 30 general purpose registers that aren't x0 into the trap frame
comptime var save_reg = 1;
inline while (save_reg < 31) : (save_reg += 1) {
@setEvalBranchQuota(11000);
comptime var buf = [_]u8{0} ** 32;
asm volatile (comptime std.fmt.bufPrint(
&buf,
"sd x{}, {}(t6)",
.{ save_reg, (save_reg - 1) * 8 },
) catch unreachable);
}
// save register x31
asm volatile (
\\mv t5, t6
\\sd t6, 30*8(t5)
\\csrw mscratch, t5
);
// clean slate. set up arguments and call the main handler
asm volatile (
\\csrr a0, mcause
\\csrr a1, mepc
\\csrr a2, mtval
\\csrr a3, mscratch
);
asm volatile (
\\ld sp, 248(a3)
\\call zig_rupt
);
// write return program counter from handler and get our trap frame back
asm volatile (
\\csrw mepc, a0
\\csrr t6, mscratch
);
// restore all general purpose registers
comptime var load_reg = 1;
inline while (load_reg < 32) : (load_reg += 1) {
@setEvalBranchQuota(10000);
comptime var buf = [_]u8{0} ** 32;
asm volatile (comptime std.fmt.bufPrint(
&buf,
"ld x{}, {}(t6)",
.{ load_reg, (load_reg - 1) * 8 },
) catch unreachable);
}
asm volatile (
\\mret
);
unreachable;
}
/// The actual interrupt vector above jumps here for high-level processing of the interrupt.
export fn zig_rupt(mcause: usize, epc: usize, tval: usize, frame: *TrapFrame) callconv(.C) usize {
switch (@intToEnum(InterruptCause, mcause)) {
.machine_timer => Timer.handle(),
.machine_external => PLIC.handle(),
else => |cause| unimplemented(cause, epc),
}
return epc;
}
/// Panic, AAAAAAAAAAAAAAAAAAAAAAAAA
pub fn unimplemented(cause: InterruptCause, mepc: usize) void {
var buf = [_]u8{0} ** 128;
@panic(std.fmt.bufPrint(
buf[0..],
"unhandled {} at 0x{x}",
.{ cause, mepc },
) catch unreachable);
} | src/rupt.zig |
const std = @import("std");
const mem = std.mem;
const fs = std.fs;
const Compilation = @import("Compilation.zig");
/// Returns the sub_path that worked, or `null` if none did.
/// The path of the returned Directory is relative to `base`.
/// The handle of the returned Directory is open.
fn testZigInstallPrefix(base_dir: fs.Dir) ?Compilation.Directory {
const test_index_file = "std" ++ fs.path.sep_str ++ "std.zig";
zig_dir: {
// Try lib/zig/std/std.zig
const lib_zig = "lib" ++ fs.path.sep_str ++ "zig";
var test_zig_dir = base_dir.openDir(lib_zig, .{}) catch break :zig_dir;
const file = test_zig_dir.openFile(test_index_file, .{}) catch {
test_zig_dir.close();
break :zig_dir;
};
file.close();
return Compilation.Directory{ .handle = test_zig_dir, .path = lib_zig };
}
// Try lib/std/std.zig
var test_zig_dir = base_dir.openDir("lib", .{}) catch return null;
const file = test_zig_dir.openFile(test_index_file, .{}) catch {
test_zig_dir.close();
return null;
};
file.close();
return Compilation.Directory{ .handle = test_zig_dir, .path = "lib" };
}
/// Both the directory handle and the path are newly allocated resources which the caller now owns.
pub fn findZigLibDir(gpa: *mem.Allocator) !Compilation.Directory {
const self_exe_path = try fs.selfExePathAlloc(gpa);
defer gpa.free(self_exe_path);
return findZigLibDirFromSelfExe(gpa, self_exe_path);
}
/// Both the directory handle and the path are newly allocated resources which the caller now owns.
pub fn findZigLibDirFromSelfExe(
allocator: *mem.Allocator,
self_exe_path: []const u8,
) error{ OutOfMemory, FileNotFound }!Compilation.Directory {
const cwd = fs.cwd();
var cur_path: []const u8 = self_exe_path;
while (fs.path.dirname(cur_path)) |dirname| : (cur_path = dirname) {
var base_dir = cwd.openDir(dirname, .{}) catch continue;
defer base_dir.close();
const sub_directory = testZigInstallPrefix(base_dir) orelse continue;
return Compilation.Directory{
.handle = sub_directory.handle,
.path = try fs.path.join(allocator, &[_][]const u8{ dirname, sub_directory.path.? }),
};
}
return error.FileNotFound;
}
/// Caller owns returned memory.
pub fn resolveGlobalCacheDir(allocator: *mem.Allocator) ![]u8 {
const appname = "zig";
if (std.Target.current.os.tag != .windows) {
if (std.os.getenv("XDG_CACHE_HOME")) |cache_root| {
return fs.path.join(allocator, &[_][]const u8{ cache_root, appname });
} else if (std.os.getenv("HOME")) |home| {
return fs.path.join(allocator, &[_][]const u8{ home, ".cache", appname });
}
}
return fs.getAppDataDir(allocator, appname);
} | src/introspect.zig |
const std = @import("std");
const c = @import("c.zig");
//====================================================================
// Types
//====================================================================
pub const chtype = if (c._LP64 == 1) c_uint else u32;
pub const mmask_t = if (c._LP64 == 1) c_uint else u32;
pub const attr_t = chtype;
pub const wchar_t = c.wchar_t;
pub const cchar_t = extern struct {
attr: attr_t,
chars: [CCHARW_MAX]wchar_t,
};
pub const NcursesError = error{
GenericError,
};
pub const MEVENT = extern struct {
id: c_short,
x: c_int,
y: c_int,
z: c_int,
bstate: mmask_t,
};
//====================================================================
// Constants and functions defined as macros in C
//====================================================================
pub const NCURSES_ATTR_SHIFT: u5 = 8;
pub fn NCURSES_BITS(mask: c_uint, shift: u5) c_uint {
return @intCast(chtype, mask) << (shift + NCURSES_ATTR_SHIFT);
}
pub fn COLOR_PAIR(n: c_int) c_int {
return @intCast(c_int, NCURSES_BITS(@intCast(c_uint, n), 0) & A_COLOR);
}
pub fn PAIR_NUMBER(a: c_int) c_int {
return @intCast(c_int, (@intCast(c_ulong, a) & A_COLOR) >> NCURSES_ATTR_SHIFT);
}
pub fn NCURSES_MOUSE_MASK(b: u5, m: c_uint) mmask_t {
return m << (b - 1) * 5;
}
pub fn KEY_F(n: c_int) c_int {
std.debug.assert(0 <= n and n <= 64);
return KEY_F0 + n;
}
pub fn BUTTON_RELEASE(event_state: c_long, button_number: c_long) c_long {
return event_state & NCURSES_MOUSE_MASK(button_number, NCURSES_BUTTON_RELEASED);
}
pub fn BUTTON_PRESS(event_state: c_long, button_number: c_long) c_long {
return event_state & NCURSES_MOUSE_MASK(button_number, NCURSES_BUTTON_PRESSED);
}
pub fn BUTTON_CLICK(event_state: c_long, button_number: c_long) c_long {
return event_state & NCURSES_MOUSE_MASK(button_number, NCURSES_BUTTON_CLICKED);
}
pub fn BUTTON_DOUBLE_CLICK(event_state: c_long, button_number: c_long) c_long {
return event_state & NCURSES_MOUSE_MASK(button_number, NCURSES_BUTTON_DOUBLE_CLICKED);
}
pub fn BUTTON_TRIPLE_CLICK(event_state: c_long, button_number: c_long) c_long {
return event_state & NCURSES_MOUSE_MASK(button_number, NCURSES_BUTTON_TRIPLE_CLICKED);
}
pub fn BUTTON_RESERVED_EVENT(event_state: c_long, button_number: c_long) c_long {
return event_state & NCURSES_MOUSE_MASK(button_number, NCURSES_BUTTON_RESERVED_EVENT);
}
// zig fmt: off
const Err = -1;
const Ok = 0;
pub const COLOR_BLACK = 0;
pub const COLOR_RED = 1;
pub const COLOR_GREEN = 2;
pub const COLOR_YELLOW = 3;
pub const COLOR_BLUE = 4;
pub const COLOR_MAGENTA = 5;
pub const COLOR_CYAN = 6;
pub const COLOR_WHITE = 7;
// These values are originally from an array `acs_map`. Since we need to define Zig consts at
// compile time, we can't use the generated array. These values are from calling these macros
// in C, libncurses v6.2.
pub const ACS_ULCORNER: chtype = 4194412; // upper left corner
pub const ACS_LLCORNER: chtype = 4194413; // lower left corner
pub const ACS_URCORNER: chtype = 4194411; // upper right corner
pub const ACS_LRCORNER: chtype = 4194410; // lower right corner
pub const ACS_LTEE : chtype = 4194420; // tee pointing right
pub const ACS_RTEE : chtype = 4194421; // tee pointing left
pub const ACS_BTEE : chtype = 4194422; // tee pointing up
pub const ACS_TTEE : chtype = 4194423; // tee pointing down
pub const ACS_HLINE : chtype = 4194417; // horizontal line
pub const ACS_VLINE : chtype = 4194424; // vertical line
pub const ACS_PLUS : chtype = 4194414; // large plus or crossover
pub const ACS_S1 : chtype = 4194415; // scan line 1
pub const ACS_S3 : chtype = 4194416; // scan line 3
pub const ACS_S7 : chtype = 4194418; // scan line 7
pub const ACS_S9 : chtype = 4194419; // scan line 9
pub const ACS_DIAMOND : chtype = 4194400; // diamond
pub const ACS_CKBOARD : chtype = 4194401; // checker board (stipple)
pub const ACS_DEGREE : chtype = 4194406; // degree symbol
pub const ACS_PLMINUS : chtype = 4194407; // plus/minus
pub const ACS_BULLET : chtype = 4194430; // bullet
pub const ACS_LARROW : chtype = 4194348; // arrow pointing left
pub const ACS_RARROW : chtype = 4194347; // arrow pointing right
pub const ACS_DARROW : chtype = 4194350; // arrow pointing down
pub const ACS_UARROW : chtype = 4194349; // arrow pointing up
pub const ACS_BOARD : chtype = 4194408; // board of squares
pub const ACS_LANTERN : chtype = 4194409; // lantern symbol
pub const ACS_BLOCK : chtype = 4194352; // solid square block
pub const ACS_LEQUAL : chtype = 4194425; // less/equal
pub const ACS_GEQUAL : chtype = 4194426; // greater/equal
pub const ACS_PI : chtype = 4194427; // Pi
pub const ACS_NEQUAL : chtype = 4194428; // not equal
pub const ACS_STERLING: chtype = 4194429; // UK pound sign
pub const ACS_BSSB = ACS_ULCORNER;
pub const ACS_SSBB = ACS_LLCORNER;
pub const ACS_BBSS = ACS_URCORNER;
pub const ACS_SBBS = ACS_LRCORNER;
pub const ACS_SBSS = ACS_RTEE;
pub const ACS_SSSB = ACS_LTEE;
pub const ACS_SSBS = ACS_BTEE;
pub const ACS_BSSS = ACS_TTEE;
pub const ACS_BSBS = ACS_HLINE;
pub const ACS_SBSB = ACS_VLINE;
pub const ACS_SSSS = ACS_PLUS;
pub const _SUBWIN = c._SUBWIN; // 0x01 /* is this a sub-window? */
pub const _ENDLINE = c._ENDLINE; // 0x02 /* is the window flush right? */
pub const _FULLWIN = c._FULLWIN; // 0x04 /* is the window full-screen? */
pub const _SCROLLWIN = c._SCROLLWIN; // 0x08 /* bottom edge is at screen bottom? */
pub const _ISPAD = c._ISPAD; // 0x10 /* is this window a pad? */
pub const _HASMOVED = c._HASMOVED; // 0x20 /* has cursor moved since last refresh? */
pub const _WRAPPED = c._WRAPPED; // 0x40 /* cursor was just wrappped */
pub const _NOCHANGE = c._NOCHANGE; // -1
pub const _NEWINDEX = c._NEWINDEX; // -1
pub const A_NORMAL : attr_t = 0;
pub const A_ATTRIBUTES: attr_t = NCURSES_BITS(~@as(c_uint, 0), 0);
pub const A_CHARTEXT : attr_t = NCURSES_BITS(1, 0) - 1;
pub const A_COLOR : attr_t = NCURSES_BITS((@as(c_uint, 1) << 8) - 1, 0);
pub const A_STANDOUT : attr_t = NCURSES_BITS(1, 8);
pub const A_UNDERLINE : attr_t = NCURSES_BITS(1, 9);
pub const A_REVERSE : attr_t = NCURSES_BITS(1, 10);
pub const A_BLINK : attr_t = NCURSES_BITS(1, 11);
pub const A_DIM : attr_t = NCURSES_BITS(1, 12);
pub const A_BOLD : attr_t = NCURSES_BITS(1, 13);
pub const A_ALTCHARSET: attr_t = NCURSES_BITS(1, 14);
pub const A_INVIS : attr_t = NCURSES_BITS(1, 15);
pub const A_PROTECT : attr_t = NCURSES_BITS(1, 16);
pub const A_HORIZONTAL: attr_t = NCURSES_BITS(1, 17);
pub const A_LEFT : attr_t = NCURSES_BITS(1, 18);
pub const A_LOW : attr_t = NCURSES_BITS(1, 19);
pub const A_RIGHT : attr_t = NCURSES_BITS(1, 20);
pub const A_TOP : attr_t = NCURSES_BITS(1, 21);
pub const A_VERTICAL : attr_t = NCURSES_BITS(1, 22);
pub const A_ITALIC : attr_t = NCURSES_BITS(1, 23);
pub const WA_ATTRIBUTES = A_ATTRIBUTES;
pub const WA_NORMAL = A_NORMAL;
pub const WA_STANDOUT = A_STANDOUT;
pub const WA_UNDERLINE = A_UNDERLINE;
pub const WA_REVERSE = A_REVERSE;
pub const WA_BLINK = A_BLINK;
pub const WA_DIM = A_DIM;
pub const WA_BOLD = A_BOLD;
pub const WA_ALTCHARSET = A_ALTCHARSET;
pub const WA_INVIS = A_INVIS;
pub const WA_PROTECT = A_PROTECT;
pub const WA_HORIZONTAL = A_HORIZONTAL;
pub const WA_LEFT = A_LEFT;
pub const WA_LOW = A_LOW;
pub const WA_RIGHT = A_RIGHT;
pub const WA_TOP = A_TOP;
pub const WA_VERTICAL = A_VERTICAL;
pub const KEY_CODE_YES = c.KEY_CODE_YES; // 0400 /* A wchar_t contains a key code */
pub const KEY_MIN = c.KEY_MIN; // 0401 /* Minimum curses key */
pub const KEY_BREAK = c.KEY_BREAK; // 0401 /* Break key (unreliable) */
pub const KEY_SRESET = c.KEY_SRESET; // 0530 /* Soft (partial) reset (unreliable) */
pub const KEY_RESET = c.KEY_RESET; // 0531 /* Reset or hard reset (unreliable) */
pub const KEY_DOWN = c.KEY_DOWN; // 0402 /* down-arrow key */
pub const KEY_UP = c.KEY_UP; // 0403 /* up-arrow key */
pub const KEY_LEFT = c.KEY_LEFT; // 0404 /* left-arrow key */
pub const KEY_RIGHT = c.KEY_RIGHT; // 0405 /* right-arrow key */
pub const KEY_HOME = c.KEY_HOME; // 0406 /* home key */
pub const KEY_BACKSPACE = c.KEY_BACKSPACE; // 0407 /* backspace key */
pub const KEY_F0 = c.KEY_F0; // 0410 /* Function keys. Space for 64 */
pub const KEY_DL = c.KEY_DL; // 0510 /* delete-line key */
pub const KEY_IL = c.KEY_IL; // 0511 /* insert-line key */
pub const KEY_DC = c.KEY_DC; // 0512 /* delete-character key */
pub const KEY_IC = c.KEY_IC; // 0513 /* insert-character key */
pub const KEY_EIC = c.KEY_EIC; // 0514 /* sent by rmir or smir in insert mode */
pub const KEY_CLEAR = c.KEY_CLEAR; // 0515 /* clear-screen or erase key */
pub const KEY_EOS = c.KEY_EOS; // 0516 /* clear-to-end-of-screen key */
pub const KEY_EOL = c.KEY_EOL; // 0517 /* clear-to-end-of-line key */
pub const KEY_SF = c.KEY_SF; // 0520 /* scroll-forward key */
pub const KEY_SR = c.KEY_SR; // 0521 /* scroll-backward key */
pub const KEY_NPAGE = c.KEY_NPAGE; // 0522 /* next-page key */
pub const KEY_PPAGE = c.KEY_PPAGE; // 0523 /* previous-page key */
pub const KEY_STAB = c.KEY_STAB; // 0524 /* set-tab key */
pub const KEY_CTAB = c.KEY_CTAB; // 0525 /* clear-tab key */
pub const KEY_CATAB = c.KEY_CATAB; // 0526 /* clear-all-tabs key */
pub const KEY_ENTER = c.KEY_ENTER; // 0527 /* enter/send key */
pub const KEY_PRINT = c.KEY_PRINT; // 0532 /* print key */
pub const KEY_LL = c.KEY_LL; // 0533 /* lower-left key (home down) */
pub const KEY_A1 = c.KEY_A1; // 0534 /* upper left of keypad */
pub const KEY_A3 = c.KEY_A3; // 0535 /* upper right of keypad */
pub const KEY_B2 = c.KEY_B2; // 0536 /* center of keypad */
pub const KEY_C1 = c.KEY_C1; // 0537 /* lower left of keypad */
pub const KEY_C3 = c.KEY_C3; // 0540 /* lower right of keypad */
pub const KEY_BTAB = c.KEY_BTAB; // 0541 /* back-tab key */
pub const KEY_BEG = c.KEY_BEG; // 0542 /* begin key */
pub const KEY_CANCEL = c.KEY_CANCEL; // 0543 /* cancel key */
pub const KEY_CLOSE = c.KEY_CLOSE; // 0544 /* close key */
pub const KEY_COMMAND = c.KEY_COMMAND; // 0545 /* command key */
pub const KEY_COPY = c.KEY_COPY; // 0546 /* copy key */
pub const KEY_CREATE = c.KEY_CREATE; // 0547 /* create key */
pub const KEY_END = c.KEY_END; // 0550 /* end key */
pub const KEY_EXIT = c.KEY_EXIT; // 0551 /* exit key */
pub const KEY_FIND = c.KEY_FIND; // 0552 /* find key */
pub const KEY_HELP = c.KEY_HELP; // 0553 /* help key */
pub const KEY_MARK = c.KEY_MARK; // 0554 /* mark key */
pub const KEY_MESSAGE = c.KEY_MESSAGE; // 0555 /* message key */
pub const KEY_MOVE = c.KEY_MOVE; // 0556 /* move key */
pub const KEY_NEXT = c.KEY_NEXT; // 0557 /* next key */
pub const KEY_OPEN = c.KEY_OPEN; // 0560 /* open key */
pub const KEY_OPTIONS = c.KEY_OPTIONS; // 0561 /* options key */
pub const KEY_PREVIOUS = c.KEY_PREVIOUS; // 0562 /* previous key */
pub const KEY_REDO = c.KEY_REDO; // 0563 /* redo key */
pub const KEY_REFERENCE = c.KEY_REFERENCE; // 0564 /* reference key */
pub const KEY_REFRESH = c.KEY_REFRESH; // 0565 /* refresh key */
pub const KEY_REPLACE = c.KEY_REPLACE; // 0566 /* replace key */
pub const KEY_RESTART = c.KEY_RESTART; // 0567 /* restart key */
pub const KEY_RESUME = c.KEY_RESUME; // 0570 /* resume key */
pub const KEY_SAVE = c.KEY_SAVE; // 0571 /* save key */
pub const KEY_SBEG = c.KEY_SBEG; // 0572 /* shifted begin key */
pub const KEY_SCANCEL = c.KEY_SCANCEL; // 0573 /* shifted cancel key */
pub const KEY_SCOMMAND = c.KEY_SCOMMAND; // 0574 /* shifted command key */
pub const KEY_SCOPY = c.KEY_SCOPY; // 0575 /* shifted copy key */
pub const KEY_SCREATE = c.KEY_SCREATE; // 0576 /* shifted create key */
pub const KEY_SDC = c.KEY_SDC; // 0577 /* shifted delete-character key */
pub const KEY_SDL = c.KEY_SDL; // 0600 /* shifted delete-line key */
pub const KEY_SELECT = c.KEY_SELECT; // 0601 /* select key */
pub const KEY_SEND = c.KEY_SEND; // 0602 /* shifted end key */
pub const KEY_SEOL = c.KEY_SEOL; // 0603 /* shifted clear-to-end-of-line key */
pub const KEY_SEXIT = c.KEY_SEXIT; // 0604 /* shifted exit key */
pub const KEY_SFIND = c.KEY_SFIND; // 0605 /* shifted find key */
pub const KEY_SHELP = c.KEY_SHELP; // 0606 /* shifted help key */
pub const KEY_SHOME = c.KEY_SHOME; // 0607 /* shifted home key */
pub const KEY_SIC = c.KEY_SIC; // 0610 /* shifted insert-character key */
pub const KEY_SLEFT = c.KEY_SLEFT; // 0611 /* shifted left-arrow key */
pub const KEY_SMESSAGE = c.KEY_SMESSAGE; // 0612 /* shifted message key */
pub const KEY_SMOVE = c.KEY_SMOVE; // 0613 /* shifted move key */
pub const KEY_SNEXT = c.KEY_SNEXT; // 0614 /* shifted next key */
pub const KEY_SOPTIONS = c.KEY_SOPTIONS; // 0615 /* shifted options key */
pub const KEY_SPREVIOUS = c.KEY_SPREVIOUS; // 0616 /* shifted previous key */
pub const KEY_SPRINT = c.KEY_SPRINT; // 0617 /* shifted print key */
pub const KEY_SREDO = c.KEY_SREDO; // 0620 /* shifted redo key */
pub const KEY_SREPLACE = c.KEY_SREPLACE; // 0621 /* shifted replace key */
pub const KEY_SRIGHT = c.KEY_SRIGHT; // 0622 /* shifted right-arrow key */
pub const KEY_SRSUME = c.KEY_SRSUME; // 0623 /* shifted resume key */
pub const KEY_SSAVE = c.KEY_SSAVE; // 0624 /* shifted save key */
pub const KEY_SSUSPEND = c.KEY_SSUSPEND; // 0625 /* shifted suspend key */
pub const KEY_SUNDO = c.KEY_SUNDO; // 0626 /* shifted undo key */
pub const KEY_SUSPEND = c.KEY_SUSPEND; // 0627 /* suspend key */
pub const KEY_UNDO = c.KEY_UNDO; // 0630 /* undo key */
pub const KEY_MOUSE = c.KEY_MOUSE; // 0631 /* Mouse event has occurred */
pub const KEY_RESIZE = c.KEY_RESIZE; // 0632 /* Terminal resize event */
pub const KEY_EVENT = c.KEY_EVENT; // 0633 /* We were interrupted by an event */
pub const KEY_MAX = c.KEY_MAX; // 0777 /* Maximum key value is 0633 */
pub const WACS_BSSB = c.WACS_BSSB; // NCURSES_WACS('l')
pub const WACS_SSBB = c.WACS_SSBB; // NCURSES_WACS('m')
pub const WACS_BBSS = c.WACS_BBSS; // NCURSES_WACS('k')
pub const WACS_SBBS = c.WACS_SBBS; // NCURSES_WACS('j')
pub const WACS_SBSS = c.WACS_SBSS; // NCURSES_WACS('u')
pub const WACS_SSSB = c.WACS_SSSB; // NCURSES_WACS('t')
pub const WACS_SSBS = c.WACS_SSBS; // NCURSES_WACS('v')
pub const WACS_BSSS = c.WACS_BSSS; // NCURSES_WACS('w')
pub const WACS_BSBS = c.WACS_BSBS; // NCURSES_WACS('q')
pub const WACS_SBSB = c.WACS_SBSB; // NCURSES_WACS('x')
pub const WACS_SSSS = c.WACS_SSSS; // NCURSES_WACS('n')
pub const WACS_ULCORNER = c.WACS_ULCORNER; // WACS_BSSB
pub const WACS_LLCORNER = c.WACS_LLCORNER; // WACS_SSBB
pub const WACS_URCORNER = c.WACS_URCORNER; // WACS_BBSS
pub const WACS_LRCORNER = c.WACS_LRCORNER; // WACS_SBBS
pub const WACS_RTEE = c.WACS_RTEE; // WACS_SBSS
pub const WACS_LTEE = c.WACS_LTEE; // WACS_SSSB
pub const WACS_BTEE = c.WACS_BTEE; // WACS_SSBS
pub const WACS_TTEE = c.WACS_TTEE; // WACS_BSSS
pub const WACS_HLINE = c.WACS_HLINE; // WACS_BSBS
pub const WACS_VLINE = c.WACS_VLINE; // WACS_SBSB
pub const WACS_PLUS = c.WACS_PLUS; // WACS_SSSS
pub const WACS_S1 = c.WACS_S1; // NCURSES_WACS('o') /* scan line 1 */
pub const WACS_S9 = c.WACS_S9; // NCURSES_WACS('s') /* scan line 9 */
pub const WACS_DIAMOND = c.WACS_DIAMOND; // NCURSES_WACS('`') /* diamond */
pub const WACS_CKBOARD = c.WACS_CKBOARD; // NCURSES_WACS('a') /* checker board */
pub const WACS_DEGREE = c.WACS_DEGREE; // NCURSES_WACS('f') /* degree symbol */
pub const WACS_PLMINUS = c.WACS_PLMINUS; // NCURSES_WACS('g') /* plus/minus */
pub const WACS_BULLET = c.WACS_BULLET; // NCURSES_WACS('~') /* bullet */
pub const WACS_LARROW = c.WACS_LARROW; // NCURSES_WACS(',') /* arrow left */
pub const WACS_RARROW = c.WACS_RARROW; // NCURSES_WACS('+') /* arrow right */
pub const WACS_DARROW = c.WACS_DARROW; // NCURSES_WACS('.') /* arrow down */
pub const WACS_UARROW = c.WACS_UARROW; // NCURSES_WACS('-') /* arrow up */
pub const WACS_BOARD = c.WACS_BOARD; // NCURSES_WACS('h') /* board of squares */
pub const WACS_LANTERN = c.WACS_LANTERN; // NCURSES_WACS('i') /* lantern symbol */
pub const WACS_BLOCK = c.WACS_BLOCK; // NCURSES_WACS('0') /* solid square block */
pub const WACS_S3 = c.WACS_S3; // NCURSES_WACS('p') /* scan line 3 */
pub const WACS_S7 = c.WACS_S7; // NCURSES_WACS('r') /* scan line 7 */
pub const WACS_LEQUAL = c.WACS_LEQUAL; // NCURSES_WACS('y') /* less/equal */
pub const WACS_GEQUAL = c.WACS_GEQUAL; // NCURSES_WACS('z') /* greater/equal */
pub const WACS_PI = c.WACS_PI; // NCURSES_WACS('{') /* Pi */
pub const WACS_NEQUAL = c.WACS_NEQUAL; // NCURSES_WACS('|') /* not equal */
pub const WACS_STERLING = c.WACS_STERLING; // NCURSES_WACS('}') /* UK pound sign */
pub const WACS_BDDB = c.WACS_BDDB; // NCURSES_WACS('C')
pub const WACS_DDBB = c.WACS_DDBB; // NCURSES_WACS('D')
pub const WACS_BBDD = c.WACS_BBDD; // NCURSES_WACS('B')
pub const WACS_DBBD = c.WACS_DBBD; // NCURSES_WACS('A')
pub const WACS_DBDD = c.WACS_DBDD; // NCURSES_WACS('G')
pub const WACS_DDDB = c.WACS_DDDB; // NCURSES_WACS('F')
pub const WACS_DDBD = c.WACS_DDBD; // NCURSES_WACS('H')
pub const WACS_BDDD = c.WACS_BDDD; // NCURSES_WACS('I')
pub const WACS_BDBD = c.WACS_BDBD; // NCURSES_WACS('R')
pub const WACS_DBDB = c.WACS_DBDB; // NCURSES_WACS('Y')
pub const WACS_DDDD = c.WACS_DDDD; // NCURSES_WACS('E')
pub const WACS_D_ULCORNER = c.WACS_D_ULCORNER; // WACS_BDDB
pub const WACS_D_LLCORNER = c.WACS_D_LLCORNER; // WACS_DDBB
pub const WACS_D_URCORNER = c.WACS_D_URCORNER; // WACS_BBDD
pub const WACS_D_LRCORNER = c.WACS_D_LRCORNER; // WACS_DBBD
pub const WACS_D_RTEE = c.WACS_D_RTEE; // WACS_DBDD
pub const WACS_D_LTEE = c.WACS_D_LTEE; // WACS_DDDB
pub const WACS_D_BTEE = c.WACS_D_BTEE; // WACS_DDBD
pub const WACS_D_TTEE = c.WACS_D_TTEE; // WACS_BDDD
pub const WACS_D_HLINE = c.WACS_D_HLINE; // WACS_BDBD
pub const WACS_D_VLINE = c.WACS_D_VLINE; // WACS_DBDB
pub const WACS_D_PLUS = c.WACS_D_PLUS; // WACS_DDDD
pub const WACS_BTTB = c.WACS_BTTB; // NCURSES_WACS('L')
pub const WACS_TTBB = c.WACS_TTBB; // NCURSES_WACS('M')
pub const WACS_BBTT = c.WACS_BBTT; // NCURSES_WACS('K')
pub const WACS_TBBT = c.WACS_TBBT; // NCURSES_WACS('J')
pub const WACS_TBTT = c.WACS_TBTT; // NCURSES_WACS('U')
pub const WACS_TTTB = c.WACS_TTTB; // NCURSES_WACS('T')
pub const WACS_TTBT = c.WACS_TTBT; // NCURSES_WACS('V')
pub const WACS_BTTT = c.WACS_BTTT; // NCURSES_WACS('W')
pub const WACS_BTBT = c.WACS_BTBT; // NCURSES_WACS('Q')
pub const WACS_TBTB = c.WACS_TBTB; // NCURSES_WACS('X')
pub const WACS_TTTT = c.WACS_TTTT; // NCURSES_WACS('N')
pub const WACS_T_ULCORNER = c.WACS_T_ULCORNER; // WACS_BTTB
pub const WACS_T_LLCORNER = c.WACS_T_LLCORNER; // WACS_TTBB
pub const WACS_T_URCORNER = c.WACS_T_URCORNER; // WACS_BBTT
pub const WACS_T_LRCORNER = c.WACS_T_LRCORNER; // WACS_TBBT
pub const WACS_T_RTEE = c.WACS_T_RTEE; // WACS_TBTT
pub const WACS_T_LTEE = c.WACS_T_LTEE; // WACS_TTTB
pub const WACS_T_BTEE = c.WACS_T_BTEE; // WACS_TTBT
pub const WACS_T_TTEE = c.WACS_T_TTEE; // WACS_BTTT
pub const WACS_T_HLINE = c.WACS_T_HLINE; // WACS_BTBT
pub const WACS_T_VLINE = c.WACS_T_VLINE; // WACS_TBTB
pub const WACS_T_PLUS = c.WACS_T_PLUS; // WACS_TTTT
pub const NCURSES_BUTTON_RELEASED: c_long = 0o1;
pub const NCURSES_BUTTON_PRESSED: c_long = 0o2;
pub const NCURSES_BUTTON_CLICKED: c_long = 0o4;
pub const NCURSES_DOUBLE_CLICKED: c_long = 0o10;
pub const NCURSES_TRIPLE_CLICKED: c_long = 0o20;
pub const NCURSES_RESERVED_EVENT: c_long = 0o40;
pub const BUTTON1_RELEASED : mmask_t = NCURSES_MOUSE_MASK(1, NCURSES_BUTTON_RELEASED);
pub const BUTTON1_PRESSED : mmask_t = NCURSES_MOUSE_MASK(1, NCURSES_BUTTON_PRESSED);
pub const BUTTON1_CLICKED : mmask_t = NCURSES_MOUSE_MASK(1, NCURSES_BUTTON_CLICKED);
pub const BUTTON1_DOUBLE_CLICKED : mmask_t = NCURSES_MOUSE_MASK(1, NCURSES_DOUBLE_CLICKED);
pub const BUTTON1_TRIPLE_CLICKED : mmask_t = NCURSES_MOUSE_MASK(1, NCURSES_TRIPLE_CLICKED);
pub const BUTTON2_RELEASED : mmask_t = NCURSES_MOUSE_MASK(2, NCURSES_BUTTON_RELEASED);
pub const BUTTON2_PRESSED : mmask_t = NCURSES_MOUSE_MASK(2, NCURSES_BUTTON_PRESSED);
pub const BUTTON2_CLICKED : mmask_t = NCURSES_MOUSE_MASK(2, NCURSES_BUTTON_CLICKED);
pub const BUTTON2_DOUBLE_CLICKED : mmask_t = NCURSES_MOUSE_MASK(2, NCURSES_DOUBLE_CLICKED);
pub const BUTTON2_TRIPLE_CLICKED : mmask_t = NCURSES_MOUSE_MASK(2, NCURSES_TRIPLE_CLICKED);
pub const BUTTON3_RELEASED : mmask_t = NCURSES_MOUSE_MASK(3, NCURSES_BUTTON_RELEASED);
pub const BUTTON3_PRESSED : mmask_t = NCURSES_MOUSE_MASK(3, NCURSES_BUTTON_PRESSED);
pub const BUTTON3_CLICKED : mmask_t = NCURSES_MOUSE_MASK(3, NCURSES_BUTTON_CLICKED);
pub const BUTTON3_DOUBLE_CLICKED : mmask_t = NCURSES_MOUSE_MASK(3, NCURSES_DOUBLE_CLICKED);
pub const BUTTON3_TRIPLE_CLICKED : mmask_t = NCURSES_MOUSE_MASK(3, NCURSES_TRIPLE_CLICKED);
pub const BUTTON4_RELEASED : mmask_t = NCURSES_MOUSE_MASK(4, NCURSES_BUTTON_RELEASED);
pub const BUTTON4_PRESSED : mmask_t = NCURSES_MOUSE_MASK(4, NCURSES_BUTTON_PRESSED);
pub const BUTTON4_CLICKED : mmask_t = NCURSES_MOUSE_MASK(4, NCURSES_BUTTON_CLICKED);
pub const BUTTON4_DOUBLE_CLICKED : mmask_t = NCURSES_MOUSE_MASK(4, NCURSES_DOUBLE_CLICKED);
pub const BUTTON4_TRIPLE_CLICKED : mmask_t = NCURSES_MOUSE_MASK(4, NCURSES_TRIPLE_CLICKED);
pub const BUTTON5_RELEASED : mmask_t = NCURSES_MOUSE_MASK(5, NCURSES_BUTTON_RELEASED);
pub const BUTTON5_PRESSED : mmask_t = NCURSES_MOUSE_MASK(5, NCURSES_BUTTON_PRESSED);
pub const BUTTON5_CLICKED : mmask_t = NCURSES_MOUSE_MASK(5, NCURSES_BUTTON_CLICKED);
pub const BUTTON5_DOUBLE_CLICKED : mmask_t = NCURSES_MOUSE_MASK(5, NCURSES_DOUBLE_CLICKED);
pub const BUTTON5_TRIPLE_CLICKED : mmask_t = NCURSES_MOUSE_MASK(5, NCURSES_TRIPLE_CLICKED);
pub const BUTTON_CTRL : mmask_t = NCURSES_MOUSE_MASK(6, 0o1);
pub const BUTTON_SHIFT : mmask_t = NCURSES_MOUSE_MASK(6, 0o2);
pub const BUTTON_ALT : mmask_t = NCURSES_MOUSE_MASK(6, 0o4);
pub const REPORT_MOUSE_POSITION : mmask_t = NCURSES_MOUSE_MASK(6, 0o10);
pub const ALL_MOUSE_EVENTS : mmask_t = REPORT_MOUSE_POSITION - 1;
pub const TRACE_DISABLE = c.TRACE_DISABLE;
pub const TRACE_TIMES = c.TRACE_TIMES;
pub const TRACE_TPUTS = c.TRACE_TPUTS;
pub const TRACE_UPDATE = c.TRACE_UPDATE;
pub const TRACE_MOVE = c.TRACE_MOVE;
pub const TRACE_CHARPUT = c.TRACE_CHARPUT;
pub const TRACE_ORDINARY = c.TRACE_ORDINARY;
pub const TRACE_CALLS = c.TRACE_CALLS;
pub const TRACE_VIRTPUT = c.TRACE_VIRTPUT;
pub const TRACE_IEVENT = c.TRACE_IEVENT;
pub const TRACE_BITS = c.TRACE_BITS;
pub const TRACE_ICALLS = c.TRACE_ICALLS;
pub const TRACE_CCALLS = c.TRACE_CCALLS;
pub const TRACE_DATABASE = c.TRACE_DATABASE;
pub const TRACE_ATTRS = c.TRACE_ATTRS;
pub const TRACE_SHIFT = c.TRACE_SHIFT;
pub const TRACE_MAXIMUM = c.TRACE_MAXIMUM;
pub const OPTIMIZE_MVCUR = c.OPTIMIZE_MVCUR;
pub const OPTIMIZE_HASHMAP = c.OPTIMIZE_HASHMAP;
pub const OPTIMIZE_SCROLL = c.OPTIMIZE_SCROLL;
pub const OPTIMIZE_ALL = c.OPTIMIZE_ALL;
// zig fmt: on
//====================================================================
// Globals
//====================================================================
pub extern "ncurses" var ttytype: [*:0]const u8;
pub extern "ncurses" var COLORS: c_int;
pub extern "ncurses" var COLOR_PAIRS: c_int;
pub extern "ncurses" var COLS: c_int;
pub extern "ncurses" var ESCDELAY: c_int;
pub extern "ncurses" var LINES: c_int;
pub extern "ncurses" var TABSIZE: c_int;
pub var stdscr: Window = undefined;
pub var curscr: Window = undefined;
pub var newscr: Window = undefined;
//====================================================================
// Initialization
//====================================================================
pub fn initscr() !Window {
const pointer = c.initscr();
if (pointer) |ptr| {
stdscr = Window{ .ptr = c.stdscr };
curscr = Window{ .ptr = c.curscr };
newscr = Window{ .ptr = c.newscr };
return Window{ .ptr = ptr };
} else {
return NcursesError.GenericError;
}
}
pub fn endwin() !void {
if (c.endwin() == Err) return NcursesError.GenericError;
}
pub fn newwin(nlines: c_int, ncols: c_int, begin_y: c_int, begin_x: c_int) !Window {
const pointer = c.newwin(nlines, ncols, begin_y, begin_x);
if (pointer) |ptr| {
return Window{ .ptr = ptr };
} else {
return NcursesError.GenericError;
}
}
pub const Window = struct {
ptr: WindowPointer,
const WindowPointer = *c._win_st;
//====================================================================
// Initialization and manipulation
//====================================================================
pub fn delwin(self: Window) !void {
if (c.delwin(self.ptr) == Err) return NcursesError.GenericError;
}
pub fn mvwin(self: Window, y: c_int, x: c_int) !void {
if (c.mvwin(self.ptr, y, x) == Err) return NcursesError.GenericError;
}
pub fn subwin(self: Window, nlines: c_int, ncols: c_int, begin_y: c_int, begin_x: c_int) !Window {
const pointer = c.subwin(self.ptr, nlines, ncols, begin_y, begin_x);
if (pointer) |ptr| {
return Window{ .ptr = ptr };
} else {
return NcursesError.GenericError;
}
}
pub fn derwin(self: Window, nlines: c_int, ncols: c_int, begin_y: c_int, begin_x: c_int) !Window {
const pointer = c.derwin(self.ptr, nlines, ncols, begin_y, begin_x);
if (pointer) |ptr| {
return Window{ .ptr = ptr };
} else {
return NcursesError.GenericError;
}
}
pub fn mvderwin(self: Window, par_y: c_int, par_x: c_int) !void {
if (c.mvderwin(self.ptr, par_y, par_x) == Err) return NcursesError.GenericError;
}
pub fn dupwin(self: Window) !Window {
const pointer = c.dupwin(self.ptr);
if (pointer) |ptr| {
return Window{ .ptr = ptr };
} else {
return NcursesError.GenericError;
}
}
pub fn wsyncup(self: Window) void {
c.wsyncaup(self.ptr);
}
pub fn syncok(self: Window, bf: bool) !void {
if (c.syncok(self.ptr, bf) == Err) return NcursesError.GenericError;
}
pub fn wcursyncup(self: Window) void {
c.wcursyncup(self.ptr);
}
pub fn wsyncdown(self: Window) void {
c.wsyncdown(self.ptr);
}
//====================================================================
// Printing
//====================================================================
// FIXME: casting `format` to `[*:0]const u8` with `format.ptr` doesn't work, the string passed
// in `args` argument must necessarily be a pointer already, probably a bug in Zig. Error:
// error: TODO: support C ABI for more targets. https://github.com/ziglang/zig/issues/1481
pub fn wprintw(self: Window, format: [:0]const u8, args: anytype) !void {
if (@call(.{}, c.wprintw, .{ self.ptr, format.ptr } ++ args) == Err) return NcursesError.GenericError;
}
pub fn mvwprintw(self: Window, y: c_int, x: c_int, format: [:0]const u8, args: anytype) !void {
if (@call(.{}, c.mvwprintw, .{ self.ptr, y, x, format.ptr } ++ args) == Err) return NcursesError.GenericError;
}
pub fn waddch(self: Window, ch: chtype) !void {
if (c.waddch(self.ptr, ch) == Err) return NcursesError.GenericError;
}
pub fn mvwaddch(self: Window, y: c_int, x: c_int, ch: chtype) !void {
if (c.mvwaddch(self.ptr, y, x, ch) == Err) return NcursesError.GenericError;
}
pub fn wechochar(self: Window, ch: chtype) !void {
if (c.wechochar(self.ptr, ch) == Err) return NcursesError.GenericError;
}
pub fn waddstr(self: Window, str: [:0]const u8) !void {
if (c.waddstr(self.ptr, str.ptr) == Err) return NcursesError.GenericError;
}
pub fn waddnstr(self: Window, str: [:0]const u8, n: c_int) !void {
if (c.waddnstr(self.ptr, str.ptr, n) == Err) return NcursesError.GenericError;
}
pub fn mvwaddstr(self: Window, y: c_int, x: c_int, str: [:0]const u8) !void {
if (c.mvwaddstr(self.ptr, y, x, str.ptr) == Err) return NcursesError.GenericError;
}
pub fn mvwaddnstr(self: Window, y: c_int, x: c_int, str: [:0]const u8, n: c_int) !void {
if (c.mvwaddnstr(self.ptr, y, x, str.ptr, n) == Err) return NcursesError.GenericError;
}
//====================================================================
// Printing with Zig (more fun)
//====================================================================
pub const Writer = std.io.Writer(Window, NcursesError, waddstrwrite);
pub fn writer(self: Window) Writer {
return .{ .context = self };
}
fn waddstrwrite(self: Window, str: []const u8) !usize {
if (c.waddnstr(self.ptr, str.ptr, @intCast(c_int, str.len)) == Err) return NcursesError.GenericError;
return str.len;
}
pub fn wprintwzig(self: Window, comptime format: []const u8, args: anytype) !void {
try self.writer().print(format, args);
}
pub fn mvwprintwzig(self: Window, y: c_int, x: c_int, comptime format: []const u8, args: anytype) !void {
try self.wmove(y, x);
try self.writer().print(format, args);
}
pub fn waddstrzig(self: Window, str: []const u8) !void {
try self.writer().writeAll(str);
}
pub fn mvwaddstrzig(self: Window, y: c_int, x: c_int, str: []const u8) !void {
try self.wmove(y, x);
try self.writer().writeAll(str);
}
//====================================================================
// Input
//====================================================================
pub fn wgetch(self: Window) !c_int {
const result = c.wgetch(self.ptr);
if (result == Err) return NcursesError.GenericError;
return result;
}
pub fn mvwgetch(self: Window, y: c_int, x: c_int) !c_int {
const result = c.mvwgetch(self.ptr, y, x);
if (result == Err) return NcursesError.GenericError;
return result;
}
pub fn wscanw(self: Window, comptime format: [:0]const u8, args: anytype) !c_int {
const result = @call(.{}, c.wprintw, .{ self.ptr, format } ++ args);
if (result == Err) {
return NcursesError.GenericError;
} else {
return result;
}
}
pub fn mvwscanw(self: Window, y: c_int, x: c_int, comptime format: [:0]const u8, args: anytype) !c_int {
const result = @call(.{}, c.wprintw, .{ self.ptr, y, x, format } ++ args);
if (result == Err) {
return NcursesError.GenericError;
} else {
return result;
}
}
pub fn wgetstr(self: Window, str: [*:0]u8) !void {
if (c.wgetstr(self.ptr, str) == Err) return NcursesError.GenericError;
}
pub fn wgetnstr(self: Window, str: [*:0]u8, n: c_int) !void {
if (c.wgetstr(self.ptr, str, n) == Err) return NcursesError.GenericError;
}
pub fn mvwgetstr(self: Window, y: c_int, x: c_int, str: [*:0]u8) !void {
if (c.mvwgetstr(self.ptr, y, x, str) == Err) return NcursesError.GenericError;
}
pub fn mvwgetnstr(self: Window, y: c_int, x: c_int, str: [*:0]u8, n: c_int) !void {
if (c.mvwgetnstr(self.ptr, y, x, str, n) == Err) return NcursesError.GenericError;
}
//====================================================================
// Character and window attribute control
//====================================================================
pub fn wattr_get(self: Window, attrs: *attr_t, pair: *c_short, opts: ?*c_void) !void {
if (c.wattr_get(self.ptr, attrs, pair, opts orelse null) == Err) return NcursesError.GenericError;
}
pub fn wattr_set(self: Window, attrs: attr_t, pair: c_short, opts: ?*c_void) !void {
if (c.wattr_set(self.ptr, attrs, pair, opts orelse null) == Err) return NcursesError.GenericError;
}
pub fn wattr_off(self: Window, attrs: attr_t, opts: ?*c_void) !void {
if (c.wattr_off(self.ptr, attrs, opts orelse null) == Err) return NcursesError.GenericError;
}
pub fn wattr_on(self: Window, attrs: attr_t, opts: ?*c_void) !void {
if (c.wattr_on(self.ptr, attrs, opts orelse null) == Err) return NcursesError.GenericError;
}
pub fn wattroff(self: Window, attrs: c_int) !void {
if (c.wattroff(self.ptr, attrs) == Err) return NcursesError.GenericError;
}
pub fn wattron(self: Window, attrs: c_int) !void {
if (c.wattron(self.ptr, attrs) == Err) return NcursesError.GenericError;
}
pub fn wattrset(self: Window, attrs: c_int) !void {
if (c.wattrset(self.ptr, attrs) == Err) return NcursesError.GenericError;
}
pub fn wchgat(self: Window, n: c_int, attr: attr_t, pair: c_short, opts: ?*const c_void) !void {
if (c.wchgat(self.ptr, n, attr, pair, opts orelse null) == Err) return NcursesError.GenericError;
}
pub fn mvwchgat(self: Window, y: c_int, x: c_int, n: c_int, attr: attr_t, pair: c_short, opts: ?*const c_void) !void {
if (c.mvwchgat(self.ptr, y, x, n, attr, pair, opts orelse null) == Err)
return NcursesError.GenericError;
}
pub fn wcolor_set(self: Window, pair: c_short, opts: ?*c_void) !void {
if (c.wcolor_set(self.ptr, pair, opts orelse null) == Err) return NcursesError.GenericError;
}
pub fn wstandend(self: Window) !void {
if (c.wstandend(self.ptr) == Err) return NcursesError.GenericError;
}
pub fn wstandout(self: Window) !void {
if (c.wstandout(self.ptr) == Err) return NcursesError.GenericError;
}
//====================================================================
// Refresh windows and lines
//====================================================================
pub fn wrefresh(self: Window) !void {
if (c.wrefresh(self.ptr) == Err) return NcursesError.GenericError;
}
pub fn wnoutrefresh(self: Window) !void {
if (c.wnoutrefresh(self.ptr) == Err) return NcursesError.GenericError;
}
pub fn redrawwin(self: Window) !void {
if (c.redrawwin(self.ptr) == Err) return NcursesError.GenericError;
}
pub fn wredrawln(self: Window, beg_line: c_int, num_lines: c_int) !void {
if (c.wredrawln(self.ptr, beg_line, num_lines) == Err) return NcursesError.GenericError;
}
//====================================================================
// Coordinates
//====================================================================
pub fn getyx(self: Window, y: *c_int, x: *c_int) !void {
y.* = try getcury(self);
x.* = try getcurx(self);
}
pub inline fn getcury(self: Window) !c_int {
const result = c.getcury(self.ptr);
if (result == Err) {
return NcursesError.GenericError;
} else {
return result;
}
}
pub inline fn getcurx(self: Window) !c_int {
const result = c.getcurx(self.ptr);
if (result == Err) {
return NcursesError.GenericError;
} else {
return result;
}
}
pub fn getbegyx(self: Window, y: *c_int, x: *c_int) !void {
y.* = try getbegy(self);
x.* = try getbegx(self);
}
pub inline fn getbegy(self: Window) !c_int {
const result = c.getbegy(self.ptr);
if (result == Err) {
return NcursesError.GenericError;
} else {
return result;
}
}
pub inline fn getbegx(self: Window) !c_int {
const result = c.getbegx(self.ptr);
if (result == Err) {
return NcursesError.GenericError;
} else {
return result;
}
}
pub fn getmaxyx(self: Window, y: *c_int, x: *c_int) !void {
y.* = try getmaxy(self);
x.* = try getmaxx(self);
}
pub inline fn getmaxy(self: Window) !c_int {
const result = c.getmaxy(self.ptr);
if (result == Err) {
return NcursesError.GenericError;
} else {
return result;
}
}
pub inline fn getmaxx(self: Window) !c_int {
const result = c.getmaxx(self.ptr);
if (result == Err) {
return NcursesError.GenericError;
} else {
return result;
}
}
pub fn getparyx(self: Window, y: *c_int, x: *c_int) !void {
y.* = try getpary(self);
x.* = try getparx(self);
}
pub inline fn getpary(self: Window) !c_int {
const result = c.getpary(self.ptr);
if (result == Err) {
return NcursesError.GenericError;
} else {
return result;
}
}
pub inline fn getparx(self: Window) !c_int {
const result = c.getparx(self.ptr);
if (result == Err) {
return NcursesError.GenericError;
} else {
return result;
}
}
//====================================================================
// Movement
//====================================================================
pub fn wmove(self: Window, y: c_int, x: c_int) !void {
if (c.wmove(self.ptr, y, x) == Err) return NcursesError.GenericError;
}
//====================================================================
// Clearing
//====================================================================
pub fn werase(self: Window) !void {
if (c.werase(self.ptr) == Err) return NcursesError.GenericError;
}
pub fn wclear(self: Window) !void {
if (c.wclear(self.ptr) == Err) return NcursesError.GenericError;
}
pub fn wclrtobot(self: Window) !void {
if (c.wclrtobot(self.ptr) == Err) return NcursesError.GenericError;
}
pub fn wclrtoeol(self: Window) !void {
if (c.wclrtoeol(self.ptr) == Err) return NcursesError.GenericError;
}
//====================================================================
// Borders, lines
//====================================================================
pub fn wborder(self: Window, ls: chtype, rs: chtype, ts: chtype, bs: chtype, tl: chtype, tr: chtype, bl: chtype, br: chtype) !void {
if (c.wborder(self.ptr, ls, rs, ts, bs, tl, tr, bl, br) == Err) return NcursesError.GenericError;
}
pub fn box(self: Window, verch: chtype, horch: chtype) !void {
if (c.box(self.ptr, verch, horch) == Err) return NcursesError.GenericError;
}
pub fn whline(self: Window, ch: chtype, n: c_int) !void {
if (c.whline(self.ptr, ch, n) == Err) return NcursesError.GenericError;
}
pub fn wvline(self: Window, ch: chtype, n: c_int) !void {
if (c.wvline(self.ptr, ch, n) == Err) return NcursesError.GenericError;
}
pub fn mvwhline(self: Window, y: c_int, x: c_int, ch: chtype, n: c_int) !void {
if (c.mvwhline(self.ptr, y, x, ch, n) == Err) return NcursesError.GenericError;
}
pub fn mvwvline(self: Window, y: c_int, x: c_int, ch: chtype, n: c_int) !void {
if (c.mvwvline(self.ptr, y, x, ch, n) == Err) return NcursesError.GenericError;
}
//====================================================================
// Input options
//====================================================================
pub fn intrflush(self: Window, bf: bool) !void {
if (c.intrflush(self.ptr, bf) == Err) return NcursesError.GenericError;
}
pub fn keypad(self: Window, bf: bool) !void {
if (c.keypad(self.ptr, bf) == Err) return NcursesError.GenericError;
}
pub fn meta(self: Window, bf: bool) !void {
if (c.meta(self.ptr, bf) == Err) return NcursesError.GenericError;
}
pub fn nodelay(self: Window, bf: bool) !void {
if (c.nodelay(self.ptr, bf) == Err) return NcursesError.GenericError;
}
pub fn notimeout(self: Window, bf: bool) !void {
if (c.notimeout(self.ptr, bf) == Err) return NcursesError.GenericError;
}
pub fn wtimeout(self: Window, delay: c_int) void {
c.wtimeout(self.ptr, delay);
}
//====================================================================
// Get a character or string
//====================================================================
pub fn winch(self: Window) chtype {
return c.winch(self.ptr);
}
pub fn mvwinch(self: Window, y: c_int, x: c_int) !chtype {
if (c.mvwinch(self.ptr, y, x) == @bitCast(chtype, Err)) return NcursesError.GenericError;
}
pub fn winchstr(self: Window, chstr: [*:0]chtype) !void {
if (c.winchstr(self.ptr, chstr) == Err) return NcursesError.GenericError;
}
pub fn winchnstr(self: Window, chstr: [*:0]chtype, n: c_int) !void {
if (c.winchstr(self.ptr, chstr, n) == Err) return NcursesError.GenericError;
}
pub fn mvwinchstr(self: Window, y: c_int, x: c_int, chstr: [*:0]chtype) !void {
if (c.mvwinchstr(self.ptr, y, x, chstr) == Err) return NcursesError.GenericError;
}
pub fn mvwinchnstr(self: Window, y: c_int, x: c_int, chstr: [*:0]chtype, n: c_int) !void {
if (c.mvwinchnstr(self.ptr, y, x, chstr, n) == Err) return NcursesError.GenericError;
}
//====================================================================
// Mouse
//====================================================================
pub fn wenclose(self: Window, y: c_int, x: c_int) bool {
return c.wenclose(self.ptr, y, x);
}
pub fn wmouse_trafo(self: Window, pY: c_int, pX: c_int, to_screen: bool) bool {
return c.wmouse_trafo(self.ptr, pY, pX, to_screen);
}
//====================================================================
// Utility functions
//====================================================================
pub fn putwin(self: Window, file: c.FILE) !void {
if (c.putwin(self.ptr, file) == Err) return NcursesError.GenericError;
}
//====================================================================
// Overlay
//====================================================================
pub fn overlay(srcwin: Window, dstwin: Window) !void {
if (c.overlay(srcwin.ptr, dstwin.ptr) == Err) return NcursesError.GenericError;
}
pub fn overwrite(srcwin: Window, dstwin: Window) !void {
if (c.overwrite(srcwin.ptr, dstwin.ptr) == Err) return NcursesError.GenericError;
}
pub fn copywin(
srcwin: Window,
dstwin: Window,
sminrow: c_int,
smincol: c_int,
dminrow: c_int,
dmincol: c_int,
dmaxrow: c_int,
dmaxcol: c_int,
overlay: c_int,
) !void {
if (c.copywin(
srcwin.ptr,
dstwin.ptr,
sminrow,
smincol,
dminrow,
dmincol,
dmaxrow,
dmaxcol,
overlay,
) == Err) return NcursesError.GenericError;
}
//====================================================================
// Properties
//====================================================================
pub fn is_cleared(self: Window) bool {
return c.is_cleared(self.ptr);
}
pub fn is_idcok(self: Window) bool {
return c.is_idcok(self.ptr);
}
pub fn is_idlok(self: Window) bool {
return c.is_idlok(self.ptr);
}
pub fn is_immedok(self: Window) bool {
return c.is_immedok(self.ptr);
}
pub fn is_keypad(self: Window) bool {
return c.is_keypad(self.ptr);
}
pub fn is_leaveok(self: Window) bool {
return c.is_leaveok(self.ptr);
}
pub fn is_nodelay(self: Window) bool {
return c.is_nodelay(self.ptr);
}
pub fn is_notimeout(self: Window) bool {
return c.is_notimeout(self.ptr);
}
pub fn is_pad(self: Window) bool {
return c.is_pad(self.ptr);
}
pub fn is_scrollok(self: Window) bool {
return c.is_scrollok(self.ptr);
}
pub fn is_subwin(self: Window) bool {
return c.is_subwin(self.ptr);
}
pub fn is_syncok(self: Window) bool {
return c.is_syncok(self.ptr);
}
pub fn wgetparent(self: Window) ?Window {
if (c.wgetparent(self.ptr)) |winptr| {
return winptr;
} else {
return null;
}
}
pub fn wgetdelay(self: Window) !c_int {
if (c.wgetdelay(self.ptr) == 0) return NcursesError.GenericError;
}
pub fn wgetscrreg(self: Window, top: *c_int, bottom: *c_int) !void {
if (c.wgetscrreg(self.ptr, top, bottom) == Err) return NcursesError.GenericError;
}
};
//====================================================================
// Printing
//====================================================================
pub inline fn printw(comptime format: [:0]const u8, args: anytype) !void {
return try stdscr.wprintw(format, args);
}
pub inline fn mvprintw(y: c_int, x: c_int, comptime format: [:0]const u8, args: anytype) !void {
return try stdscr.mvwprintw(y, x, format, args);
}
pub inline fn addch(ch: chtype) !void {
return try stdscr.waddch(ch);
}
pub inline fn mvaddch(y: c_int, x: c_int, ch: chtype) !void {
return try stdscr.mvwaddch(y, x, ch);
}
pub inline fn echochar(ch: chtype) !void {
return try stdscr.wechochar(ch);
}
pub inline fn addstr(str: [:0]const u8) !void {
return try stdscr.waddstr(str);
}
pub inline fn addnstr(str: [:0]const u8, n: c_int) !void {
return try stdscr.waddnstr(str, n);
}
pub inline fn mvaddstr(y: c_int, x: c_int, str: [:0]const u8) !void {
return try stdscr.mvwaddstr(y, x, str);
}
pub inline fn mvaddnstr(y: c_int, x: c_int, str: [:0]const u8, n: c_int) !void {
return try stdscr.mvwaddnstr(y, x, str, n);
}
//====================================================================
// Printing with Zig (more fun)
//====================================================================
pub inline fn printwzig(comptime format: []const u8, args: anytype) !void {
return try stdscr.wprintwzig(format, args);
}
pub inline fn mvprintwzig(y: c_int, x: c_int, comptime format: []const u8, args: anytype) !void {
return try stdscr.mvwprintwzig(y, x, format, args);
}
pub inline fn addstrzig(str: []const u8) !void {
return try stdscr.waddstrzig(str);
}
pub inline fn mvaddstrzig(y: c_int, x: c_int, str: []const u8) !void {
return try stdscr.mvwaddstrzig(y, x, str);
}
//====================================================================
// Input
//====================================================================
pub inline fn getch() !c_int {
return try stdscr.wgetch();
}
pub inline fn mvgetch(y: c_int, x: c_int) !c_int {
return try stdscr.mvwgetch(y, x);
}
pub fn ungetch(ch: c_int) !void {
if (c.ungetch(ch) == Err) return NcursesError.GenericError;
}
pub fn has_key(ch: c_int) bool {
return c.has_key(ch) == True;
}
pub inline fn scanw(comptime format: [:0]const u8, args: anytype) !c_int {
return try stdscr.wscanw(format, args);
}
pub inline fn mvscanw(y: c_int, x: c_int, comptime format: [:0]const u8, args: anytype) !c_int {
return try stdscr.mvwscanw(y, x, format, args);
}
pub inline fn getstr(str: [*:0]u8) !void {
return try stdscr.wgetstr(str);
}
pub inline fn getnstr(str: [*:0]u8, n: c_int) !void {
return try stdscr.wgetnstr(str, n);
}
pub inline fn mvgetstr(y: c_int, x: c_int, str: [*:0]u8) !void {
return try stdscr.mvwgetstr(y, x, str);
}
pub inline fn mvgetnstr(y: c_int, x: c_int, str: [*:0]u8, n: c_int) !void {
return try stdscr.mvwgetnstr(y, x, str, n);
}
//====================================================================
// Input options
//====================================================================
pub fn cbreak() !void {
if (c.cbreak() == Err) return NcursesError.GenericError;
}
pub fn nocbreak() !void {
if (c.nocbreak() == Err) return NcursesError.GenericError;
}
pub fn echo() !void {
if (c.echo() == Err) return NcursesError.GenericError;
}
pub fn noecho() !void {
if (c.noecho() == Err) return NcursesError.GenericError;
}
pub fn raw() !void {
if (c.raw() == Err) return NcursesError.GenericError;
}
pub fn noraw() !void {
if (c.noraw() == Err) return NcursesError.GenericError;
}
pub fn halfdelay(tenths: c_int) !void {
if (c.halfdelay(tenths) == Err) return NcursesError.GenericError;
}
pub fn qiflush() void {
c.qiflush();
}
pub fn noqiflush() void {
c.noqiflush();
}
pub inline fn timeout(delay: c_int) void {
stdscr.wtimeout(delay);
}
pub fn typeahead(fd: c_int) !void {
if (c.typeahead(fd) == Err) return NcursesError.GenericError;
}
//====================================================================
// Get a character or string
//====================================================================
pub inline fn inch() chtype {
return stdscr.winch();
}
pub inline fn mvinch(y: c_int, x: c_int) !chtype {
return stdscr.mvwinch(y, x);
}
pub inline fn inchstr(chstr: [*:0]chtype) !void {
return stdscr.winchstr(chstr);
}
pub inline fn inchnstr(chstr: [*:0]chtype, n: c_int) !void {
return stdscr.winchstr(chstr, n);
}
pub inline fn mvinchstr(y: c_int, x: c_int, chstr: [*:0]chtype) !void {
return stdscr.mvwinchstr(y, x, chstr);
}
pub inline fn mvinchnstr(y: c_int, x: c_int, chstr: [*:0]chtype, n: c_int) !void {
return stdscr.mvwinchnstr(y, x, chstr, n);
}
//====================================================================
// Character and window attribute control
//====================================================================
pub inline fn attr_get(attrs: *attr_t, pair: *c_short, opts: ?*c_void) !void {
return try stdscr.wattr_get(attrs, pair, opts);
}
pub inline fn attr_set(attrs: attr_t, pair: c_short, opts: ?*c_void) !void {
return try stdscr.wattr_set(attrs, pair, opts);
}
pub inline fn attr_off(attrs: attr_t, opts: ?*c_void) !void {
return try stdscr.wattr_off(attrs, opts);
}
pub inline fn attr_on(attrs: attr_t, opts: ?*c_void) !void {
return try stdscr.wattr_on(attrs, opts);
}
pub inline fn attroff(attrs: c_int) !void {
return try stdscr.wattroff(attrs);
}
pub inline fn attron(attrs: c_int) !void {
return try stdscr.wattron(attrs);
}
pub inline fn attrset(attrs: c_int) !void {
return try stdscr.wattrset(attrs);
}
pub inline fn chgat(n: c_int, attr: attr_t, pair: c_short, opts: ?*const c_void) !void {
return try stdscr.wchgat(n, attr, pair, opts);
}
pub inline fn mvchgat(y: c_int, x: c_int, n: c_int, attr: attr_t, pair: c_short, opts: ?*const c_void) !void {
return try stdscr.mvwchgat(y, x, n, attr, pair, opts);
}
pub inline fn color_set(pair: c_short, opts: ?*c_void) !void {
return stdscr.wcolor_set(pair, opts);
}
pub inline fn standend() !void {
return stdscr.wstandend();
}
pub inline fn standout() !void {
return stdscr.wstandout();
}
//====================================================================
// Refresh windows and lines
//====================================================================
pub inline fn refresh() !void {
return try stdscr.wrefresh();
}
pub fn doupdate() !void {
if (c.doupdate() == Err) return NcursesError.GenericError;
}
//====================================================================
// Movement
//====================================================================
pub inline fn move(y: c_int, x: c_int) !void {
return try stdscr.wmove(y, x);
}
//====================================================================
// Clearing
//====================================================================
pub inline fn erase() !void {
return try stdscr.werase();
}
pub inline fn clear() !void {
return try stdscr.wclear();
}
pub inline fn clrtobot() !void {
return try stdscr.wclrtobot();
}
pub inline fn clrtoeol() !void {
return try stdscr.wclrtoeol();
}
//====================================================================
// Borders, lines
//====================================================================
pub inline fn border(ls: chtype, rs: chtype, ts: chtype, bs: chtype, tl: chtype, tr: chtype, bl: chtype, br: chtype) !void {
return try stdscr.wborder(ls, rs, ts, bs, tl, tr, bl, br);
}
pub inline fn hline(ch: chtype, n: c_int) !void {
return try stdscr.whline(ch, n);
}
pub inline fn vline(ch: chtype, n: c_int) !void {
return try stdscr.wvline(ch, n);
}
pub inline fn mvhline(y: c_int, x: c_int, ch: chtype, n: c_int) !void {
return try stdscr.mvwhline(y, x, ch, n);
}
pub inline fn mvvline(y: c_int, x: c_int, ch: chtype, n: c_int) !void {
return try stdscr.mvwvline(y, x, ch, n);
}
//====================================================================
// Mouse
//====================================================================
pub fn has_mouse() bool {
return c.has_mouse();
}
pub fn getmouse(event: *MEVENT) !void {
if (c.getmouse(@ptrCast(*c.MEVENT, event)) == Err) return NcursesError.GenericError;
}
pub fn ungetmouse(event: *MEVENT) !void {
if (c.ungetmouse(@ptrCast(*c.MEVENT, event)) == Err) return NcursesError.GenericError;
}
pub fn mousemask(newmask: mmask_t, oldmask: ?*mmask_t) mmask_t {
return c.mousemask(newmask, oldmask orelse null);
}
pub inline fn mouse_trafo(pY: *c_int, pX: *c_int, to_screen: bool) bool {
return stdscr.wmouse_trafo(pY, pX, to_screen);
}
// mouseinterval returns the previous interval value, unless the terminal was not initialized.
// Inthat case, it returns the maximum interval value (166).
pub fn mouseinterval(erval: c_int) !c_int {
const result = c.mouseinterval(erval);
if (result == 166) {
return NcursesError.GenericError;
} else {
return result;
}
}
//====================================================================
// Colors
//====================================================================
pub fn start_color() !void {
if (c.start_color() == Err) return NcursesError.GenericError;
}
pub fn has_colors() bool {
return c.has_colors();
}
pub fn can_change_color() bool {
return c.can_change_color();
}
pub fn init_pair(pair: c_short, f: c_short, b: c_short) !void {
if (c.init_pair(pair, f, b) == Err) return NcursesError.GenericError;
}
pub fn init_color(color: c_short, r: c_short, g: c_short, b: c_short) !void {
if (c.init_color(color, r, g, b) == Err) return NcursesError.GenericError;
}
pub fn init_extended_pair(pair: c_int, f: c_int, b: c_int) !void {
if (c.init_pair(pair, f, b) == Err) return NcursesError.GenericError;
}
pub fn init_extended_color(color: c_int, r: c_int, g: c_int, b: c_int) !void {
if (c.init_color(color, r, g, b) == Err) return NcursesError.GenericError;
}
pub fn pair_content(pair: c_short, f: *c_short, b: *c_short) !void {
if (c.color_content(pair, f, b) == Err) return NcursesError.GenericError;
}
pub fn color_content(color: c_short, r: *c_short, g: *c_short, b: *c_short) !void {
if (c.color_content(color, r, g, b) == Err) return NcursesError.GenericError;
}
pub fn extended_pair_content(pair: c_int, f: *c_int, b: *c_int) !void {
if (c.color_content(pair, f, b) == Err) return NcursesError.GenericError;
}
pub fn extended_color_content(color: c_int, r: *c_int, g: *c_int, b: *c_int) !void {
if (c.color_content(color, r, g, b) == Err) return NcursesError.GenericError;
}
pub fn reset_color_pairs() void {
c.reset_color_pairs();
}
pub fn pair_number(attrs: c_int) c_int {
return @intCast(
c_int,
((@intCast(c_ulong, attrs) & @enumToInt(Attribute.color)) >> Attribute.default_shift),
);
}
pub fn color_pair(n: c_int) c_int {
return ncursesBits(n, 0) & @enumToInt(Attribute.color);
}
//====================================================================
// Screen dump/restore
//====================================================================
pub fn scr_dump(filename: [:0]const u8) !void {
if (c.scr_dump(filename.ptr) == Err) return NcursesError.GenericError;
}
pub fn scr_restore(filename: [:0]const u8) !void {
if (c.scr_restore(filename.ptr) == Err) return NcursesError.GenericError;
}
pub fn scr_init(filename: [:0]const u8) !void {
if (c.scr_init(filename.ptr) == Err) return NcursesError.GenericError;
}
pub fn scr_set(filename: [:0]const u8) !void {
if (c.scr_set(filename.ptr) == Err) return NcursesError.GenericError;
}
//====================================================================
// Utility functions
//====================================================================
pub fn unctrl(ch: chtype) ![*:0]const u8 {
if (c.unctrl(ch)) |result| {
return result;
} else {
return NcursesError.GenericError;
}
}
pub fn wunctrl(ch: cchar_t) ![*:0]const wchar_t {
if (c.wunctrl(ch)) |result| {
return result;
} else {
return NcursesError.GenericError;
}
}
pub fn keyname(ch: c_int) ![*:0]const u8 {
if (c.keyname(ch)) |result| {
return result;
} else {
return NcursesError.GenericError;
}
}
pub fn key_name(ch: wchar_t) ![*:0]const u8 {
if (c.keyname(ch)) |result| {
return result;
} else {
return NcursesError.GenericError;
}
}
pub fn filter() void {
c.filter();
}
pub fn nofilter() void {
c.nofilter();
}
pub fn use_env(f: bool) void {
c.use_env(f);
}
pub fn use_tioctl(f: bool) void {
c.use_tioctl(f);
}
pub fn getwin(file: c.FILE) Window {
if (c.getwin(file)) |winptr| {
return Window{ .ptr = winptr };
} else {
return NcursesError.GenericError;
}
}
pub fn delay_output(ms: c_int) !void {
if (c.delay_output(ms) == Err) return NcursesError.GenericError;
}
pub fn flushinp() !void {
if (c.flushinp() == Err) return NcursesError.GenericError;
}
//====================================================================
// Low-level routines
//====================================================================
pub fn def_prog_mode() !void {
if (c.def_prog_mode() == Err) return NcursesError.GenericError;
}
pub fn def_shell_mode() !void {
if (c.def_shell_mode() == Err) return NcursesError.GenericError;
}
pub fn reset_prog_mode() !void {
if (c.reset_prog_mode() == Err) return NcursesError.GenericError;
}
pub fn reset_shell_mode() !void {
if (c.reset_shell_mode() == Err) return NcursesError.GenericError;
}
pub fn resetty() !void {
if (c.resetty() == Err) return NcursesError.GenericError;
}
pub fn savetty() !void {
if (c.savetty() == Err) return NcursesError.GenericError;
}
pub fn getsyx(y: *c_int, x: *c_int) !void {
if (newscr) |winptr| {
if (winptr.is_leaveok()) {
y.* = -1;
x.* = -1;
} else {
try winptr.getyx(y, x);
}
}
}
pub fn setsyx(y: *c_int, x: *c_int) !void {
if (newscr) |winptr| {
if (y == -1 and x == -1) {
winptr.leaveok(true);
} else {
winptr.leaveok(false);
try winptr.wmove(y.*, x.*);
}
}
}
pub fn ripoffline(line: c_int, init: fn (WindowPointer, c_int) callconv(.C) c_int) !void {
if (c.ripoffline(line, init) == Err) return NcursesError.GenericError;
}
pub fn curs_set(visibility: c_int) !void {
if (c.curs_set(visibility) == Err) return NcursesError.GenericError;
}
pub fn napms(ms: c_int) !void {
if (c.napms(ms) == Err) return NcursesError.GenericError;
} | src/ncurses.zig |
const std = @import("std");
const info = std.log.info;
const warn = std.log.warn;
const math = std.math;
const cop0 = @import("cop0.zig");
const FPUCtrlReg = enum(u32) {
FCR31 = 31,
};
pub const Cond = enum(u4) {
F = 0x0,
UN = 0x1,
EQ = 0x2,
UEQ = 0x3,
OLT = 0x4,
ULT = 0x5,
OLE = 0x6,
ULE = 0x7,
SF = 0x8,
NGLE = 0x9,
SEQ = 0xA,
NGL = 0xB,
LT = 0xC,
NGE = 0xD,
LE = 0xE,
NGT = 0xF,
};
pub const Fmt = enum {
S, D, W, L
};
const RoundingMode = enum(u2) {
RoundNearest = 0,
RoundZero = 1,
RoundInfP = 2,
RoundInfN = 3,
};
const FPUFlags = enum(u5) {
I = 0b00001,
U = 0b00010,
O = 0b00100,
Z = 0b01000,
V = 0b10000,
};
const FCR31 = packed struct {
rm : u2 = @enumToInt(RoundingMode.RoundNearest),
flags : u5 = 0,
enables: u5 = 0,
cause : u5 = 0,
causeE : bool = false,
_pad0 : u5 = 0,
c : bool = false,
fs : bool = false,
_pad1 : u7 = 0,
};
var isDisasm = false;
var fprs: [32]u64 = undefined;
var fcr31: FCR31 = FCR31{};
pub var coc1 = false;
fn getFd(instr: u32) u32 {
return (instr >> 6) & 0x1F;
}
fn getFs(instr: u32) u32 {
return (instr >> 11) & 0x1F;
}
fn getFt(instr: u32) u32 {
return (instr >> 16) & 0x1F;
}
pub fn getCtrl32(idx: u32) u32 {
var data: u32 = undefined;
switch (idx) {
@enumToInt(FPUCtrlReg.FCR31) => {
data = @bitCast(u32, fcr31);
},
else => {
warn("[FPU] Read from unhandled FPU Control register {}.", .{idx});
@panic("unhandled FPU Control register");
}
}
info("[FPU] Read {s}.", .{@tagName(@intToEnum(FPUCtrlReg, idx))});
return data;
}
pub fn setCtrl32(idx: u32, data: u32) void {
switch (idx) {
@enumToInt(FPUCtrlReg.FCR31) => {
fcr31 = @bitCast(FCR31, data);
},
else => {
warn("[FPU] Write to unhandled FPU Control register {}, data: {X}h.", .{idx, data});
@panic("unhandled FPU Control register");
}
}
info("[FPU] Write {s}, data: {X}h.", .{@tagName(@intToEnum(FPUCtrlReg, idx)), data});
}
pub fn getFGR32(idx: u32) u32 {
if (cop0.status.fr) {
return @truncate(u32, fprs[idx]);
} else {
if ((idx & 1) != 0) {
return @truncate(u32, fprs[idx & 0x1E] >> 32);
} else {
return @truncate(u32, fprs[idx]);
}
}
}
pub fn getFGR64(idx: u32) u64 {
var idx_ = idx;
if (!cop0.status.fr) {
idx_ &= 0x1E;
}
return fprs[idx_];
}
pub fn setFGR32(idx: u32, data: u32) void {
if (cop0.status.fr) {
fprs[idx] = (fprs[idx] & 0xFFFFFFFF_00000000) | @intCast(u64, data);
} else {
if ((idx & 1) != 0) {
fprs[idx & 0x1E] = (fprs[idx] & 0xFFFFFFFF) | (@intCast(u64, data) << 32);
} else {
fprs[idx] = (fprs[idx] & 0xFFFFFFFF_00000000) | @intCast(u64, data);
}
}
}
pub fn setFGR64(idx: u32, data: u64) void {
var idx_ = idx;
if (!cop0.status.fr) {
idx_ &= 0x1E;
}
fprs[idx_] = data;
}
/// ADD - ADD
pub fn fADD(instr: u32, fmt: comptime Fmt) void {
const fd = getFd(instr);
const fs = getFs(instr);
const ft = getFt(instr);
switch (fmt) {
Fmt.S => setFGR32(fd, @bitCast(u32, @intToFloat(f32, getFGR32(fs)) + @intToFloat(f32, getFGR32(ft)))),
Fmt.D => setFGR64(fd, @bitCast(u64, @intToFloat(f64, getFGR64(fs)) + @intToFloat(f64, getFGR64(ft)))),
else => {
@panic("add: unhandled fmt");
}
}
if (isDisasm) info("[FPU] ADD.{s} ${}, ${}, ${}; ${} = {X}h", .{@tagName(fmt), fd, fs, ft, fd, getFGR64(fd)});
}
/// C - Compare
pub fn fC(instr: u32, cond: u4, fmt: comptime Fmt) void {
const fs = getFs(instr);
const ft = getFt(instr);
var cond_: u4 = 0;
switch (fmt) {
Fmt.S => {
const s = @intToFloat(f32, getFGR32(fs));
const t = @intToFloat(f32, getFGR32(ft));
if (math.isNan(s) or math.isNan(t)) {
if ((cond & 8) != 0) @panic("c.cond: invalid operation");
cond_ = 1;
} else {
if (s < t) cond_ |= 2;
if (s == t) cond_ |= 4;
}
},
Fmt.D => {
const s = @intToFloat(f64, getFGR64(fs));
const t = @intToFloat(f64, getFGR64(ft));
if (math.isNan(s) or math.isNan(t)) {
if ((cond & 8) != 0) @panic("c.cond: invalid operation");
cond_ = 1;
} else {
if (s < t) cond_ |= 2;
if (s == t) cond_ |= 4;
}
},
else => {
@panic("c.cond: unhandled fmt");
}
}
fcr31.c = (cond & cond_) != 0;
coc1 = fcr31.c;
if (isDisasm) info("[FPU] C.{s}.{s} ${}, ${}", .{@tagName(@intToEnum(Cond, cond)), @tagName(fmt), fs, ft});
}
/// CVT.D - ConVerT to Double
pub fn fCVT_D(instr: u32, fmt: comptime Fmt) void {
const fd = getFd(instr);
const fs = getFs(instr);
var data: f64 = undefined;
switch (fmt) {
Fmt.S => data = @floatCast(f64, @bitCast(f32, getFGR32(fs))),
Fmt.W => data = @intToFloat(f64, getFGR32(fs)),
else => {
@panic("cvt.d: unhandled fmt");
}
}
setFGR64(fd, @bitCast(u64, data));
if (isDisasm) info("[FPU] CVT.D.{s} ${}, ${}; ${} = {X}h", .{@tagName(fmt), fd, fs, fd, @bitCast(u64, data)});
}
/// CVT.S - ConVerT to Single
pub fn fCVT_S(instr: u32, fmt: comptime Fmt) void {
const fd = getFd(instr);
const fs = getFs(instr);
var data: f32 = undefined;
switch (fmt) {
Fmt.D => data = @floatCast(f32, @bitCast(f64, getFGR64(fs))),
Fmt.W => data = @intToFloat(f32, getFGR32(fs)),
else => {
@panic("cvt.s: unhandled fmt");
}
}
setFGR32(fd, @bitCast(u32, data));
if (isDisasm) info("[FPU] CVT.S.{s} ${}, ${}; ${} = {X}h", .{@tagName(fmt), fd, fs, fd, @bitCast(u32, data)});
}
/// CVT.W - ConVerT to Word
pub fn fCVT_W(instr: u32, fmt: comptime Fmt) void {
const fd = getFd(instr);
const fs = getFs(instr);
var data: u32 = undefined;
switch (fmt) {
// Fmt.S => data = @truncate(u32, @floatToInt(u64, @floatCast(f64, @bitCast(f32, getFGR32(fs))))),
Fmt.S => data = 0,
Fmt.D => data = @truncate(u32, @floatToInt(u64, @bitCast(f64, getFGR64(fs)))),
else => {
@panic("cvt.w: unhandled fmt");
}
}
setFGR32(fd, data);
if (isDisasm) info("[FPU] CVT.W.{s} ${}, ${}; ${} = {X}h", .{@tagName(fmt), fd, fs, fd, @bitCast(u32, data)});
}
/// DIV - DIVide
pub fn fDIV(instr: u32, fmt: comptime Fmt) void {
const fd = getFd(instr);
const fs = getFs(instr);
const ft = getFt(instr);
switch (fmt) {
Fmt.S => setFGR32(fd, @bitCast(u32, @intToFloat(f32, getFGR32(fs)) / @intToFloat(f32, getFGR32(ft)))),
Fmt.D => setFGR64(fd, @bitCast(u64, @intToFloat(f64, getFGR64(fs)) / @intToFloat(f64, getFGR64(ft)))),
else => {
@panic("div: unhandled fmt");
}
}
if (isDisasm) info("[FPU] DIV.{s} ${}, ${}, ${}; ${} = {X}h", .{@tagName(fmt), fd, fs, ft, fd, getFGR64(fd)});
}
/// MOV - MOVe
pub fn fMOV(instr: u32, fmt: comptime Fmt) void {
const fd = getFd(instr);
const fs = getFs(instr);
var data: f32 = undefined;
switch (fmt) {
Fmt.S => setFGR32(fd, @bitCast(u32, @intToFloat(f32, getFGR32(fs)))),
Fmt.D => setFGR64(fd, @bitCast(u64, @intToFloat(f64, getFGR64(fs)))),
else => {
@panic("mov: unhandled fmt");
}
}
if (isDisasm) info("[FPU] MOV.{s} ${}, ${}; ${} = {X}h", .{@tagName(fmt), fd, fs, fd, @bitCast(u32, data)});
}
/// MUL - MULtiply
pub fn fMUL(instr: u32, fmt: comptime Fmt) void {
const fd = getFd(instr);
const fs = getFs(instr);
const ft = getFt(instr);
switch (fmt) {
Fmt.S => setFGR32(fd, @bitCast(u32, @intToFloat(f32, getFGR32(fs)) * @intToFloat(f32, getFGR32(ft)))),
Fmt.D => setFGR64(fd, @bitCast(u64, @intToFloat(f64, getFGR64(fs)) * @intToFloat(f64, getFGR64(ft)))),
else => {
@panic("mul: unhandled fmt");
}
}
if (isDisasm) info("[FPU] MUL.{s} ${}, ${}, ${}; ${} = {X}h", .{@tagName(fmt), fd, fs, ft, fd, getFGR64(fd)});
}
/// NEG - NEGate
pub fn fNEG(instr: u32, fmt: comptime Fmt) void {
const fd = getFd(instr);
const fs = getFs(instr);
var data: f32 = undefined;
switch (fmt) {
Fmt.S => setFGR32(fd, @bitCast(u32, -@intToFloat(f32, getFGR32(fs)))),
else => {
@panic("neg: unhandled fmt");
}
}
if (isDisasm) info("[FPU] NEG.{s} ${}, ${}; ${} = {X}h", .{@tagName(fmt), fd, fs, fd, @bitCast(u32, data)});
}
/// SQRT - SQuare RooT
pub fn fSQRT(instr: u32, fmt: comptime Fmt) void {
const fd = getFd(instr);
const fs = getFs(instr);
var data: f32 = undefined;
switch (fmt) {
Fmt.S => setFGR32(fd, @bitCast(u32, @sqrt(@intToFloat(f32, getFGR32(fs))))),
else => {
@panic("mov unhandled fmt");
}
}
if (isDisasm) info("[FPU] MOV.{s} ${}, ${}; ${} = {X}h", .{@tagName(fmt), fd, fs, fd, @bitCast(u32, data)});
}
/// SUB - SUB
pub fn fSUB(instr: u32, fmt: comptime Fmt) void {
const fd = getFd(instr);
const fs = getFs(instr);
const ft = getFt(instr);
switch (fmt) {
Fmt.S => setFGR32(fd, @bitCast(u32, @intToFloat(f32, getFGR32(fs)) - @intToFloat(f32, getFGR32(ft)))),
Fmt.D => setFGR64(fd, @bitCast(u64, @intToFloat(f64, getFGR64(fs)) - @intToFloat(f64, getFGR64(ft)))),
else => {
@panic("add: unhandled fmt");
}
}
if (isDisasm) info("[FPU] SUB.{s} ${}, ${}, ${}; ${} = {X}h", .{@tagName(fmt), fd, fs, ft, fd, getFGR64(fd)});
}
/// TRUNC.W - TRUNCate to Word
pub fn fTRUNC_W(instr: u32, fmt: comptime Fmt) void {
const fd = getFd(instr);
const fs = getFs(instr);
var data: u32 = undefined;
switch (fmt) {
Fmt.S => data = @bitCast(u32, @trunc(@bitCast(f32, getFGR32(fs)))),
Fmt.D => data = @truncate(u32, @floatToInt(u64, @trunc(@bitCast(f64, getFGR64(fs))))),
else => {
@panic("trunc.w: unhandled fmt");
}
}
setFGR32(fd, data);
if (isDisasm) info("[FPU] TRUNC.W.{s} ${}, ${}; ${} = {X}h", .{@tagName(fmt), fd, fs, fd, @bitCast(u32, data)});
} | src/core/cop1.zig |
const std = @import("../std.zig");
const assert = std.debug.assert;
const utf8Decode = std.unicode.utf8Decode;
const utf8Encode = std.unicode.utf8Encode;
pub const ParseError = error{
OutOfMemory,
InvalidLiteral,
};
pub const ParsedCharLiteral = union(enum) {
success: u21,
failure: Error,
};
pub const Result = union(enum) {
success,
failure: Error,
};
pub const Error = union(enum) {
/// The character after backslash is missing or not recognized.
invalid_escape_character: usize,
/// Expected hex digit at this index.
expected_hex_digit: usize,
/// Unicode escape sequence had no digits with rbrace at this index.
empty_unicode_escape_sequence: usize,
/// Expected hex digit or '}' at this index.
expected_hex_digit_or_rbrace: usize,
/// Invalid unicode codepoint at this index.
invalid_unicode_codepoint: usize,
/// Expected '{' at this index.
expected_lbrace: usize,
/// Expected '}' at this index.
expected_rbrace: usize,
/// Expected '\'' at this index.
expected_single_quote: usize,
/// The character at this index cannot be represented without an escape sequence.
invalid_character: usize,
};
/// Only validates escape sequence characters.
/// Slice must be valid utf8 starting and ending with "'" and exactly one codepoint in between.
pub fn parseCharLiteral(slice: []const u8) ParsedCharLiteral {
assert(slice.len >= 3 and slice[0] == '\'' and slice[slice.len - 1] == '\'');
switch (slice[1]) {
'\\' => {
var offset: usize = 1;
const result = parseEscapeSequence(slice, &offset);
if (result == .success and (offset + 1 != slice.len or slice[offset] != '\''))
return .{ .failure = .{ .expected_single_quote = offset } };
return result;
},
0 => return .{ .failure = .{ .invalid_character = 1 } },
else => {
const codepoint = utf8Decode(slice[1 .. slice.len - 1]) catch unreachable;
return .{ .success = codepoint };
},
}
}
/// Parse an escape sequence from `slice[offset..]`. If parsing is successful,
/// offset is updated to reflect the characters consumed.
fn parseEscapeSequence(slice: []const u8, offset: *usize) ParsedCharLiteral {
assert(slice.len > offset.*);
assert(slice[offset.*] == '\\');
if (slice.len == offset.* + 1)
return .{ .failure = .{ .invalid_escape_character = offset.* + 1 } };
offset.* += 2;
switch (slice[offset.* - 1]) {
'n' => return .{ .success = '\n' },
'r' => return .{ .success = '\r' },
'\\' => return .{ .success = '\\' },
't' => return .{ .success = '\t' },
'\'' => return .{ .success = '\'' },
'"' => return .{ .success = '"' },
'x' => {
var value: u8 = 0;
var i: usize = offset.*;
while (i < offset.* + 2) : (i += 1) {
if (i == slice.len) return .{ .failure = .{ .expected_hex_digit = i } };
const c = slice[i];
switch (c) {
'0'...'9' => {
value *= 16;
value += c - '0';
},
'a'...'f' => {
value *= 16;
value += c - 'a' + 10;
},
'A'...'F' => {
value *= 16;
value += c - 'A' + 10;
},
else => {
return .{ .failure = .{ .expected_hex_digit = i } };
},
}
}
offset.* = i;
return .{ .success = value };
},
'u' => {
var i: usize = offset.*;
if (i >= slice.len or slice[i] != '{') return .{ .failure = .{ .expected_lbrace = i } };
i += 1;
if (i >= slice.len) return .{ .failure = .{ .expected_hex_digit_or_rbrace = i } };
if (slice[i] == '}') return .{ .failure = .{ .empty_unicode_escape_sequence = i } };
var value: u32 = 0;
while (i < slice.len) : (i += 1) {
const c = slice[i];
switch (c) {
'0'...'9' => {
value *= 16;
value += c - '0';
},
'a'...'f' => {
value *= 16;
value += c - 'a' + 10;
},
'A'...'F' => {
value *= 16;
value += c - 'A' + 10;
},
'}' => {
i += 1;
break;
},
else => return .{ .failure = .{ .expected_hex_digit_or_rbrace = i } },
}
if (value > 0x10ffff) {
return .{ .failure = .{ .invalid_unicode_codepoint = i } };
}
} else {
return .{ .failure = .{ .expected_rbrace = i } };
}
offset.* = i;
return .{ .success = @intCast(u21, value) };
},
else => return .{ .failure = .{ .invalid_escape_character = offset.* - 1 } },
}
}
test "parseCharLiteral" {
try std.testing.expectEqual(
ParsedCharLiteral{ .success = 'a' },
parseCharLiteral("'a'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .success = 'ä' },
parseCharLiteral("'ä'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .success = 0 },
parseCharLiteral("'\\x00'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .success = 0x4f },
parseCharLiteral("'\\x4f'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .success = 0x4f },
parseCharLiteral("'\\x4F'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .success = 0x3041 },
parseCharLiteral("'ぁ'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .success = 0 },
parseCharLiteral("'\\u{0}'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .success = 0x3041 },
parseCharLiteral("'\\u{3041}'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .success = 0x7f },
parseCharLiteral("'\\u{7f}'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .success = 0x7fff },
parseCharLiteral("'\\u{7FFF}'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .failure = .{ .expected_hex_digit = 4 } },
parseCharLiteral("'\\x0'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .failure = .{ .expected_single_quote = 5 } },
parseCharLiteral("'\\x000'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .failure = .{ .invalid_escape_character = 2 } },
parseCharLiteral("'\\y'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .failure = .{ .expected_lbrace = 3 } },
parseCharLiteral("'\\u'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .failure = .{ .expected_lbrace = 3 } },
parseCharLiteral("'\\uFFFF'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .failure = .{ .empty_unicode_escape_sequence = 4 } },
parseCharLiteral("'\\u{}'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .failure = .{ .invalid_unicode_codepoint = 9 } },
parseCharLiteral("'\\u{FFFFFF}'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .failure = .{ .expected_hex_digit_or_rbrace = 8 } },
parseCharLiteral("'\\u{FFFF'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .failure = .{ .expected_single_quote = 9 } },
parseCharLiteral("'\\u{FFFF}x'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .failure = .{ .invalid_character = 1 } },
parseCharLiteral("'\x00'"),
);
}
/// Parses `bytes` as a Zig string literal and appends the result to `buf`.
/// Asserts `bytes` has '"' at beginning and end.
pub fn parseAppend(buf: *std.ArrayList(u8), bytes: []const u8) error{OutOfMemory}!Result {
assert(bytes.len >= 2 and bytes[0] == '"' and bytes[bytes.len - 1] == '"');
try buf.ensureUnusedCapacity(bytes.len - 2);
var index: usize = 1;
while (true) {
const b = bytes[index];
switch (b) {
'\\' => {
const escape_char_index = index + 1;
const result = parseEscapeSequence(bytes, &index);
switch (result) {
.success => |codepoint| {
if (bytes[escape_char_index] == 'u') {
buf.items.len += utf8Encode(codepoint, buf.unusedCapacitySlice()) catch {
return Result{ .failure = .{ .invalid_unicode_codepoint = escape_char_index + 1 } };
};
} else {
buf.appendAssumeCapacity(@intCast(u8, codepoint));
}
},
.failure => |err| return Result{ .failure = err },
}
},
'\n' => return Result{ .failure = .{ .invalid_character = index } },
'"' => return Result.success,
else => {
try buf.append(b);
index += 1;
},
}
} else unreachable; // TODO should not need else unreachable on while(true)
}
/// Higher level API. Does not return extra info about parse errors.
/// Caller owns returned memory.
pub fn parseAlloc(allocator: std.mem.Allocator, bytes: []const u8) ParseError![]u8 {
var buf = std.ArrayList(u8).init(allocator);
defer buf.deinit();
switch (try parseAppend(&buf, bytes)) {
.success => return buf.toOwnedSlice(),
.failure => return error.InvalidLiteral,
}
}
test "parse" {
const expect = std.testing.expect;
const expectError = std.testing.expectError;
const eql = std.mem.eql;
var fixed_buf_mem: [64]u8 = undefined;
var fixed_buf_alloc = std.heap.FixedBufferAllocator.init(&fixed_buf_mem);
var alloc = fixed_buf_alloc.allocator();
try expectError(error.InvalidLiteral, parseAlloc(alloc, "\"\\x6\""));
try expect(eql(u8, "foo\nbar", try parseAlloc(alloc, "\"foo\\nbar\"")));
try expect(eql(u8, "\x12foo", try parseAlloc(alloc, "\"\\x12foo\"")));
try expect(eql(u8, "bytes\u{1234}foo", try parseAlloc(alloc, "\"bytes\\u{1234}foo\"")));
try expect(eql(u8, "foo", try parseAlloc(alloc, "\"foo\"")));
try expect(eql(u8, "foo", try parseAlloc(alloc, "\"f\x6f\x6f\"")));
try expect(eql(u8, "f💯", try parseAlloc(alloc, "\"f\u{1f4af}\"")));
} | lib/std/zig/string_literal.zig |
const std = @import("std");
const interop = @import("interop.zig");
const iup = @import("iup.zig");
const CallbackHandler = @import("callback_handler.zig").CallbackHandler;
///
/// Global handler for unhandled errors thrown inside callback functions
pub const ErrorHandlerFn = fn (?Element, anyerror) anyerror!void;
///
/// Global handler for IDLE
/// Predefined IUP action, generated when there are no events or messages to be processed.
/// Often used to perform background operations.
pub const IdleHandlerFn = fn () anyerror!void;
const MainLoop = @This();
const Element = iup.Element;
var exit_error: ?anyerror = null;
var error_handler: ?ErrorHandlerFn = null;
///
/// Initializes the IUP toolkit. Must be called before any other IUP function.
pub fn open() iup.Error!void {
try interop.open();
}
///
/// Sets a callback function to handle errors returned inside the main loop
/// Rethrow the error to terminate the application
pub fn setErrorHandler(value: ?ErrorHandlerFn) void {
MainLoop.error_handler = value;
}
///
/// Terminates the current message loop. It has the same effect of a callback returning IUP_CLOSE.
pub fn exitLoop() void {
interop.exitLoop();
}
///
/// Global handler for IDLE
/// Predefined IUP action, generated when there are no events or messages to be processed.
/// Often used to perform background operations.
pub fn setIdleCallback(value: ?IdleHandlerFn) void {
const Handler = CallbackHandler(void, IdleHandlerFn, "IDLE_ACTION");
Handler.setGlobalCallback(value);
}
///
/// Called by the message loop
pub fn onError(element: ?Element, err: anyerror) i32 {
if (MainLoop.error_handler) |func| {
if (func(element, err)) {
return interop.consts.IUP_DEFAULT;
} else |rethrown| {
MainLoop.exit_error = rethrown;
}
}
return interop.consts.IUP_CLOSE;
}
///
/// Executes the user interaction until a callback returns IUP_CLOSE,
/// IupExitLoop is called, or hiding the last visible dialog.
/// When this function is called, it will interrupt the program execution until a callback returns IUP_CLOSE,
/// IupExitLoop is called, or there are no visible dialogs.
/// If you cascade many calls to IupMainLoop there must be a "return IUP_CLOSE" or
/// IupExitLoop call for each cascade level, hiddinh all dialogs will close only one level.
/// Call IupMainLoopLevel to obtain the current level.
/// If IupMainLoop is called without any visible dialogs and no active timers,
/// the application will hang and will not be possible to close the main loop.
/// The process will have to be interrupted by the system.
/// When the last visible dialog is hidden the IupExitLoop function is automatically called,
/// causing the IupMainLoop to return. To avoid that set LOCKLOOP=YES before hiding the last dialog.
pub fn beginLoop() !void {
interop.beginLoop();
if (exit_error) |err| return err;
}
///
/// Returns a string with the IUP version number.
pub fn showVersion() void {
interop.showVersion();
}
///
/// Ends the IUP toolkit and releases internal memory.
/// It will also automatically destroy all dialogs and all elements that have names.
pub fn close() void {
interop.close();
} | src/MainLoop.zig |
const std = @import("std");
const Component = @import("../Component.zig");
const Input = @import("../Input.zig");
// Identifies common character states.
pub const CombatStateID = enum(u32)
{
Standing,
Crouching,
WalkingForward,
WalkingBackwards,
Jump,
_
};
// A context is passed into the combat state callbacks.
pub const CombatStateContext = struct
{
bTransition: bool = false, // indicates that a state transition has been triggered
NextState: CombatStateID = CombatStateID.Standing, // indicates the next state to transition to.
InputCommand: Input.InputCommand = .{},
PhysicsComponent: ?*Component.PhysicsComponent = null
};
// Provides an interface for combat states to respond to various events
pub const CombatStateCallbacks = struct
{
OnStart: ?fn(context: *CombatStateContext) void = null, // Called when starting an action
OnUpdate: ?fn(context: *CombatStateContext) void = null, // Called every frame
OnEnd: ?fn(context: *CombatStateContext) void = null // Called when finishing an action
};
// Stores the combat states used for a character.
pub const CombatStateRegistery = struct
{
const MAX_STATES = 256;
CombatStates: [MAX_STATES]?*CombatStateCallbacks = [_]?*CombatStateCallbacks{null} ** MAX_STATES,
pub fn RegisterCommonState(self: *CombatStateRegistery, StateID: CombatStateID, StateCallbacks:*CombatStateCallbacks) void
{
// TODO: assert(StateID <= LastCommonStateID). Whatever the zig way of doing this is...
// condition might be ''' StateID < std.meta.fields(CombatStateID).len '''
self.CombatStates[@enumToInt(StateID)] = StateCallbacks;
}
};
// Runs and keeps track of a state machine
pub const CombatStateMachineProcessor = struct
{
Registery: CombatStateRegistery = .{},
CurrentState: CombatStateID = CombatStateID.Standing,
Context: ?*CombatStateContext = null,
pub fn UpdateStateMachine(self: *CombatStateMachineProcessor) void
{
if(self.Context) | context |
{
if(self.Registery.CombatStates[@enumToInt(self.CurrentState)]) | State |
{
if(State.OnUpdate) | OnUpdate | { OnUpdate(context); }
// Perform a state transition when requested
if(context.bTransition)
{
// Call the OnEnd function of the previous state to do any cleanup required.
if(State.OnEnd) | OnEnd | { OnEnd(context); }
// Call the OnStart function on the next state to do any setup required
if(self.Registery.CombatStates[@enumToInt(context.NextState)]) | NextState |
{
if(NextState.OnStart) | OnStart | { OnStart(context); }
}
// Make sure the transition isn't performed more than once.
context.bTransition = false;
// Make the next state current.
self.CurrentState = context.NextState;
}
}
}
}
};
test "Register a combat state."
{
var Registery = CombatStateRegistery{};
var TestState = CombatStateCallbacks{};
try std.testing.expect(Registery.CombatStates[0] == null);
Registery.RegisterCommonState(CombatStateID.Standing, &TestState);
try std.testing.expect(Registery.CombatStates[0] != null);
}
const TestContext = struct
{
base: CombatStateContext = .{},
TestVar: bool = false,
TestVar2: bool = false,
};
fn TestOnUpdate(context: *CombatStateContext) void
{
const context_sub = @fieldParentPtr(TestContext, "base", context);
context_sub.TestVar = true;
}
test "Test running a state update on a state machine processor."
{
var context = TestContext{};
var Processor = CombatStateMachineProcessor{.Context = &context.base};
var TestState = CombatStateCallbacks { .OnUpdate = TestOnUpdate };
Processor.Registery.RegisterCommonState(CombatStateID.Standing, &TestState);
Processor.UpdateStateMachine();
try std.testing.expect(context.TestVar == true);
}
test "Test transitioning the state machine from one state to another."
{
const Dummy = struct
{
// Test transitioning from one common state to another
fn StandingOnUpdate(context: *CombatStateContext) void
{
context.bTransition = true;
context.NextState = CombatStateID.Jump;
}
fn StandingOnEnd(context: *CombatStateContext) void
{
const context_sub = @fieldParentPtr(TestContext, "base", context);
context_sub.TestVar = true;
}
fn JumpOnStart(context: *CombatStateContext) void
{
const context_sub = @fieldParentPtr(TestContext, "base", context);
context_sub.TestVar2 = true;
}
};
var context = TestContext{};
var Processor = CombatStateMachineProcessor{.Context = &context.base};
var StandingCallbacks = CombatStateCallbacks { .OnUpdate = Dummy.StandingOnUpdate, .OnEnd = Dummy.StandingOnEnd };
var JumpCallbacks = CombatStateCallbacks { .OnStart = Dummy.JumpOnStart };
Processor.Registery.RegisterCommonState(CombatStateID.Standing, &StandingCallbacks);
Processor.Registery.RegisterCommonState(CombatStateID.Jump, &JumpCallbacks);
Processor.UpdateStateMachine();
// Test that the transition is finished
try std.testing.expect(context.base.bTransition == false);
// Test that the state machine correctly transitioned to the jump state
try std.testing.expectEqual(Processor.CurrentState, CombatStateID.Jump);
// Test to see if OnEnd was called on the previous state.
try std.testing.expect(context.TestVar == true);
// Test to see if OnStart was called on the next state.
try std.testing.expect(context.TestVar2 == true);
} | src/ActionStates/StateMachine.zig |
const std = @import("std");
const zzz = @import("zzz");
const Import = @import("import.zig").Import;
const Allocator = std.mem.Allocator;
allocator: *Allocator,
file: std.fs.File,
deps: std.ArrayList(Import),
text: []const u8,
const Self = @This();
const ZTree = zzz.ZTree(1, 1000);
const ChildIterator = struct {
val: ?*const zzz.ZNode,
fn next(self: *ChildIterator) ?*const zzz.ZNode {
return if (self.val) |node| blk: {
self.val = node.sibling;
break :blk node;
} else null;
}
fn init(node: *const zzz.ZNode) ChildIterator {
return ChildIterator{
.val = node.child,
};
}
};
/// if path doesn't exist, create it else load contents
pub fn init(allocator: *Allocator, file: std.fs.File) !Self {
var deps = std.ArrayList(Import).init(allocator);
errdefer deps.deinit();
const text = try file.readToEndAlloc(allocator, 0x2000);
errdefer allocator.free(text);
if (std.mem.indexOf(u8, text, "\r\n") != null) {
std.log.err("imports.zzz requires LF line endings, not CRLF", .{});
return error.LineEnding;
}
var tree = ZTree{};
var root = try tree.appendText(text);
// iterate and append to deps
var import_it = ChildIterator.init(root);
while (import_it.next()) |node| {
try deps.append(try Import.fromZNode(node));
}
return Self{
.allocator = allocator,
.file = file,
.deps = deps,
.text = text,
};
}
/// on destruction serialize to file
pub fn deinit(self: *Self) void {
self.deps.deinit();
self.allocator.free(self.text);
}
pub fn commit(self: *Self) !void {
var tree = ZTree{};
var root = try tree.addNode(null, .Null);
for (self.deps.items) |dep| {
_ = try dep.addToZNode(root, &tree);
}
_ = try self.file.seekTo(0);
_ = try self.file.setEndPos(0);
try root.stringifyPretty(self.file.writer());
}
pub fn addImport(self: *Self, import: Import) !void {
if (import.name.len == 0) {
return error.EmptyName;
}
for (self.deps.items) |dep| {
if (std.mem.eql(u8, dep.name, import.name)) {
return error.NameExists;
}
}
try self.deps.append(import);
}
pub fn removeImport(self: *Self, name: []const u8) !void {
for (self.deps.items) |dep, i| {
if (std.mem.eql(u8, dep.name, name)) {
_ = self.deps.orderedRemove(i);
break;
}
} else return error.NameNotFound;
} | src/manifest.zig |
const std = @import("std");
const testing = std.testing;
pub fn readULEB128(comptime T: type, in_stream: var) !T {
const ShiftT = std.meta.IntType(false, std.math.log2(T.bit_count));
var result: T = 0;
var shift: usize = 0;
while (true) {
const byte = try in_stream.readByte();
if (shift > T.bit_count)
return error.Overflow;
var operand: T = undefined;
if (@shlWithOverflow(T, byte & 0x7f, @intCast(ShiftT, shift), &operand))
return error.Overflow;
result |= operand;
if ((byte & 0x80) == 0)
return result;
shift += 7;
}
}
pub fn readULEB128Mem(comptime T: type, ptr: *[*]const u8) !T {
const ShiftT = std.meta.IntType(false, std.math.log2(T.bit_count));
var result: T = 0;
var shift: usize = 0;
var i: usize = 0;
while (true) : (i += 1) {
const byte = ptr.*[i];
if (shift > T.bit_count)
return error.Overflow;
var operand: T = undefined;
if (@shlWithOverflow(T, byte & 0x7f, @intCast(ShiftT, shift), &operand))
return error.Overflow;
result |= operand;
if ((byte & 0x80) == 0) {
ptr.* += i + 1;
return result;
}
shift += 7;
}
}
pub fn readILEB128(comptime T: type, in_stream: var) !T {
const UT = std.meta.IntType(false, T.bit_count);
const ShiftT = std.meta.IntType(false, std.math.log2(T.bit_count));
var result: UT = 0;
var shift: usize = 0;
while (true) {
const byte: u8 = try in_stream.readByte();
if (shift > T.bit_count)
return error.Overflow;
var operand: UT = undefined;
if (@shlWithOverflow(UT, @as(UT, byte & 0x7f), @intCast(ShiftT, shift), &operand)) {
if (byte != 0x7f)
return error.Overflow;
}
result |= operand;
shift += 7;
if ((byte & 0x80) == 0) {
if (shift < T.bit_count and (byte & 0x40) != 0) {
result |= @bitCast(UT, @intCast(T, -1)) << @intCast(ShiftT, shift);
}
return @bitCast(T, result);
}
}
}
pub fn readILEB128Mem(comptime T: type, ptr: *[*]const u8) !T {
const UT = std.meta.IntType(false, T.bit_count);
const ShiftT = std.meta.IntType(false, std.math.log2(T.bit_count));
var result: UT = 0;
var shift: usize = 0;
var i: usize = 0;
while (true) : (i += 1) {
const byte = ptr.*[i];
if (shift > T.bit_count)
return error.Overflow;
var operand: UT = undefined;
if (@shlWithOverflow(UT, @as(UT, byte & 0x7f), @intCast(ShiftT, shift), &operand)) {
if (byte != 0x7f)
return error.Overflow;
}
result |= operand;
shift += 7;
if ((byte & 0x80) == 0) {
if (shift < T.bit_count and (byte & 0x40) != 0) {
result |= @bitCast(UT, @intCast(T, -1)) << @intCast(ShiftT, shift);
}
ptr.* += i + 1;
return @bitCast(T, result);
}
}
}
fn test_read_stream_ileb128(comptime T: type, encoded: []const u8) !T {
var in_stream = std.io.fixedBufferStream(encoded);
return try readILEB128(T, in_stream.inStream());
}
fn test_read_stream_uleb128(comptime T: type, encoded: []const u8) !T {
var in_stream = std.io.fixedBufferStream(encoded);
return try readULEB128(T, in_stream.inStream());
}
fn test_read_ileb128(comptime T: type, encoded: []const u8) !T {
var in_stream = std.io.fixedBufferStream(encoded);
const v1 = readILEB128(T, in_stream.inStream());
var in_ptr = encoded.ptr;
const v2 = readILEB128Mem(T, &in_ptr);
testing.expectEqual(v1, v2);
return v1;
}
fn test_read_uleb128(comptime T: type, encoded: []const u8) !T {
var in_stream = std.io.fixedBufferStream(encoded);
const v1 = readULEB128(T, in_stream.inStream());
var in_ptr = encoded.ptr;
const v2 = readULEB128Mem(T, &in_ptr);
testing.expectEqual(v1, v2);
return v1;
}
fn test_read_ileb128_seq(comptime T: type, comptime N: usize, encoded: []const u8) void {
var in_stream = std.io.fixedBufferStream(encoded);
var in_ptr = encoded.ptr;
var i: usize = 0;
while (i < N) : (i += 1) {
const v1 = readILEB128(T, in_stream.inStream());
const v2 = readILEB128Mem(T, &in_ptr);
testing.expectEqual(v1, v2);
}
}
fn test_read_uleb128_seq(comptime T: type, comptime N: usize, encoded: []const u8) void {
var in_stream = std.io.fixedBufferStream(encoded);
var in_ptr = encoded.ptr;
var i: usize = 0;
while (i < N) : (i += 1) {
const v1 = readULEB128(T, in_stream.inStream());
const v2 = readULEB128Mem(T, &in_ptr);
testing.expectEqual(v1, v2);
}
}
test "deserialize signed LEB128" {
// Truncated
testing.expectError(error.EndOfStream, test_read_stream_ileb128(i64, "\x80"));
// Overflow
testing.expectError(error.Overflow, test_read_ileb128(i8, "\x80\x80\x40"));
testing.expectError(error.Overflow, test_read_ileb128(i16, "\x80\x80\x80\x40"));
testing.expectError(error.Overflow, test_read_ileb128(i32, "\x80\x80\x80\x80\x40"));
testing.expectError(error.Overflow, test_read_ileb128(i64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x40"));
testing.expectError(error.Overflow, test_read_ileb128(i8, "\xff\x7e"));
// Decode SLEB128
testing.expect((try test_read_ileb128(i64, "\x00")) == 0);
testing.expect((try test_read_ileb128(i64, "\x01")) == 1);
testing.expect((try test_read_ileb128(i64, "\x3f")) == 63);
testing.expect((try test_read_ileb128(i64, "\x40")) == -64);
testing.expect((try test_read_ileb128(i64, "\x41")) == -63);
testing.expect((try test_read_ileb128(i64, "\x7f")) == -1);
testing.expect((try test_read_ileb128(i64, "\x80\x01")) == 128);
testing.expect((try test_read_ileb128(i64, "\x81\x01")) == 129);
testing.expect((try test_read_ileb128(i64, "\xff\x7e")) == -129);
testing.expect((try test_read_ileb128(i64, "\x80\x7f")) == -128);
testing.expect((try test_read_ileb128(i64, "\x81\x7f")) == -127);
testing.expect((try test_read_ileb128(i64, "\xc0\x00")) == 64);
testing.expect((try test_read_ileb128(i64, "\xc7\x9f\x7f")) == -12345);
testing.expect((try test_read_ileb128(i8, "\xff\x7f")) == -1);
testing.expect((try test_read_ileb128(i16, "\xff\xff\x7f")) == -1);
testing.expect((try test_read_ileb128(i32, "\xff\xff\xff\xff\x7f")) == -1);
testing.expect((try test_read_ileb128(i32, "\x80\x80\x80\x80\x08")) == -0x80000000);
testing.expect((try test_read_ileb128(i64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x01")) == @bitCast(i64, @intCast(u64, 0x8000000000000000)));
testing.expect((try test_read_ileb128(i64, "\x80\x80\x80\x80\x80\x80\x80\x80\x40")) == -0x4000000000000000);
testing.expect((try test_read_ileb128(i64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x7f")) == -0x8000000000000000);
// Decode unnormalized SLEB128 with extra padding bytes.
testing.expect((try test_read_ileb128(i64, "\x80\x00")) == 0);
testing.expect((try test_read_ileb128(i64, "\x80\x80\x00")) == 0);
testing.expect((try test_read_ileb128(i64, "\xff\x00")) == 0x7f);
testing.expect((try test_read_ileb128(i64, "\xff\x80\x00")) == 0x7f);
testing.expect((try test_read_ileb128(i64, "\x80\x81\x00")) == 0x80);
testing.expect((try test_read_ileb128(i64, "\x80\x81\x80\x00")) == 0x80);
// Decode sequence of SLEB128 values
test_read_ileb128_seq(i64, 4, "\x81\x01\x3f\x80\x7f\x80\x80\x80\x00");
}
test "deserialize unsigned LEB128" {
// Truncated
testing.expectError(error.EndOfStream, test_read_stream_uleb128(u64, "\x80"));
// Overflow
testing.expectError(error.Overflow, test_read_uleb128(u8, "\x80\x02"));
testing.expectError(error.Overflow, test_read_uleb128(u8, "\x80\x80\x40"));
testing.expectError(error.Overflow, test_read_uleb128(u16, "\x80\x80\x84"));
testing.expectError(error.Overflow, test_read_uleb128(u16, "\x80\x80\x80\x40"));
testing.expectError(error.Overflow, test_read_uleb128(u32, "\x80\x80\x80\x80\x90"));
testing.expectError(error.Overflow, test_read_uleb128(u32, "\x80\x80\x80\x80\x40"));
testing.expectError(error.Overflow, test_read_uleb128(u64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x40"));
// Decode ULEB128
testing.expect((try test_read_uleb128(u64, "\x00")) == 0);
testing.expect((try test_read_uleb128(u64, "\x01")) == 1);
testing.expect((try test_read_uleb128(u64, "\x3f")) == 63);
testing.expect((try test_read_uleb128(u64, "\x40")) == 64);
testing.expect((try test_read_uleb128(u64, "\x7f")) == 0x7f);
testing.expect((try test_read_uleb128(u64, "\x80\x01")) == 0x80);
testing.expect((try test_read_uleb128(u64, "\x81\x01")) == 0x81);
testing.expect((try test_read_uleb128(u64, "\x90\x01")) == 0x90);
testing.expect((try test_read_uleb128(u64, "\xff\x01")) == 0xff);
testing.expect((try test_read_uleb128(u64, "\x80\x02")) == 0x100);
testing.expect((try test_read_uleb128(u64, "\x81\x02")) == 0x101);
testing.expect((try test_read_uleb128(u64, "\x80\xc1\x80\x80\x10")) == 4294975616);
testing.expect((try test_read_uleb128(u64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x01")) == 0x8000000000000000);
// Decode ULEB128 with extra padding bytes
testing.expect((try test_read_uleb128(u64, "\x80\x00")) == 0);
testing.expect((try test_read_uleb128(u64, "\x80\x80\x00")) == 0);
testing.expect((try test_read_uleb128(u64, "\xff\x00")) == 0x7f);
testing.expect((try test_read_uleb128(u64, "\xff\x80\x00")) == 0x7f);
testing.expect((try test_read_uleb128(u64, "\x80\x81\x00")) == 0x80);
testing.expect((try test_read_uleb128(u64, "\x80\x81\x80\x00")) == 0x80);
// Decode sequence of ULEB128 values
test_read_uleb128_seq(u64, 4, "\x81\x01\x3f\x80\x7f\x80\x80\x80\x00");
} | lib/std/debug/leb128.zig |
const std = @import("std");
const FrameProcessorBase = @import("frame-processor.zig").FrameProcessor;
const mc = @import("mc.zig");
const audio = @import("audio-extractor.zig");
usingnamespace @cImport({
@cInclude("jni.h");
@cInclude("win32/jni_md.h");
});
const MinecraftFrameProcessor = FrameProcessorBase(*mc.NativeMapContext);
var allocator: *std.mem.Allocator = std.heap.c_allocator;
var pointerID: jfieldID = undefined;
// Internal native functions
export fn Java_academy_hekiyou_vidmap_NativeMap__1_1createNativeContext(
env: *JNIEnv,
instance: jobject,
buffer: jobject,
width: jint,
height: jint,
) callconv(.C) jlong {
_ = instance;
var context = allocator.create(mc.NativeMapContext) catch return 0;
context.buffer = @ptrCast([*]u8, env.*.*.GetDirectBufferAddress.?(env, buffer));
context.mapWidth = @truncate(u16, @intCast(c_ulong, width));
context.mapHeight = @truncate(u16, @intCast(c_ulong, height));
var processor = allocator.create(MinecraftFrameProcessor) catch {
allocator.destroy(context);
return 0;
};
processor.userData = context;
processor.callback = mc.toMinecraftColors;
return @intCast(jlong, @ptrToInt(processor));
}
export fn Java_academy_hekiyou_vidmap_NativeMap__1_1open(
env: *JNIEnv,
instance: jobject,
jsource: jstring,
) callconv(.C) jdouble {
const source = env.*.*.GetStringUTFChars.?(env, jsource, null);
defer env.*.*.ReleaseStringUTFChars.?(env, jsource, source);
var processor = deriveProcessor(env, instance) catch return -1.0;
var context = processor.userData.?;
return processor.open(source, context.mapWidth * 128, context.mapHeight * 128) catch -1.0;
}
export fn Java_academy_hekiyou_vidmap_NativeMap__1_1processNextFrame(
env: *JNIEnv,
instance: jobject,
) callconv(.C) jboolean {
var processor = deriveProcessor(env, instance) catch return 0;
return if (processor.processNextFrame()) 1 else 0;
}
export fn Java_academy_hekiyou_vidmap_NativeMap__1_1free(
env: *JNIEnv,
instance: jobject,
) callconv(.C) void {
var processor = deriveProcessor(env, instance) catch return;
processor.close() catch @panic("Failed to close frame processor");
}
// Global functions that require no instance
export fn Java_academy_hekiyou_vidmap_NativeMap_initialize(
env: *JNIEnv,
class: jclass,
) callconv(.C) void {
pointerID = env.*.*.GetFieldID.?(env, class, "__pointer", "J");
}
export fn Java_academy_hekiyou_vidmap_NativeMap_deinitialize(
env: *JNIEnv,
class: jclass,
) callconv(.C) void {
_ = env;
_ = class;
// is there anything to deinitialize
}
export fn Java_academy_hekiyou_vidmap_NativeMap_extractAudio(
env: *JNIEnv,
class: jclass,
jsrc: jstring,
jdst: jstring,
) callconv(.C) bool {
_ = env;
_ = class;
_ = jsrc;
_ = jdst;
const src = env.*.*.GetStringUTFChars.?(env, jsrc, null);
defer env.*.*.ReleaseStringUTFChars.?(env, jsrc, src);
const dst = env.*.*.GetStringUTFChars.?(env, jdst, null);
defer env.*.*.ReleaseStringUTFChars.?(env, jdst, dst);
audio.extractAudio(src, dst) catch return false;
return true;
}
inline fn deriveProcessor(env: *JNIEnv, instance: jobject) !*MinecraftFrameProcessor {
var jpointer: jlong = env.*.*.GetLongField.?(env, instance, pointerID);
if (jpointer == -1)
return error.Uninitialized;
return @intToPtr(*MinecraftFrameProcessor, @intCast(usize, jpointer));
}
inline fn deriveContext(env: *JNIEnv, instance: jobject) !mc.NativeMapContext {
return deriveProcessor(env, instance).userData;
} | nativemap/src/jni-lib.zig |
const std = @import("std");
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const expectEqualStrings = std.testing.expectEqualStrings;
const expectEqualSlices = std.testing.expectEqualSlices;
const Context = @import("Context.zig");
const Zigstr = @import("zigstr/Zigstr.zig");
test "README tests" {
var allocator = std.testing.allocator;
var ctx = Context.init(allocator);
defer ctx.deinit();
var zigstr = try Zigstr.Factory.init(&ctx);
defer zigstr.deinit();
var str = try zigstr.new("Héllo");
// Byte count.
expectEqual(@as(usize, 6), str.byteCount());
// Code point iteration.
var cp_iter = try str.codePointIter();
var want = [_]u21{ 'H', 0x00E9, 'l', 'l', 'o' };
var i: usize = 0;
while (cp_iter.next()) |cp| : (i += 1) {
expectEqual(want[i], cp);
}
// Code point count.
expectEqual(@as(usize, 5), str.codePointCount());
// Collect all code points at once.
expectEqualSlices(u21, &want, try str.codePoints());
// Grapheme cluster iteration.
var giter = try str.graphemeIter();
const gc_want = [_][]const u8{ "H", "é", "l", "l", "o" };
i = 0;
while (try giter.next()) |gc| : (i += 1) {
expect(gc.eql(gc_want[i]));
}
// Collect all grapheme clusters at once.
expectEqual(@as(usize, 5), try str.graphemeCount());
const gcs = try str.graphemes();
for (gcs) |gc, j| {
expect(gc.eql(gc_want[j]));
}
// Grapheme count.
expectEqual(@as(usize, 5), try str.graphemeCount());
// Copy
var str2 = try str.copy();
expect(str.eql(str2.bytes));
expect(str2.eql("Héllo"));
expect(str.sameAs(str2));
// Equality
try str.reset("foo"); // re-initialize a Zigstr.
expect(str.eql("foo")); // exact
expect(!str.eql("fooo")); // lengths
expect(!str.eql("foó")); // combining marks
expect(!str.eql("Foo")); // letter case
expect(try str.eqlBy("Foo", .ignore_case));
try str.reset("foé");
expect(try str.eqlBy("foe\u{0301}", .normalize));
try str.reset("foϓ");
expect(try str.eqlBy("foΥ\u{0301}", .normalize));
try str.reset("Foϓ");
expect(try str.eqlBy("foΥ\u{0301}", .norm_ignore));
try str.reset("FOÉ");
expect(try str.eqlBy("foe\u{0301}", .norm_ignore)); // foÉ == foé
// Trimming.
try str.reset(" Hello");
try str.trimLeft(" ");
expect(str.eql("Hello"));
try str.reset("Hello ");
try str.trimRight(" ");
expect(str.eql("Hello"));
try str.reset(" Hello ");
try str.trim(" ");
expect(str.eql("Hello"));
// indexOf / contains / lastIndexOf
expectEqual(str.indexOf("l"), 2);
expectEqual(str.indexOf("z"), null);
expect(str.contains("l"));
expect(!str.contains("z"));
expectEqual(str.lastIndexOf("l"), 3);
expectEqual(str.lastIndexOf("z"), null);
// count
expectEqual(str.count("l"), 2);
expectEqual(str.count("ll"), 1);
expectEqual(str.count("z"), 0);
// Tokenization
try str.reset(" Hello World ");
// Token iteration.
var tok_iter = str.tokenIter(" ");
expectEqualStrings("Hello", tok_iter.next().?);
expectEqualStrings("World", tok_iter.next().?);
expect(tok_iter.next() == null);
// Collect all tokens at once.
var ts = try str.tokenize(" ");
expectEqual(@as(usize, 2), ts.len);
expectEqualStrings("Hello", ts[0]);
expectEqualStrings("World", ts[1]);
// Split
var split_iter = str.splitIter(" ");
expectEqualStrings("", split_iter.next().?);
expectEqualStrings("Hello", split_iter.next().?);
expectEqualStrings("World", split_iter.next().?);
expectEqualStrings("", split_iter.next().?);
expect(split_iter.next() == null);
// Collect all sub-strings at once.
var ss = try str.split(" ");
expectEqual(@as(usize, 4), ss.len);
expectEqualStrings("", ss[0]);
expectEqualStrings("Hello", ss[1]);
expectEqualStrings("World", ss[2]);
expectEqualStrings("", ss[3]);
// startsWith / endsWith
try str.reset("Hello World");
expect(str.startsWith("Hell"));
expect(!str.startsWith("Zig"));
expect(str.endsWith("World"));
expect(!str.endsWith("Zig"));
// Concatenation
try str.reset("Hello");
try str.concat(" World");
expect(str.eql("Hello World"));
var others = [_][]const u8{ " is", " the", " tradition!" };
try str.concatAll(&others);
expect(str.eql("Hello World is the tradition!"));
// replace
try str.reset("Hello");
var replacements = try str.replace("l", "z");
expectEqual(@as(usize, 2), replacements);
expect(str.eql("Hezzo"));
replacements = try str.replace("z", "");
expectEqual(@as(usize, 2), replacements);
expect(str.eql("Heo"));
// Append a code point or many.
try str.reset("Hell");
try str.append('o');
expectEqual(@as(usize, 5), str.bytes.len);
expect(str.eql("Hello"));
try str.appendAll(&[_]u21{ ' ', 'W', 'o', 'r', 'l', 'd' });
expect(str.eql("Hello World"));
// Test for empty string.
expect(!str.empty());
// Chomp line breaks.
try str.reset("Hello\n");
try str.chomp();
expectEqual(@as(usize, 5), str.bytes.len);
expect(str.eql("Hello"));
try str.reset("Hello\r");
try str.chomp();
expectEqual(@as(usize, 5), str.bytes.len);
expect(str.eql("Hello"));
try str.reset("Hello\r\n");
try str.chomp();
expectEqual(@as(usize, 5), str.bytes.len);
expect(str.eql("Hello"));
// byteSlice, codePointSlice, graphemeSlice, substr
try str.reset("H\u{0065}\u{0301}llo"); // Héllo
expectEqualSlices(u8, try str.byteSlice(1, 4), "\u{0065}\u{0301}");
expectEqualSlices(u21, try str.codePointSlice(1, 3), &[_]u21{ '\u{0065}', '\u{0301}' });
const gc1 = try str.graphemeSlice(1, 2);
expect(gc1[0].eql("\u{0065}\u{0301}"));
// Substrings
var str3 = try str.substr(1, 2);
expect(str3.eql("\u{0065}\u{0301}"));
expect(str3.eql(try str.byteSlice(1, 4)));
// Letter case detection.
try str.reset("hello! 123");
expect(try str.isLower());
expect(!try str.isUpper());
try str.reset("HELLO! 123");
expect(try str.isUpper());
expect(!try str.isLower());
// Letter case conversion.
try str.reset("Héllo! 123");
try str.toLower();
expect(str.eql("héllo! 123"));
try str.toUpper();
expect(str.eql("HÉLLO! 123"));
// Fixed-width cell / columns size. This uses halfwidth for ambiguous code points, which is the
// most common case. To use fullwidth, use the Zigstr.Width component struct directly.
try str.reset("Héllo 😊");
expectEqual(@as(usize, 8), try str.width());
} | src/zigstr_readme_tests.zig |
const Emit = @This();
const std = @import("std");
const assert = std.debug.assert;
const bits = @import("bits.zig");
const leb128 = std.leb;
const link = @import("../../link.zig");
const log = std.log.scoped(.codegen);
const math = std.math;
const mem = std.mem;
const Air = @import("../../Air.zig");
const DebugInfoOutput = @import("../../codegen.zig").DebugInfoOutput;
const DW = std.dwarf;
const Encoder = bits.Encoder;
const ErrorMsg = Module.ErrorMsg;
const MCValue = @import("CodeGen.zig").MCValue;
const Mir = @import("Mir.zig");
const Module = @import("../../Module.zig");
const Instruction = bits.Instruction;
const Register = bits.Register;
const Type = @import("../../type.zig").Type;
mir: Mir,
bin_file: *link.File,
debug_output: DebugInfoOutput,
target: *const std.Target,
err_msg: ?*ErrorMsg = null,
src_loc: Module.SrcLoc,
code: *std.ArrayList(u8),
prev_di_line: u32,
prev_di_column: u32,
/// Relative to the beginning of `code`.
prev_di_pc: usize,
code_offset_mapping: std.AutoHashMapUnmanaged(Mir.Inst.Index, usize) = .{},
relocs: std.ArrayListUnmanaged(Reloc) = .{},
const InnerError = error{
OutOfMemory,
EmitFail,
};
const Reloc = struct {
/// Offset of the instruction.
source: u64,
/// Target of the relocation.
target: Mir.Inst.Index,
/// Offset of the relocation within the instruction.
offset: u64,
/// Length of the instruction.
length: u5,
};
pub fn emitMir(emit: *Emit) InnerError!void {
const mir_tags = emit.mir.instructions.items(.tag);
for (mir_tags) |tag, index| {
const inst = @intCast(u32, index);
try emit.code_offset_mapping.putNoClobber(emit.bin_file.allocator, inst, emit.code.items.len);
switch (tag) {
.adc => try emit.mirArith(.adc, inst),
.add => try emit.mirArith(.add, inst),
.sub => try emit.mirArith(.sub, inst),
.xor => try emit.mirArith(.xor, inst),
.@"and" => try emit.mirArith(.@"and", inst),
.@"or" => try emit.mirArith(.@"or", inst),
.sbb => try emit.mirArith(.sbb, inst),
.cmp => try emit.mirArith(.cmp, inst),
.adc_scale_src => try emit.mirArithScaleSrc(.adc, inst),
.add_scale_src => try emit.mirArithScaleSrc(.add, inst),
.sub_scale_src => try emit.mirArithScaleSrc(.sub, inst),
.xor_scale_src => try emit.mirArithScaleSrc(.xor, inst),
.and_scale_src => try emit.mirArithScaleSrc(.@"and", inst),
.or_scale_src => try emit.mirArithScaleSrc(.@"or", inst),
.sbb_scale_src => try emit.mirArithScaleSrc(.sbb, inst),
.cmp_scale_src => try emit.mirArithScaleSrc(.cmp, inst),
.adc_scale_dst => try emit.mirArithScaleDst(.adc, inst),
.add_scale_dst => try emit.mirArithScaleDst(.add, inst),
.sub_scale_dst => try emit.mirArithScaleDst(.sub, inst),
.xor_scale_dst => try emit.mirArithScaleDst(.xor, inst),
.and_scale_dst => try emit.mirArithScaleDst(.@"and", inst),
.or_scale_dst => try emit.mirArithScaleDst(.@"or", inst),
.sbb_scale_dst => try emit.mirArithScaleDst(.sbb, inst),
.cmp_scale_dst => try emit.mirArithScaleDst(.cmp, inst),
.adc_scale_imm => try emit.mirArithScaleImm(.adc, inst),
.add_scale_imm => try emit.mirArithScaleImm(.add, inst),
.sub_scale_imm => try emit.mirArithScaleImm(.sub, inst),
.xor_scale_imm => try emit.mirArithScaleImm(.xor, inst),
.and_scale_imm => try emit.mirArithScaleImm(.@"and", inst),
.or_scale_imm => try emit.mirArithScaleImm(.@"or", inst),
.sbb_scale_imm => try emit.mirArithScaleImm(.sbb, inst),
.cmp_scale_imm => try emit.mirArithScaleImm(.cmp, inst),
// Even though MOV is technically not an arithmetic op,
// its structure can be represented using the same set of
// opcode primitives.
.mov => try emit.mirArith(.mov, inst),
.mov_scale_src => try emit.mirArithScaleSrc(.mov, inst),
.mov_scale_dst => try emit.mirArithScaleDst(.mov, inst),
.mov_scale_imm => try emit.mirArithScaleImm(.mov, inst),
.movabs => try emit.mirMovabs(inst),
.lea => try emit.mirLea(inst),
.lea_rip => try emit.mirLeaRip(inst),
.imul_complex => try emit.mirIMulComplex(inst),
.push => try emit.mirPushPop(.push, inst),
.pop => try emit.mirPushPop(.pop, inst),
.jmp => try emit.mirJmpCall(.jmp, inst),
.call => try emit.mirJmpCall(.call, inst),
.cond_jmp_greater_less => try emit.mirCondJmp(.cond_jmp_greater_less, inst),
.cond_jmp_above_below => try emit.mirCondJmp(.cond_jmp_above_below, inst),
.cond_jmp_eq_ne => try emit.mirCondJmp(.cond_jmp_eq_ne, inst),
.cond_set_byte_greater_less => try emit.mirCondSetByte(.cond_set_byte_greater_less, inst),
.cond_set_byte_above_below => try emit.mirCondSetByte(.cond_set_byte_above_below, inst),
.cond_set_byte_eq_ne => try emit.mirCondSetByte(.cond_set_byte_eq_ne, inst),
.ret => try emit.mirRet(inst),
.syscall => try emit.mirSyscall(),
.@"test" => try emit.mirTest(inst),
.brk => try emit.mirBrk(),
.call_extern => try emit.mirCallExtern(inst),
.dbg_line => try emit.mirDbgLine(inst),
.dbg_prologue_end => try emit.mirDbgPrologueEnd(inst),
.dbg_epilogue_begin => try emit.mirDbgEpilogueBegin(inst),
.arg_dbg_info => try emit.mirArgDbgInfo(inst),
else => {
return emit.fail("Implement MIR->Isel lowering for x86_64 for pseudo-inst: {s}", .{tag});
},
}
}
try emit.fixupRelocs();
}
pub fn deinit(emit: *Emit) void {
emit.relocs.deinit(emit.bin_file.allocator);
emit.code_offset_mapping.deinit(emit.bin_file.allocator);
emit.* = undefined;
}
fn fail(emit: *Emit, comptime format: []const u8, args: anytype) InnerError {
@setCold(true);
assert(emit.err_msg == null);
emit.err_msg = try ErrorMsg.create(emit.bin_file.allocator, emit.src_loc, format, args);
return error.EmitFail;
}
fn fixupRelocs(emit: *Emit) InnerError!void {
// TODO this function currently assumes all relocs via JMP/CALL instructions are 32bit in size.
// This should be reversed like it is done in aarch64 MIR emit code: start with the smallest
// possible resolution, i.e., 8bit, and iteratively converge on the minimum required resolution
// until the entire decl is correctly emitted with all JMP/CALL instructions within range.
for (emit.relocs.items) |reloc| {
const target = emit.code_offset_mapping.get(reloc.target) orelse
return emit.fail("JMP/CALL relocation target not found!", .{});
const disp = @intCast(i32, @intCast(i64, target) - @intCast(i64, reloc.source + reloc.length));
mem.writeIntLittle(i32, emit.code.items[reloc.offset..][0..4], disp);
}
}
fn mirBrk(emit: *Emit) InnerError!void {
const encoder = try Encoder.init(emit.code, 1);
encoder.opcode_1byte(0xcc);
}
fn mirSyscall(emit: *Emit) InnerError!void {
const encoder = try Encoder.init(emit.code, 2);
encoder.opcode_2byte(0x0f, 0x05);
}
fn mirPushPop(emit: *Emit, tag: Mir.Inst.Tag, inst: Mir.Inst.Index) InnerError!void {
const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]);
switch (ops.flags) {
0b00 => {
// PUSH/POP reg
const opc: u8 = switch (tag) {
.push => 0x50,
.pop => 0x58,
else => unreachable,
};
const encoder = try Encoder.init(emit.code, 1);
encoder.opcode_withReg(opc, ops.reg1.lowId());
},
0b01 => {
// PUSH/POP r/m64
const imm = emit.mir.instructions.items(.data)[inst].imm;
const opc: u8 = switch (tag) {
.push => 0xff,
.pop => 0x8f,
else => unreachable,
};
const modrm_ext: u3 = switch (tag) {
.push => 0x6,
.pop => 0x0,
else => unreachable,
};
const encoder = try Encoder.init(emit.code, 6);
encoder.opcode_1byte(opc);
if (math.cast(i8, imm)) |imm_i8| {
encoder.modRm_indirectDisp8(modrm_ext, ops.reg1.lowId());
encoder.imm8(@intCast(i8, imm_i8));
} else |_| {
encoder.modRm_indirectDisp32(modrm_ext, ops.reg1.lowId());
encoder.imm32(imm);
}
},
0b10 => {
// PUSH imm32
assert(tag == .push);
const imm = emit.mir.instructions.items(.data)[inst].imm;
const opc: u8 = if (imm <= math.maxInt(i8)) 0x6a else 0x6b;
const encoder = try Encoder.init(emit.code, 2);
encoder.opcode_1byte(opc);
if (imm <= math.maxInt(i8)) {
encoder.imm8(@intCast(i8, imm));
} else if (imm <= math.maxInt(i16)) {
encoder.imm16(@intCast(i16, imm));
} else {
encoder.imm32(imm);
}
},
0b11 => unreachable,
}
}
fn mirJmpCall(emit: *Emit, tag: Mir.Inst.Tag, inst: Mir.Inst.Index) InnerError!void {
const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]);
const flag = @truncate(u1, ops.flags);
if (flag == 0) {
const target = emit.mir.instructions.items(.data)[inst].inst;
const opc: u8 = switch (tag) {
.jmp => 0xe9,
.call => 0xe8,
else => unreachable,
};
const source = emit.code.items.len;
const encoder = try Encoder.init(emit.code, 5);
encoder.opcode_1byte(opc);
try emit.relocs.append(emit.bin_file.allocator, .{
.source = source,
.target = target,
.offset = emit.code.items.len,
.length = 5,
});
encoder.imm32(0x0);
return;
}
const modrm_ext: u3 = switch (tag) {
.jmp => 0x4,
.call => 0x2,
else => unreachable,
};
if (ops.reg1 == .none) {
// JMP/CALL [imm]
const imm = emit.mir.instructions.items(.data)[inst].imm;
const encoder = try Encoder.init(emit.code, 7);
encoder.opcode_1byte(0xff);
encoder.modRm_SIBDisp0(modrm_ext);
encoder.sib_disp32();
encoder.imm32(imm);
return;
}
// JMP/CALL reg
const encoder = try Encoder.init(emit.code, 2);
encoder.opcode_1byte(0xff);
encoder.modRm_direct(modrm_ext, ops.reg1.lowId());
}
const CondType = enum {
/// greater than or equal
gte,
/// greater than
gt,
/// less than
lt,
/// less than or equal
lte,
/// above or equal
ae,
/// above
a,
/// below
b,
/// below or equal
be,
/// not equal
ne,
/// equal
eq,
fn fromTagAndFlags(tag: Mir.Inst.Tag, flags: u2) CondType {
return switch (tag) {
.cond_jmp_greater_less,
.cond_set_byte_greater_less,
=> switch (flags) {
0b00 => CondType.gte,
0b01 => CondType.gt,
0b10 => CondType.lt,
0b11 => CondType.lte,
},
.cond_jmp_above_below,
.cond_set_byte_above_below,
=> switch (flags) {
0b00 => CondType.ae,
0b01 => CondType.a,
0b10 => CondType.b,
0b11 => CondType.be,
},
.cond_jmp_eq_ne,
.cond_set_byte_eq_ne,
=> switch (@truncate(u1, flags)) {
0b0 => CondType.ne,
0b1 => CondType.eq,
},
else => unreachable,
};
}
};
inline fn getCondOpCode(tag: Mir.Inst.Tag, cond: CondType) u8 {
switch (cond) {
.gte => return switch (tag) {
.cond_jmp_greater_less => 0x8d,
.cond_set_byte_greater_less => 0x9d,
else => unreachable,
},
.gt => return switch (tag) {
.cond_jmp_greater_less => 0x8f,
.cond_set_byte_greater_less => 0x9f,
else => unreachable,
},
.lt => return switch (tag) {
.cond_jmp_greater_less => 0x8c,
.cond_set_byte_greater_less => 0x9c,
else => unreachable,
},
.lte => return switch (tag) {
.cond_jmp_greater_less => 0x8e,
.cond_set_byte_greater_less => 0x9e,
else => unreachable,
},
.ae => return switch (tag) {
.cond_jmp_above_below => 0x83,
.cond_set_byte_above_below => 0x93,
else => unreachable,
},
.a => return switch (tag) {
.cond_jmp_above_below => 0x87,
.cond_set_byte_greater_less => 0x97,
else => unreachable,
},
.b => return switch (tag) {
.cond_jmp_above_below => 0x82,
.cond_set_byte_greater_less => 0x92,
else => unreachable,
},
.be => return switch (tag) {
.cond_jmp_above_below => 0x86,
.cond_set_byte_greater_less => 0x96,
else => unreachable,
},
.eq => return switch (tag) {
.cond_jmp_eq_ne => 0x84,
.cond_set_byte_eq_ne => 0x94,
else => unreachable,
},
.ne => return switch (tag) {
.cond_jmp_eq_ne => 0x85,
.cond_set_byte_eq_ne => 0x95,
else => unreachable,
},
}
}
fn mirCondJmp(emit: *Emit, tag: Mir.Inst.Tag, inst: Mir.Inst.Index) InnerError!void {
const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]);
const target = emit.mir.instructions.items(.data)[inst].inst;
const cond = CondType.fromTagAndFlags(tag, ops.flags);
const opc = getCondOpCode(tag, cond);
const source = emit.code.items.len;
const encoder = try Encoder.init(emit.code, 6);
encoder.opcode_2byte(0x0f, opc);
try emit.relocs.append(emit.bin_file.allocator, .{
.source = source,
.target = target,
.offset = emit.code.items.len,
.length = 6,
});
encoder.imm32(0);
}
fn mirCondSetByte(emit: *Emit, tag: Mir.Inst.Tag, inst: Mir.Inst.Index) InnerError!void {
const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]);
const cond = CondType.fromTagAndFlags(tag, ops.flags);
const opc = getCondOpCode(tag, cond);
const encoder = try Encoder.init(emit.code, 4);
encoder.rex(.{
.w = true,
.b = ops.reg1.isExtended(),
});
encoder.opcode_2byte(0x0f, opc);
encoder.modRm_direct(0x0, ops.reg1.lowId());
}
fn mirTest(emit: *Emit, inst: Mir.Inst.Index) InnerError!void {
const tag = emit.mir.instructions.items(.tag)[inst];
assert(tag == .@"test");
const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]);
switch (ops.flags) {
0b00 => blk: {
if (ops.reg2 == .none) {
// TEST r/m64, imm32
const imm = emit.mir.instructions.items(.data)[inst].imm;
if (ops.reg1.to64() == .rax) {
// TODO reduce the size of the instruction if the immediate
// is smaller than 32 bits
const encoder = try Encoder.init(emit.code, 6);
encoder.rex(.{
.w = true,
});
encoder.opcode_1byte(0xa9);
encoder.imm32(imm);
break :blk;
}
const opc: u8 = if (ops.reg1.size() == 8) 0xf6 else 0xf7;
const encoder = try Encoder.init(emit.code, 7);
encoder.rex(.{
.w = true,
.b = ops.reg1.isExtended(),
});
encoder.opcode_1byte(opc);
encoder.modRm_direct(0, ops.reg1.lowId());
encoder.imm8(@intCast(i8, imm));
break :blk;
}
// TEST r/m64, r64
return emit.fail("TODO TEST r/m64, r64", .{});
},
else => return emit.fail("TODO more TEST alternatives", .{}),
}
}
fn mirRet(emit: *Emit, inst: Mir.Inst.Index) InnerError!void {
const tag = emit.mir.instructions.items(.tag)[inst];
assert(tag == .ret);
const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]);
const encoder = try Encoder.init(emit.code, 3);
switch (ops.flags) {
0b00 => {
// RETF imm16
const imm = emit.mir.instructions.items(.data)[inst].imm;
encoder.opcode_1byte(0xca);
encoder.imm16(@intCast(i16, imm));
},
0b01 => encoder.opcode_1byte(0xcb), // RETF
0b10 => {
// RET imm16
const imm = emit.mir.instructions.items(.data)[inst].imm;
encoder.opcode_1byte(0xc2);
encoder.imm16(@intCast(i16, imm));
},
0b11 => encoder.opcode_1byte(0xc3), // RET
}
}
const EncType = enum {
/// OP r/m64, imm32
mi,
/// OP r/m64, r64
mr,
/// OP r64, r/m64
rm,
};
const OpCode = struct {
opc: u8,
/// Only used if `EncType == .mi`.
modrm_ext: u3,
};
inline fn getArithOpCode(tag: Mir.Inst.Tag, enc: EncType) OpCode {
switch (enc) {
.mi => return switch (tag) {
.adc => .{ .opc = 0x81, .modrm_ext = 0x2 },
.add => .{ .opc = 0x81, .modrm_ext = 0x0 },
.sub => .{ .opc = 0x81, .modrm_ext = 0x5 },
.xor => .{ .opc = 0x81, .modrm_ext = 0x6 },
.@"and" => .{ .opc = 0x81, .modrm_ext = 0x4 },
.@"or" => .{ .opc = 0x81, .modrm_ext = 0x1 },
.sbb => .{ .opc = 0x81, .modrm_ext = 0x3 },
.cmp => .{ .opc = 0x81, .modrm_ext = 0x7 },
.mov => .{ .opc = 0xc7, .modrm_ext = 0x0 },
else => unreachable,
},
.mr => {
const opc: u8 = switch (tag) {
.adc => 0x11,
.add => 0x01,
.sub => 0x29,
.xor => 0x31,
.@"and" => 0x21,
.@"or" => 0x09,
.sbb => 0x19,
.cmp => 0x39,
.mov => 0x89,
else => unreachable,
};
return .{ .opc = opc, .modrm_ext = undefined };
},
.rm => {
const opc: u8 = switch (tag) {
.adc => 0x13,
.add => 0x03,
.sub => 0x2b,
.xor => 0x33,
.@"and" => 0x23,
.@"or" => 0x0b,
.sbb => 0x1b,
.cmp => 0x3b,
.mov => 0x8b,
else => unreachable,
};
return .{ .opc = opc, .modrm_ext = undefined };
},
}
}
fn mirArith(emit: *Emit, tag: Mir.Inst.Tag, inst: Mir.Inst.Index) InnerError!void {
const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]);
switch (ops.flags) {
0b00 => blk: {
if (ops.reg2 == .none) {
// OP reg1, imm32
// OP r/m64, imm32
const imm = emit.mir.instructions.items(.data)[inst].imm;
const opcode = getArithOpCode(tag, .mi);
const encoder = try Encoder.init(emit.code, 7);
encoder.rex(.{
.w = ops.reg1.size() == 64,
.b = ops.reg1.isExtended(),
});
if (tag != .mov and imm <= math.maxInt(i8)) {
encoder.opcode_1byte(opcode.opc + 2);
encoder.modRm_direct(opcode.modrm_ext, ops.reg1.lowId());
encoder.imm8(@intCast(i8, imm));
} else {
encoder.opcode_1byte(opcode.opc);
encoder.modRm_direct(opcode.modrm_ext, ops.reg1.lowId());
encoder.imm32(imm);
}
break :blk;
}
// OP reg1, reg2
// OP r/m64, r64
const opcode = getArithOpCode(tag, .mr);
const opc = if (ops.reg1.size() == 8) opcode.opc - 1 else opcode.opc;
const encoder = try Encoder.init(emit.code, 3);
encoder.rex(.{
.w = ops.reg1.size() == 64 and ops.reg2.size() == 64,
.r = ops.reg1.isExtended(),
.b = ops.reg2.isExtended(),
});
encoder.opcode_1byte(opc);
encoder.modRm_direct(ops.reg1.lowId(), ops.reg2.lowId());
},
0b01 => blk: {
const imm = emit.mir.instructions.items(.data)[inst].imm;
const opcode = getArithOpCode(tag, .rm);
const opc = if (ops.reg1.size() == 8) opcode.opc - 1 else opcode.opc;
if (ops.reg2 == .none) {
// OP reg1, [imm32]
// OP r64, r/m64
const encoder = try Encoder.init(emit.code, 8);
encoder.rex(.{
.w = ops.reg1.size() == 64,
.b = ops.reg1.isExtended(),
});
encoder.opcode_1byte(opc);
encoder.modRm_SIBDisp0(ops.reg1.lowId());
encoder.sib_disp32();
encoder.disp32(imm);
break :blk;
}
// OP reg1, [reg2 + imm32]
// OP r64, r/m64
const encoder = try Encoder.init(emit.code, 7);
encoder.rex(.{
.w = ops.reg1.size() == 64,
.r = ops.reg1.isExtended(),
.b = ops.reg2.isExtended(),
});
encoder.opcode_1byte(opc);
if (imm <= math.maxInt(i8)) {
encoder.modRm_indirectDisp8(ops.reg1.lowId(), ops.reg2.lowId());
encoder.disp8(@intCast(i8, imm));
} else {
encoder.modRm_indirectDisp32(ops.reg1.lowId(), ops.reg2.lowId());
encoder.disp32(imm);
}
},
0b10 => blk: {
if (ops.reg2 == .none) {
// OP [reg1 + 0], imm32
// OP r/m64, imm32
const imm = emit.mir.instructions.items(.data)[inst].imm;
const opcode = getArithOpCode(tag, .mi);
const opc = if (ops.reg1.size() == 8) opcode.opc - 1 else opcode.opc;
const encoder = try Encoder.init(emit.code, 7);
encoder.rex(.{
.w = ops.reg1.size() == 64,
.b = ops.reg1.isExtended(),
});
encoder.opcode_1byte(opc);
encoder.modRm_indirectDisp0(opcode.modrm_ext, ops.reg1.lowId());
if (imm <= math.maxInt(i8)) {
encoder.imm8(@intCast(i8, imm));
} else if (imm <= math.maxInt(i16)) {
encoder.imm16(@intCast(i16, imm));
} else {
encoder.imm32(imm);
}
break :blk;
}
// OP [reg1 + imm32], reg2
// OP r/m64, r64
const imm = emit.mir.instructions.items(.data)[inst].imm;
const opcode = getArithOpCode(tag, .mr);
const opc = if (ops.reg1.size() == 8) opcode.opc - 1 else opcode.opc;
const encoder = try Encoder.init(emit.code, 7);
encoder.rex(.{
.w = ops.reg2.size() == 64,
.r = ops.reg1.isExtended(),
.b = ops.reg2.isExtended(),
});
encoder.opcode_1byte(opc);
if (imm <= math.maxInt(i8)) {
encoder.modRm_indirectDisp8(ops.reg1.lowId(), ops.reg2.lowId());
encoder.disp8(@intCast(i8, imm));
} else {
encoder.modRm_indirectDisp32(ops.reg1.lowId(), ops.reg2.lowId());
encoder.disp32(imm);
}
},
0b11 => blk: {
if (ops.reg2 == .none) {
// OP [reg1 + imm32], imm32
// OP r/m64, imm32
const payload = emit.mir.instructions.items(.data)[inst].payload;
const imm_pair = emit.mir.extraData(Mir.ImmPair, payload).data;
const opcode = getArithOpCode(tag, .mi);
const opc = if (ops.reg1.size() == 8) opcode.opc - 1 else opcode.opc;
const encoder = try Encoder.init(emit.code, 11);
encoder.rex(.{
.w = false,
.b = ops.reg1.isExtended(),
});
encoder.opcode_1byte(opc);
if (imm_pair.dest_off <= math.maxInt(i8)) {
encoder.modRm_indirectDisp8(opcode.modrm_ext, ops.reg1.lowId());
encoder.disp8(@intCast(i8, imm_pair.dest_off));
} else {
encoder.modRm_indirectDisp32(opcode.modrm_ext, ops.reg1.lowId());
encoder.disp32(imm_pair.dest_off);
}
encoder.imm32(imm_pair.operand);
break :blk;
}
// TODO clearly mov doesn't belong here; for other, arithemtic ops,
// this is the same as 0b00.
const opcode = getArithOpCode(tag, if (tag == .mov) .rm else .mr);
const opc = if (ops.reg1.size() == 8) opcode.opc - 1 else opcode.opc;
const encoder = try Encoder.init(emit.code, 3);
encoder.rex(.{
.w = ops.reg1.size() == 64 and ops.reg2.size() == 64,
.r = ops.reg1.isExtended(),
.b = ops.reg2.isExtended(),
});
encoder.opcode_1byte(opc);
encoder.modRm_direct(ops.reg1.lowId(), ops.reg2.lowId());
},
}
}
fn mirArithScaleSrc(emit: *Emit, tag: Mir.Inst.Tag, inst: Mir.Inst.Index) InnerError!void {
const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]);
const scale = ops.flags;
// OP reg1, [reg2 + scale*rcx + imm32]
const opcode = getArithOpCode(tag, .rm);
const opc = if (ops.reg1.size() == 8) opcode.opc - 1 else opcode.opc;
const imm = emit.mir.instructions.items(.data)[inst].imm;
const encoder = try Encoder.init(emit.code, 8);
encoder.rex(.{
.w = ops.reg1.size() == 64,
.r = ops.reg1.isExtended(),
.b = ops.reg2.isExtended(),
});
encoder.opcode_1byte(opc);
if (imm <= math.maxInt(i8)) {
encoder.modRm_SIBDisp8(ops.reg1.lowId());
encoder.sib_scaleIndexBaseDisp8(scale, Register.rcx.lowId(), ops.reg2.lowId());
encoder.disp8(@intCast(i8, imm));
} else {
encoder.modRm_SIBDisp32(ops.reg1.lowId());
encoder.sib_scaleIndexBaseDisp32(scale, Register.rcx.lowId(), ops.reg2.lowId());
encoder.disp32(imm);
}
}
fn mirArithScaleDst(emit: *Emit, tag: Mir.Inst.Tag, inst: Mir.Inst.Index) InnerError!void {
const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]);
const scale = ops.flags;
const imm = emit.mir.instructions.items(.data)[inst].imm;
if (ops.reg2 == .none) {
// OP [reg1 + scale*rax + 0], imm32
const opcode = getArithOpCode(tag, .mi);
const opc = if (ops.reg1.size() == 8) opcode.opc - 1 else opcode.opc;
const encoder = try Encoder.init(emit.code, 8);
encoder.rex(.{
.w = ops.reg1.size() == 64,
.b = ops.reg1.isExtended(),
});
encoder.opcode_1byte(opc);
encoder.modRm_SIBDisp0(opcode.modrm_ext);
encoder.sib_scaleIndexBase(scale, Register.rax.lowId(), ops.reg1.lowId());
if (imm <= math.maxInt(i8)) {
encoder.imm8(@intCast(i8, imm));
} else if (imm <= math.maxInt(i16)) {
encoder.imm16(@intCast(i16, imm));
} else {
encoder.imm32(imm);
}
return;
}
// OP [reg1 + scale*rax + imm32], reg2
const opcode = getArithOpCode(tag, .mr);
const opc = if (ops.reg1.size() == 8) opcode.opc - 1 else opcode.opc;
const encoder = try Encoder.init(emit.code, 8);
encoder.rex(.{
.w = ops.reg1.size() == 64,
.r = ops.reg2.isExtended(),
.b = ops.reg1.isExtended(),
});
encoder.opcode_1byte(opc);
if (imm <= math.maxInt(i8)) {
encoder.modRm_SIBDisp8(ops.reg2.lowId());
encoder.sib_scaleIndexBaseDisp8(scale, Register.rax.lowId(), ops.reg1.lowId());
encoder.disp8(@intCast(i8, imm));
} else {
encoder.modRm_SIBDisp32(ops.reg2.lowId());
encoder.sib_scaleIndexBaseDisp32(scale, Register.rax.lowId(), ops.reg1.lowId());
encoder.disp32(imm);
}
}
fn mirArithScaleImm(emit: *Emit, tag: Mir.Inst.Tag, inst: Mir.Inst.Index) InnerError!void {
const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]);
const scale = ops.flags;
const payload = emit.mir.instructions.items(.data)[inst].payload;
const imm_pair = emit.mir.extraData(Mir.ImmPair, payload).data;
const opcode = getArithOpCode(tag, .mi);
const opc = if (ops.reg1.size() == 8) opcode.opc - 1 else opcode.opc;
const encoder = try Encoder.init(emit.code, 2);
encoder.rex(.{
.w = ops.reg1.size() == 64,
.b = ops.reg1.isExtended(),
});
encoder.opcode_1byte(opc);
if (imm_pair.dest_off <= math.maxInt(i8)) {
encoder.modRm_SIBDisp8(opcode.modrm_ext);
encoder.sib_scaleIndexBaseDisp8(scale, Register.rax.lowId(), ops.reg1.lowId());
encoder.disp8(@intCast(i8, imm_pair.dest_off));
} else {
encoder.modRm_SIBDisp32(opcode.modrm_ext);
encoder.sib_scaleIndexBaseDisp32(scale, Register.rax.lowId(), ops.reg1.lowId());
encoder.disp32(imm_pair.dest_off);
}
encoder.imm32(imm_pair.operand);
}
fn mirMovabs(emit: *Emit, inst: Mir.Inst.Index) InnerError!void {
const tag = emit.mir.instructions.items(.tag)[inst];
assert(tag == .movabs);
const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]);
const encoder = try Encoder.init(emit.code, 10);
const is_64 = blk: {
if (ops.flags == 0b00) {
// movabs reg, imm64
const opc: u8 = if (ops.reg1.size() == 8) 0xb0 else 0xb8;
if (ops.reg1.size() == 64) {
encoder.rex(.{
.w = true,
.b = ops.reg1.isExtended(),
});
encoder.opcode_withReg(opc, ops.reg1.lowId());
break :blk true;
}
break :blk false;
}
if (ops.reg1 == .none) {
// movabs moffs64, rax
const opc: u8 = if (ops.reg2.size() == 8) 0xa2 else 0xa3;
encoder.rex(.{
.w = ops.reg2.size() == 64,
});
encoder.opcode_1byte(opc);
break :blk ops.reg2.size() == 64;
} else {
// movabs rax, moffs64
const opc: u8 = if (ops.reg2.size() == 8) 0xa0 else 0xa1;
encoder.rex(.{
.w = ops.reg1.size() == 64,
});
encoder.opcode_1byte(opc);
break :blk ops.reg1.size() == 64;
}
};
if (is_64) {
const payload = emit.mir.instructions.items(.data)[inst].payload;
const imm64 = emit.mir.extraData(Mir.Imm64, payload).data;
encoder.imm64(imm64.decode());
} else {
const imm = emit.mir.instructions.items(.data)[inst].imm;
if (imm <= math.maxInt(i8)) {
encoder.imm8(@intCast(i8, imm));
} else if (imm <= math.maxInt(i16)) {
encoder.imm16(@intCast(i16, imm));
} else {
encoder.imm32(imm);
}
}
}
fn mirIMulComplex(emit: *Emit, inst: Mir.Inst.Index) InnerError!void {
const tag = emit.mir.instructions.items(.tag)[inst];
assert(tag == .imul_complex);
const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]);
switch (ops.flags) {
0b00 => {
const encoder = try Encoder.init(emit.code, 4);
encoder.rex(.{
.w = ops.reg1.size() == 64,
.r = ops.reg1.isExtended(),
.b = ops.reg2.isExtended(),
});
encoder.opcode_2byte(0x0f, 0xaf);
encoder.modRm_direct(ops.reg1.lowId(), ops.reg2.lowId());
},
0b10 => {
const imm = emit.mir.instructions.items(.data)[inst].imm;
const opc: u8 = if (imm <= math.maxInt(i8)) 0x6b else 0x69;
const encoder = try Encoder.init(emit.code, 7);
encoder.rex(.{
.w = ops.reg1.size() == 64,
.r = ops.reg1.isExtended(),
.b = ops.reg1.isExtended(),
});
encoder.opcode_1byte(opc);
encoder.modRm_direct(ops.reg1.lowId(), ops.reg2.lowId());
if (imm <= math.maxInt(i8)) {
encoder.imm8(@intCast(i8, imm));
} else if (imm <= math.maxInt(i16)) {
encoder.imm16(@intCast(i16, imm));
} else {
encoder.imm32(imm);
}
},
else => return emit.fail("TODO implement imul", .{}),
}
}
fn mirLea(emit: *Emit, inst: Mir.Inst.Index) InnerError!void {
const tag = emit.mir.instructions.items(.tag)[inst];
assert(tag == .lea);
const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]);
assert(ops.flags == 0b01);
const imm = emit.mir.instructions.items(.data)[inst].imm;
if (imm == 0) {
const encoder = try Encoder.init(emit.code, 3);
encoder.rex(.{
.w = ops.reg1.size() == 64,
.r = ops.reg1.isExtended(),
.b = ops.reg2.isExtended(),
});
encoder.opcode_1byte(0x8d);
encoder.modRm_indirectDisp0(ops.reg1.lowId(), ops.reg2.lowId());
} else if (imm <= math.maxInt(i8)) {
const encoder = try Encoder.init(emit.code, 4);
encoder.rex(.{
.w = ops.reg1.size() == 64,
.r = ops.reg1.isExtended(),
.b = ops.reg2.isExtended(),
});
encoder.opcode_1byte(0x8d);
encoder.modRm_indirectDisp8(ops.reg1.lowId(), ops.reg2.lowId());
encoder.disp8(@intCast(i8, imm));
} else {
const encoder = try Encoder.init(emit.code, 7);
encoder.rex(.{
.w = ops.reg1.size() == 64,
.r = ops.reg1.isExtended(),
.b = ops.reg2.isExtended(),
});
encoder.opcode_1byte(0x8d);
encoder.modRm_indirectDisp32(ops.reg1.lowId(), ops.reg2.lowId());
encoder.disp32(imm);
}
}
fn mirLeaRip(emit: *Emit, inst: Mir.Inst.Index) InnerError!void {
const tag = emit.mir.instructions.items(.tag)[inst];
assert(tag == .lea_rip);
const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]);
const start_offset = emit.code.items.len;
const encoder = try Encoder.init(emit.code, 7);
encoder.rex(.{
.w = ops.reg1.size() == 64,
.r = ops.reg1.isExtended(),
});
encoder.opcode_1byte(0x8d);
encoder.modRm_RIPDisp32(ops.reg1.lowId());
const end_offset = emit.code.items.len;
if (@truncate(u1, ops.flags) == 0b0) {
const payload = emit.mir.instructions.items(.data)[inst].payload;
const imm = emit.mir.extraData(Mir.Imm64, payload).data.decode();
encoder.disp32(@intCast(i32, @intCast(i64, imm) - @intCast(i64, end_offset - start_offset + 4)));
} else {
const got_entry = emit.mir.instructions.items(.data)[inst].got_entry;
encoder.disp32(0);
if (emit.bin_file.cast(link.File.MachO)) |macho_file| {
// TODO I think the reloc might be in the wrong place.
const decl = macho_file.active_decl.?;
try decl.link.macho.relocs.append(emit.bin_file.allocator, .{
.offset = @intCast(u32, end_offset),
.target = .{ .local = got_entry },
.addend = 0,
.subtractor = null,
.pcrel = true,
.length = 2,
.@"type" = @enumToInt(std.macho.reloc_type_x86_64.X86_64_RELOC_GOT),
});
} else {
return emit.fail("TODO implement lea_rip for linking backends different than MachO", .{});
}
}
}
fn mirCallExtern(emit: *Emit, inst: Mir.Inst.Index) InnerError!void {
const tag = emit.mir.instructions.items(.tag)[inst];
assert(tag == .call_extern);
const n_strx = emit.mir.instructions.items(.data)[inst].extern_fn;
const offset = blk: {
const offset = @intCast(u32, emit.code.items.len + 1);
// callq
const encoder = try Encoder.init(emit.code, 5);
encoder.opcode_1byte(0xe8);
encoder.imm32(0x0);
break :blk offset;
};
if (emit.bin_file.cast(link.File.MachO)) |macho_file| {
// Add relocation to the decl.
try macho_file.active_decl.?.link.macho.relocs.append(emit.bin_file.allocator, .{
.offset = offset,
.target = .{ .global = n_strx },
.addend = 0,
.subtractor = null,
.pcrel = true,
.length = 2,
.@"type" = @enumToInt(std.macho.reloc_type_x86_64.X86_64_RELOC_BRANCH),
});
} else {
return emit.fail("TODO implement call_extern for linking backends different than MachO", .{});
}
}
fn mirDbgLine(emit: *Emit, inst: Mir.Inst.Index) InnerError!void {
const tag = emit.mir.instructions.items(.tag)[inst];
assert(tag == .dbg_line);
const payload = emit.mir.instructions.items(.data)[inst].payload;
const dbg_line_column = emit.mir.extraData(Mir.DbgLineColumn, payload).data;
try emit.dbgAdvancePCAndLine(dbg_line_column.line, dbg_line_column.column);
}
fn dbgAdvancePCAndLine(emit: *Emit, line: u32, column: u32) InnerError!void {
const delta_line = @intCast(i32, line) - @intCast(i32, emit.prev_di_line);
const delta_pc: usize = emit.code.items.len - emit.prev_di_pc;
switch (emit.debug_output) {
.dwarf => |dbg_out| {
// TODO Look into using the DWARF special opcodes to compress this data.
// It lets you emit single-byte opcodes that add different numbers to
// both the PC and the line number at the same time.
try dbg_out.dbg_line.ensureUnusedCapacity(11);
dbg_out.dbg_line.appendAssumeCapacity(DW.LNS.advance_pc);
leb128.writeULEB128(dbg_out.dbg_line.writer(), delta_pc) catch unreachable;
if (delta_line != 0) {
dbg_out.dbg_line.appendAssumeCapacity(DW.LNS.advance_line);
leb128.writeILEB128(dbg_out.dbg_line.writer(), delta_line) catch unreachable;
}
dbg_out.dbg_line.appendAssumeCapacity(DW.LNS.copy);
emit.prev_di_pc = emit.code.items.len;
emit.prev_di_line = line;
emit.prev_di_column = column;
emit.prev_di_pc = emit.code.items.len;
},
.plan9 => |dbg_out| {
if (delta_pc <= 0) return; // only do this when the pc changes
// we have already checked the target in the linker to make sure it is compatable
const quant = @import("../../link/Plan9/aout.zig").getPCQuant(emit.target.cpu.arch) catch unreachable;
// increasing the line number
try @import("../../link/Plan9.zig").changeLine(dbg_out.dbg_line, delta_line);
// increasing the pc
const d_pc_p9 = @intCast(i64, delta_pc) - quant;
if (d_pc_p9 > 0) {
// minus one because if its the last one, we want to leave space to change the line which is one quanta
try dbg_out.dbg_line.append(@intCast(u8, @divExact(d_pc_p9, quant) + 128) - quant);
if (dbg_out.pcop_change_index.*) |pci|
dbg_out.dbg_line.items[pci] += 1;
dbg_out.pcop_change_index.* = @intCast(u32, dbg_out.dbg_line.items.len - 1);
} else if (d_pc_p9 == 0) {
// we don't need to do anything, because adding the quant does it for us
} else unreachable;
if (dbg_out.start_line.* == null)
dbg_out.start_line.* = emit.prev_di_line;
dbg_out.end_line.* = line;
// only do this if the pc changed
emit.prev_di_line = line;
emit.prev_di_column = column;
emit.prev_di_pc = emit.code.items.len;
},
.none => {},
}
}
fn mirDbgPrologueEnd(emit: *Emit, inst: Mir.Inst.Index) InnerError!void {
const tag = emit.mir.instructions.items(.tag)[inst];
assert(tag == .dbg_prologue_end);
switch (emit.debug_output) {
.dwarf => |dbg_out| {
try dbg_out.dbg_line.append(DW.LNS.set_prologue_end);
try emit.dbgAdvancePCAndLine(emit.prev_di_line, emit.prev_di_column);
},
.plan9 => {},
.none => {},
}
}
fn mirDbgEpilogueBegin(emit: *Emit, inst: Mir.Inst.Index) InnerError!void {
const tag = emit.mir.instructions.items(.tag)[inst];
assert(tag == .dbg_epilogue_begin);
switch (emit.debug_output) {
.dwarf => |dbg_out| {
try dbg_out.dbg_line.append(DW.LNS.set_epilogue_begin);
try emit.dbgAdvancePCAndLine(emit.prev_di_line, emit.prev_di_column);
},
.plan9 => {},
.none => {},
}
}
fn mirArgDbgInfo(emit: *Emit, inst: Mir.Inst.Index) InnerError!void {
const tag = emit.mir.instructions.items(.tag)[inst];
assert(tag == .arg_dbg_info);
const payload = emit.mir.instructions.items(.data)[inst].payload;
const arg_dbg_info = emit.mir.extraData(Mir.ArgDbgInfo, payload).data;
const mcv = emit.mir.function.args[arg_dbg_info.arg_index];
try emit.genArgDbgInfo(arg_dbg_info.air_inst, mcv);
}
fn genArgDbgInfo(emit: *Emit, inst: Air.Inst.Index, mcv: MCValue) !void {
const ty_str = emit.mir.function.air.instructions.items(.data)[inst].ty_str;
const zir = &emit.mir.function.mod_fn.owner_decl.getFileScope().zir;
const name = zir.nullTerminatedString(ty_str.str);
const name_with_null = name.ptr[0 .. name.len + 1];
const ty = emit.mir.function.air.getRefType(ty_str.ty);
switch (mcv) {
.register => |reg| {
switch (emit.debug_output) {
.dwarf => |dbg_out| {
try dbg_out.dbg_info.ensureUnusedCapacity(3);
dbg_out.dbg_info.appendAssumeCapacity(link.File.Elf.abbrev_parameter);
dbg_out.dbg_info.appendSliceAssumeCapacity(&[2]u8{ // DW.AT.location, DW.FORM.exprloc
1, // ULEB128 dwarf expression length
reg.dwarfLocOp(),
});
try dbg_out.dbg_info.ensureUnusedCapacity(5 + name_with_null.len);
try emit.addDbgInfoTypeReloc(ty); // DW.AT.type, DW.FORM.ref4
dbg_out.dbg_info.appendSliceAssumeCapacity(name_with_null); // DW.AT.name, DW.FORM.string
},
.plan9 => {},
.none => {},
}
},
.stack_offset => {
switch (emit.debug_output) {
.dwarf => {},
.plan9 => {},
.none => {},
}
},
else => {},
}
}
/// Adds a Type to the .debug_info at the current position. The bytes will be populated later,
/// after codegen for this symbol is done.
fn addDbgInfoTypeReloc(emit: *Emit, ty: Type) !void {
switch (emit.debug_output) {
.dwarf => |dbg_out| {
assert(ty.hasCodeGenBits());
const index = dbg_out.dbg_info.items.len;
try dbg_out.dbg_info.resize(index + 4); // DW.AT.type, DW.FORM.ref4
const gop = try dbg_out.dbg_info_type_relocs.getOrPut(emit.bin_file.allocator, ty);
if (!gop.found_existing) {
gop.value_ptr.* = .{
.off = undefined,
.relocs = .{},
};
}
try gop.value_ptr.relocs.append(emit.bin_file.allocator, @intCast(u32, index));
},
.plan9 => {},
.none => {},
}
} | src/arch/x86_64/Emit.zig |
const std = @import("std");
const Context = @import("context.zig").Context;
const SourceRange = @import("context.zig").SourceRange;
const BuiltinEnumValue = @import("builtins.zig").BuiltinEnumValue;
fn printSourceRange(out: std.io.StreamSource.OutStream, contents: []const u8, source_range: SourceRange) !void {
try out.writeAll(contents[source_range.loc0.index..source_range.loc1.index]);
}
fn printErrorMessage(out: std.io.StreamSource.OutStream, maybe_source_range: ?SourceRange, contents: []const u8, comptime fmt: []const u8, args: var) !void {
comptime var arg_index: usize = 0;
inline for (fmt) |ch| {
if (ch == '%') {
// source range
try printSourceRange(out, contents, args[arg_index]);
arg_index += 1;
} else if (ch == '#') {
// string
try out.writeAll(args[arg_index]);
arg_index += 1;
} else if (ch == '<') {
// the maybe_source_range that was passed in
if (maybe_source_range) |source_range| {
try printSourceRange(out, contents, source_range);
} else {
try out.writeByte('?');
}
} else if (ch == '|') {
// list of enum values
const values: []const BuiltinEnumValue = args[arg_index];
for (values) |value, i| {
if (i > 0) try out.writeAll(", ");
try out.writeByte('\'');
try out.writeAll(value.label);
try out.writeByte('\'');
switch (value.payload_type) {
.none => {},
.f32 => try out.writeAll("(number)"),
}
}
arg_index += 1;
} else {
try out.writeByte(ch);
}
}
}
fn printError(ctx: Context, maybe_source_range: ?SourceRange, comptime fmt: []const u8, args: var) !void {
const KNRM = if (ctx.errors_color) "\x1B[0m" else "";
const KBOLD = if (ctx.errors_color) "\x1B[1m" else "";
const KRED = if (ctx.errors_color) "\x1B[31m" else "";
const KYEL = if (ctx.errors_color) "\x1B[33m" else "";
const KWHITE = if (ctx.errors_color) "\x1B[37m" else "";
const out = ctx.errors_out;
const source_range = maybe_source_range orelse {
// we don't know where in the source file the error occurred
try out.print("{}{}{}: {}", .{ KYEL, KBOLD, ctx.source.filename, KWHITE });
try printErrorMessage(out, null, ctx.source.contents, fmt, args);
try out.print("{}\n\n", .{KNRM});
return;
};
// we want to echo the problematic line from the source file.
// look backward to find the start of the line
var i: usize = source_range.loc0.index;
while (i > 0) : (i -= 1) {
if (ctx.source.contents[i - 1] == '\n') {
break;
}
}
const start = i;
// look forward to find the end of the line
i = source_range.loc0.index;
while (i < ctx.source.contents.len) : (i += 1) {
if (ctx.source.contents[i] == '\n' or ctx.source.contents[i] == '\r') {
break;
}
}
const end = i;
const line_num = source_range.loc0.line + 1;
const column_num = source_range.loc0.index - start + 1;
// print source filename, line number, and column number
try out.print("{}{}{}:{}:{}: {}", .{ KYEL, KBOLD, ctx.source.filename, line_num, column_num, KWHITE });
// print the error message
try printErrorMessage(out, maybe_source_range, ctx.source.contents, fmt, args);
try out.print("{}\n\n", .{KNRM});
if (source_range.loc0.index == source_range.loc1.index) {
// if there's no span, it's probably an "expected X, found end of file" error.
// there's nothing to echo (but we still want to show the line number)
return;
}
// echo the source line
try out.print("{}\n", .{ctx.source.contents[start..end]});
// show arrows pointing at the problematic span
i = start;
while (i < source_range.loc0.index) : (i += 1) {
try out.print(" ", .{});
}
try out.print("{}{}", .{ KRED, KBOLD });
while (i < end and i < source_range.loc1.index) : (i += 1) {
try out.print("^", .{});
}
try out.print("{}\n", .{KNRM});
}
pub fn fail(ctx: Context, maybe_source_range: ?SourceRange, comptime fmt: []const u8, args: var) error{Failed} {
printError(ctx, maybe_source_range, fmt, args) catch {};
return error.Failed;
} | src/zangscript/fail.zig |
const std = @import("std");
const assert = std.debug.assert;
pub const IntBuf = struct {
data: [4096]i32,
pw: usize,
pr: usize,
pub fn init() IntBuf {
var self = IntBuf{
.data = undefined,
.pw = 0,
.pr = 0,
};
return self;
}
pub fn empty(self: IntBuf) bool {
return (self.pr >= self.pw);
}
pub fn read(self: IntBuf, pos: usize) ?i32 {
if (pos >= self.pw) {
return null;
}
return self.data[pos];
}
pub fn write(self: *IntBuf, pos: usize, value: i32) void {
self.data[pos] = value;
}
pub fn get(self: *IntBuf) ?i32 {
if (self.empty()) {
return null;
}
const value = self.data[self.pr];
self.pr += 1;
if (self.empty()) {
self.clear();
}
return value;
}
pub fn put(self: *IntBuf, value: i32) void {
self.data[self.pw] = value;
self.pw += 1;
}
pub fn clear(self: *IntBuf) void {
self.pr = 0;
self.pw = 0;
}
};
pub const Computer = struct {
rom: IntBuf,
ram: IntBuf,
pc: usize,
inputs: IntBuf,
outputs: IntBuf,
reentrant: bool,
halted: bool,
const OP = enum(u32) {
ADD = 1,
MUL = 2,
RDSV = 3,
PRINT = 4,
JIT = 5,
JIF = 6,
CLT = 7,
CEQ = 8,
HALT = 99,
};
const MODE = enum(u32) {
POSITION = 0,
IMMEDIATE = 1,
};
pub fn init(str: []const u8) Computer {
var self = Computer{
.rom = undefined,
.ram = undefined,
.pc = 0,
.inputs = undefined,
.outputs = undefined,
.reentrant = false,
.halted = false,
};
var it = std.mem.split(u8, str, ",");
while (it.next()) |what| {
const instr = std.fmt.parseInt(i32, what, 10) catch unreachable;
self.rom.put(instr);
}
self.clear();
return self;
}
pub fn deinit(self: *Computer) void {
_ = self;
}
pub fn get(self: Computer, pos: usize) i32 {
return self.ram.read(pos);
}
pub fn set(self: *Computer, pos: usize, val: i32) void {
self.ram.write(pos, val);
}
pub fn clear(self: *Computer) void {
// std.debug.warn("RESET\n");
self.ram = self.rom;
self.halted = false;
self.pc = 0;
self.inputs.clear();
self.outputs.clear();
}
pub fn enqueueInput(self: *Computer, input: i32) void {
// std.debug.warn("ENQUEUE {}\n", input);
self.inputs.put(input);
}
pub fn setReentrant(self: *Computer) void {
self.reentrant = true;
}
pub fn getOutput(self: *Computer) ?i32 {
if (self.outputs.empty()) {
return null;
}
const result = self.outputs.get().?;
return result;
}
pub fn run(self: *Computer) ?i32 {
if (!self.reentrant) self.clear();
while (!self.halted) {
var instr: u32 = @intCast(u32, self.ram.read(self.pc + 0).?);
// std.debug.warn("instr: {}\n", instr);
const op = @intToEnum(OP, instr % 100);
instr /= 100;
const m1 = @intToEnum(MODE, instr % 10);
instr /= 10;
const m2 = @intToEnum(MODE, instr % 10);
instr /= 10;
// const m3 = @intToEnum(MODE, instr % 10);
instr /= 10;
switch (op) {
OP.HALT => {
// std.debug.warn("{} | HALT\n", self.pc);
self.halted = true;
break;
},
OP.ADD => {
const v1 = self.decode(1, m1);
const v2 = self.decode(2, m2);
const p3 = self.ram.read(self.pc + 3).?;
// std.debug.warn("{} | ADD: {} = {} + {}\n", self.pc, p3, v1, v2);
self.ram.write(@intCast(usize, p3), v1 + v2);
self.pc += 4;
},
OP.MUL => {
const v1 = self.decode(1, m1);
const v2 = self.decode(2, m2);
const p3 = self.ram.read(self.pc + 3).?;
// std.debug.warn("{} | MUL: {} = {} * {}\n", self.pc, p3, v1, v2);
self.ram.write(@intCast(usize, p3), v1 * v2);
self.pc += 4;
},
OP.RDSV => {
if (self.inputs.empty()) {
// std.debug.warn("{} | RDSV: PAUSED\n", self.pc);
break;
}
const p1 = self.ram.read(self.pc + 1).?;
// std.debug.warn("{} | RDSV: {} = {}\n", self.pc, p1, self.inputs.get());
self.ram.write(@intCast(usize, p1), self.inputs.get().?);
self.pc += 2;
},
OP.PRINT => {
const v1 = self.decode(1, m1);
// std.debug.warn("{} | PRINT: {}\n", self.pc, v1);
self.outputs.put(v1);
self.pc += 2;
},
OP.JIT => {
const v1 = self.decode(1, m1);
const v2 = self.decode(2, m2);
// std.debug.warn("{} | JIT: {} {}\n", self.pc, v1, v2);
if (v1 == 0) {
self.pc += 3;
} else {
self.pc = @intCast(usize, v2);
}
},
OP.JIF => {
const v1 = self.decode(1, m1);
const v2 = self.decode(2, m2);
// std.debug.warn("{} | JIF: {} {}\n", self.pc, v1, v2);
if (v1 == 0) {
self.pc = @intCast(usize, v2);
} else {
self.pc += 3;
}
},
OP.CLT => {
const v1 = self.decode(1, m1);
const v2 = self.decode(2, m2);
const p3 = self.ram.read(self.pc + 3).?;
// std.debug.warn("{} | CLT: {} = {} LT {}\n", self.pc, p3, v1, v2);
// tried doing this way, got an error:
//
// const value: i32 = if (v1 < v2) 1 else 0;
// error: cannot store runtime value in type 'comptime_int'
//
var value: i32 = 0;
if (v1 < v2) value = 1;
self.ram.write(@intCast(usize, p3), value);
self.pc += 4;
},
OP.CEQ => {
const v1 = self.decode(1, m1);
const v2 = self.decode(2, m2);
const p3 = self.ram.read(self.pc + 3).?;
// std.debug.warn("{} | CEQ: {} = {} EQ {}\n", self.pc, p3, v1, v2);
var value: i32 = 0;
if (v1 == v2) value = 1;
self.ram.write(@intCast(usize, p3), value);
self.pc += 4;
},
}
}
return self.getOutput();
}
fn decode(self: Computer, pos: usize, mode: MODE) i32 {
const p = self.ram.read(self.pc + pos).?;
const v: i32 = switch (mode) {
MODE.POSITION => self.ram.read(@intCast(usize, p)).?,
MODE.IMMEDIATE => p,
};
return v;
}
}; | 2019/p07/computer.zig |
const std = @import("std");
const ArrayList = std.ArrayList;
const Allocator = std.mem.Allocator;
const Checksum = @import("./checksum.zig").Checksum;
/// A checksum implementation - using the CRC-32 algorithm.
pub fn Crc32() type {
return struct {
const Self = @This();
const ChecksumType = u32;
const default_crc32_val = 0xffffffff;
bytes: ArrayList(u8),
checksum: Checksum(ChecksumType),
checksum_value: ChecksumType,
allocator: *Allocator,
// static lookup table of 256 pre-generated constants
const crc32_tab = [_]u32{
0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D,
};
pub fn init(allocator: *Allocator) Self {
return Self{
.bytes = ArrayList(u8).init(allocator),
.checksum = Checksum(ChecksumType){
.reset_fn = reset,
.update_byte_array_range_fn = updateByteArrayRange,
.close_fn = close,
},
.checksum_value = default_crc32_val,
.allocator = allocator,
};
}
fn reset(checksum: *Checksum(ChecksumType)) void {
const self = @fieldParentPtr(Self, "checksum", checksum);
self.checksum_value = default_crc32_val;
self.bytes.shrink(0);
}
fn close(checksum: *Checksum(ChecksumType)) void {
const self = @fieldParentPtr(Self, "checksum", checksum);
self.bytes.deinit();
}
/// Source: https://docs.microsoft.com/en-us/openspecs/office_protocols/ms-abs/06966aa2-70da-4bf9-8448-3355f277cd77?redirectedfrom=MSDN
fn updateByteArrayRange(checksum: *Checksum(ChecksumType), bs: []const u8, offset: usize, len: usize) !void {
const self = @fieldParentPtr(Self, "checksum", checksum);
for (bs[offset .. offset + len]) |b| {
try self.bytes.append(b);
}
var crc: ChecksumType = default_crc32_val;
for (self.bytes.items) |b, idx| {
crc = crc32_tab[(crc & 0xff) ^ b] ^ (crc >> 8);
}
self.checksum_value = ~crc;
}
};
} | src/crc-32.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const List = std.ArrayList;
const Map = std.AutoHashMap;
const StrMap = std.StringHashMap;
const BitSet = std.DynamicBitSet;
const Str = []const u8;
const util = @import("util.zig");
const gpa = util.gpa;
const data = @embedFile("../data/day03.txt");
const BIT_COUNT = 12;
pub fn main() !void {
print("{}\n", .{task1()});
print("{}\n", .{task2()});
}
fn task1() u64 {
var lines = tokenize(u8, data, "\n");
var totalLineCount: u64 = 0;
var gammaRate: u64 = 0;
var bitCount: [BIT_COUNT]u32 = .{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
while (lines.next()) |line| {
var bitIndex: u8 = 0;
for (line) |num| {
bitCount[bitIndex] += toSortaBinary(num);
bitIndex = (bitIndex + 1) % 12;
}
totalLineCount += 1;
}
const cutOff = totalLineCount / 2;
for (bitCount) |indexValue, index| {
if (indexValue > cutOff) {
gammaRate += std.math.pow(u64, 2, BIT_COUNT - index - 1);
}
}
const epsilonRate = ~@intCast(u12, gammaRate);
return gammaRate * epsilonRate; // 5208 * 2982
}
fn task2() u64 {
var lines = tokenize(u8, data, "\n");
while (lines.next()) |line| {
_ = line;
}
return 0;
}
fn toSortaBinary(num: u8) u8 {
return num - 48;
}
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const indexOf = std.mem.indexOfScalar;
const indexOfAny = std.mem.indexOfAny;
const indexOfStr = std.mem.indexOfPosLinear;
const lastIndexOf = std.mem.lastIndexOfScalar;
const lastIndexOfAny = std.mem.lastIndexOfAny;
const lastIndexOfStr = std.mem.lastIndexOfLinear;
const trim = std.mem.trim;
const sliceMin = std.mem.min;
const sliceMax = std.mem.max;
const parseInt = std.fmt.parseInt;
const parseFloat = std.fmt.parseFloat;
const min = std.math.min;
const min3 = std.math.min3;
const max = std.math.max;
const max3 = std.math.max3;
const print = std.debug.print;
const assert = std.debug.assert;
const sort = std.sort.sort;
const asc = std.sort.asc;
const desc = std.sort.desc; | src/day03.zig |
const std = @import("std");
const builtin = @import("builtin");
const Gigatron = @import("gigatron.zig");
const win32 = @import("win32.zig");
const gl = @import("win32_gl.zig");
pub fn hrErr(hresult: win32.foundation.HRESULT) !void {
if(hresult >= 0) return;
std.log.err("HRESULT error: 0x{X:0>8}\n", .{@bitCast(u32, hresult)});
return error.HResultError;
}
pub fn hrStatus(hresult: win32.foundation.HRESULT) !win32.foundation.HRESULT {
if(hresult >= 0) return hresult;
std.log.err("HRESULT error: 0x{X:0>8}\n", .{@bitCast(u32, hresult)});
return error.HResultError;
}
pub fn intErr(atom: anytype) !@TypeOf(atom) {
if(atom != 0) return atom;
const err = win32.foundation.GetLastError();
const err_code = @truncate(u16, @enumToInt(err));
std.log.err("INT error: {}, last error: 0x{X:0>4} - {s}\n", .{atom, err_code, err});
return error.IntError;
}
pub fn boolErr(b: win32.foundation.BOOL) !void {
if(b != 0) return;
const err = win32.foundation.GetLastError();
const err_code = @truncate(u16, @enumToInt(err));
std.log.err("BOOL error: 0x{X:0>4} - {s}\n", .{err_code, err});
return error.BoolError;
}
//@NOTE: Calls to this function may force thread
// syncs that could negatively impact performance.
pub fn glErr(v: void) !void {
_ = v;
const err = gl.glGetError();
if(err == gl.GL_NO_ERROR) return;
return switch(err) {
1280 => error.GL_INVALID_ENUM,
1281 => error.GL_INVALID_VALUE,
1282 => error.GL_INVALID_OPERATION,
1283 => error.GL_STACK_OVERFLOW,
1284 => error.GL_STACK_UNDERFLOW,
1285 => error.GL_OUT_OF_MEMORY,
else => {
std.debug.panic("Unknown GL Error Code: {}\n", .{err});
},
};
}
//@TODO: Allow adjustable emulation speed
//@TODO: We want to be able to track multiple windows and allow them to use instance fields
// instead of globals. We *could* do https://devblogs.microsoft.com/oldnewthing/20140203-00/?p=1893
// but keep in mind we need to save the hWnd in the CREATE message for that to work.
// Alternatively we can just have a global for each window.
//
// Main window: vga output, blinkenlights
// Debugger: step, watch, disassembly, ram view, rom view, register view, babelfish data view
const gigatron_clock_rate = Gigatron.clock_rate;
var main_window: MainWindow = undefined;
var sound: Sound = undefined;
//@TODO: Allow for selectable resolution, fullscreen, handle HiDPI
//Handles main display and blinkenlights
const MainWindow = struct {
const wf = win32.foundation;
const wg = win32.graphics;
const wnm = win32.ui.windows_and_messaging;
hModule: wf.HINSTANCE,
wndClass: wnm.WNDCLASSEXW,
hWnd: wf.HWND,
hDC: wg.gdi.HDC,
wglRC: wg.open_gl.HGLRC,
gl_texture: gl.GLuint,
frame_buffer: [vid_width * (vid_height + blinken_height)]RGB888,
buttons: *Gigatron.Buttons,
babelfish: *Gigatron.BabelFish,
const vid_width = Gigatron.VgaMonitor.vid_width;
const vid_height = Gigatron.VgaMonitor.vid_height;
const blinken_height = 10;
const RGB888 = packed struct {
r: u8,
g: u8,
b: u8,
};
fn init(b: *Gigatron.Buttons, bf: *Gigatron.BabelFish) !void {
const self = &main_window;
self.buttons = b;
self.babelfish = bf;
self.hModule = win32.system.library_loader.GetModuleHandleW(null) orelse return error.InvalidModuleHanlde;
self.wndClass = std.mem.zeroes(wnm.WNDCLASSEXW);
self.wndClass.cbSize = @sizeOf(wnm.WNDCLASSEXW);
self.wndClass.style = wnm.CS_OWNDC;
self.wndClass.lpfnWndProc = winProc;
self.wndClass.hInstance = @ptrCast(
wf.HINSTANCE,
self.hModule,
);
self.wndClass.hCursor = wnm.LoadCursorW(
null,
wnm.IDC_ARROW,
);
self.wndClass.hbrBackground = @ptrCast(
wg.gdi.HBRUSH,
wg.gdi.GetStockObject(wg.gdi.BLACK_BRUSH),
);
self.wndClass.lpszClassName = std.unicode.utf8ToUtf16LeStringLiteral("ZGE");
_ = try intErr(wnm.RegisterClassExW(&self.wndClass));
var display_rect = wf.RECT{
.left = 0,
.top = 0,
.right = vid_width,
.bottom = (vid_height + blinken_height),
};
//@TODO: use GetSystemMetrics instead of AdjustWindowRectEx because the latter is stupid. Alternatively
// just create the window and then resize it afterwards by the difference between clientrect and its rect.
try boolErr(wnm.AdjustWindowRectEx(
&display_rect,
wnm.WS_CAPTION,
win32.zig.FALSE,
@intToEnum(wnm.WINDOW_EX_STYLE, 0),
));
const window_style = @intToEnum(wnm.WINDOW_STYLE,
@enumToInt(wnm.WS_OVERLAPPED) |
@enumToInt(wnm.WS_MINIMIZEBOX) |
@enumToInt(wnm.WS_SYSMENU)
);
self.hWnd = wnm.CreateWindowExW(
@intToEnum(wnm.WINDOW_EX_STYLE, 0),
self.wndClass.lpszClassName,
std.unicode.utf8ToUtf16LeStringLiteral("Zig Gigatron Emulator"), //why not Zigatron? Because that's tacky.
window_style,
wnm.CW_USEDEFAULT,
wnm.CW_USEDEFAULT,
display_rect.right - display_rect.left,
display_rect.bottom - display_rect.top,
null,
null,
@ptrCast(wf.HINSTANCE, self.hModule),
null
) orelse return error.CreateWindowFailed;
errdefer _ = wnm.DestroyWindow(self.hWnd);
//We're going to use OpenGL to put a simple frame buffer on the screen because
// frankly, it's the simplest way.
self.hDC = wg.gdi.GetDC(self.hWnd) orelse return error.InvalidDc;
errdefer _ = wg.gdi.ReleaseDC(self.hWnd, self.hDC);
var pfd = std.mem.zeroes(wg.open_gl.PIXELFORMATDESCRIPTOR);
pfd.nSize = @sizeOf(wg.open_gl.PIXELFORMATDESCRIPTOR);
pfd.nVersion = 1;
pfd.dwFlags =
wg.gdi.PFD_DRAW_TO_WINDOW
| wg.gdi.PFD_SUPPORT_OPENGL
| wg.gdi.PFD_DOUBLEBUFFER
| wg.gdi.PFD_TYPE_RGBA
;
pfd.cColorBits = 24;
pfd.cDepthBits = 0;
pfd.iLayerType = wg.gdi.PFD_MAIN_PLANE;
const pfi = try intErr(wg.open_gl.ChoosePixelFormat(self.hDC, &pfd));
try boolErr(wg.open_gl.SetPixelFormat(self.hDC, pfi, &pfd));
self.wglRC = wg.open_gl.wglCreateContext(self.hDC) orelse return error.CreateGlContextFailure;
errdefer _ = wg.open_gl.wglDeleteContext(self.wglRC);
try boolErr(wg.open_gl.wglMakeCurrent(self.hDC, self.wglRC));
try glErr(gl.glGenTextures(1, &self.gl_texture));
//return indicates if window is already visible or not, we don't care.
_ = wnm.ShowWindow(self.hWnd, wnm.SW_SHOW);
//This disables vsync, assuming the driver isn't forcing it
// if we get forced to vsync then missed frames are likely.
// We should probably do something about that, like run
// the display copy in a different thread.
const wglSwapIntervalEXT_proc_addr = wg.open_gl.wglGetProcAddress("wglSwapIntervalEXT") orelse return error.GetProcAddressFailure;
const wglSwapIntervalEXT = @intToPtr(
gl.PFNWGLSWAPINTERVALEXTPROC,
@ptrToInt(wglSwapIntervalEXT_proc_addr)
).?;
try boolErr(wglSwapIntervalEXT(0));
}
//Ye olde WNDPROC
pub fn winProc(
hWnd: wf.HWND,
uMsg: c_uint,
wParam: wf.WPARAM,
lParam: wf.LPARAM
) callconv(std.os.windows.WINAPI) wf.LRESULT {
const wkm = win32.ui.input.keyboard_and_mouse;
const self = &main_window;
//@TODO: actual gamepads, configurable controls
switch(uMsg) {
wnm.WM_CLOSE => win32.system.threading.ExitProcess(1),
wnm.WM_SYSKEYDOWN,
wnm.WM_KEYDOWN => {
const key_param = @intToEnum(wkm.VIRTUAL_KEY, wParam);
switch(key_param) {
wkm.VK_UP => self.buttons.up = 0,
wkm.VK_DOWN => self.buttons.down = 0,
wkm.VK_LEFT => self.buttons.left = 0,
wkm.VK_RIGHT => self.buttons.right = 0,
wkm.VK_NEXT => self.buttons.select = 0, //pg down
wkm.VK_PRIOR => self.buttons.start = 0, //pg up
wkm.VK_HOME,
wkm.VK_INSERT => self.buttons.b = 0, //home or insert
wkm.VK_END,
wkm.VK_DELETE,
wkm.VK_BACK => self.buttons.a = 0, //end, del, bksp
//@TODO: this *should* be control+f3
wkm.VK_F3 => self.babelfish.controlKeyPress(.load),
else => return wnm.DefWindowProcW(hWnd, uMsg, wParam, lParam),
}
},
wnm.WM_SYSKEYUP,
wnm.WM_KEYUP => {
const key_param = @intToEnum(wkm.VIRTUAL_KEY, wParam);
switch(key_param) {
wkm.VK_UP => self.buttons.up = 1,
wkm.VK_DOWN => self.buttons.down = 1,
wkm.VK_LEFT => self.buttons.left = 1,
wkm.VK_RIGHT => self.buttons.right = 1,
wkm.VK_NEXT => self.buttons.select = 1, //pg down
wkm.VK_PRIOR => self.buttons.start = 1, //pg up
wkm.VK_HOME,
wkm.VK_INSERT => self.buttons.b = 1, //home or insert
wkm.VK_END,
wkm.VK_DELETE,
wkm.VK_BACK => self.buttons.a = 1, //end, del, bksp
else => return wnm.DefWindowProcW(hWnd, uMsg, wParam, lParam),
}
},
wnm.WM_CHAR => {
if(wParam >=0 and wParam <= 127) {
//lparam:
//0-15 repeat count, 16-23 scan code, 24 extended key, 25-28 reserved, 29 alt, 30 prev state, 31 transition
//seems like it is never sent for UP transitions, but that's ok because the babelfish doesn't seem to
//care anyway
const ascii = @truncate(u8, wParam);
const key = if(ascii == '\r') '\n' else ascii; //return generates cr, but babelfish treats it as lf
self.babelfish.asciiKeyPress(key);
} else return wnm.DefWindowProcW(hWnd, uMsg, wParam, lParam);
},
else => return wnm.DefWindowProcW(hWnd, uMsg, wParam, lParam),
}
return 0;
}
fn handleMessages(self: *@This()) void {
var message: wnm.MSG = undefined;
while(
wnm.PeekMessageW(
&message,
self.hWnd,
0,
0,
wnm.PM_REMOVE
)
!= win32.zig.FALSE) {
_ = wnm.TranslateMessage(&message);
_ = wnm.DispatchMessageW(&message);
}
}
fn destroy(self: *@This()) void {
_ = wg.open_gl.wglMakeCurrent(null, null);
_ = wg.open_gl.wglDeleteContext(self.wglRC);
_ = wg.gdi.ReleaseDC(self.hWnd, self.hDC);
_ = wnm.DestroyWindow(self.hWnd);
}
fn render(self: *@This(), vga: *Gigatron.VgaMonitor, leds: [4]bool) !void {
//copy the monitor pixels into the frame buffer:
for(vga.pixels[0..(vid_width * vid_height)]) |p, i| {
self.frame_buffer[i] = Gigatron.VgaMonitor.convert(RGB888, p);
}
//draw the blinkenlights in an ugly 10px tall panel
// at the bottom of the screen
for(self.frame_buffer[(vid_width * vid_height)..]) |*p, i| {
const x = i % vid_width;
const black = RGB888{.r=0, .g=0, .b=0};
const red = RGB888{.r=255, .g=0,.b=0};
const grey = RGB888{.r=128,.g=128,.b=128};
const spacing = 10;
const width = 10;
const start_0 = vid_width - ((width + spacing) * 4);
const start_1 = start_0 + width + spacing;
const start_2 = start_1 + width + spacing;
const start_3 = start_2 + width + spacing;
p.* = switch(x) {
start_0...start_0 + (width - 1) => if(leds[0]) red else black,
start_1...start_1 + (width - 1) => if(leds[1]) red else black,
start_2...start_2 + (width - 1) => if(leds[2]) red else black,
start_3...start_3 + (width - 1) => if(leds[3]) red else black,
else => grey,
};
}
try glErr({
gl.glEnable(gl.GL_TEXTURE_2D);
gl.glBindTexture(gl.GL_TEXTURE_2D, self.gl_texture);
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST);
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST);
gl.glTexImage2D(
gl.GL_TEXTURE_2D,
0,
gl.GL_RGB,
vid_width,
vid_height + blinken_height,
0,
gl.GL_RGB,
gl.GL_UNSIGNED_BYTE,
&self.frame_buffer,
);
});
try glErr({
gl.glBegin(gl.GL_QUADS);
gl.glTexCoord2f(0.0, 0.0);
gl.glVertex2f(-1.0, 1.0);
gl.glTexCoord2f(1.0, 0.0);
gl.glVertex2f(1.0, 1.0);
gl.glTexCoord2f(1.0, 1.0);
gl.glVertex2f(1.0, -1.0);
gl.glTexCoord2f(0.0, 1.0);
gl.glVertex2f(-1.0, -1.0);
gl.glEnd();
gl.glDisable(gl.GL_TEXTURE_2D);
});
try boolErr(wg.open_gl.SwapBuffers(self.hDC));
}
};
//After some experimentation with different syncing strategies, I settled on
// using the size of the audio sample buffer to determine the passage of
// time. This was weirdly consistent compared to the alternatives.
pub const Sound = struct {
const wca = win32.media.audio;
const wf = win32.foundation;
device_enumerator: *wca.IMMDeviceEnumerator,
device: *wca.IMMDevice,
client: *wca.IAudioClient,
render_client: *wca.IAudioRenderClient,
samples: Samples,
sample_lock: bool,
buffer_frames: c_uint,
buffer_event: wf.HANDLE,
const Samples = std.fifo.LinearFifo(f32, .{.Static = 2048});
pub fn init() !@This() {
var self: @This() = undefined; //someday we can use explicit result location
//tell windows we want a 1ms scheduler granularity instead of the
// 15ms eternity it uses by defualt. We do it here because we use
// the sound buffer for timing now.
//ignore any errors, shouldn't be possible and we can't do anything
// about them anyway
_ = win32.media.timeBeginPeriod(1);
try hrErr(win32.system.com.CoCreateInstance(
wca.CLSID_MMDeviceEnumerator,
null,
win32.system.com.CLSCTX_INPROC_SERVER,
wca.IID_IMMDeviceEnumerator,
@ptrCast(*?*anyopaque, &self.device_enumerator),
));
errdefer _ = self.device_enumerator.IUnknown_Release();
try hrErr(self.device_enumerator.IMMDeviceEnumerator_GetDefaultAudioEndpoint(
.eRender,
.eConsole,
@ptrCast(*?@TypeOf(self.device), &self.device),
));
errdefer _ = self.device.IUnknown_Release();
try hrErr(self.device.IMMDevice_Activate(
wca.IID_IAudioClient,
@enumToInt(win32.system.com.CLSCTX_INPROC_SERVER),
null,
@ptrCast(*?*anyopaque, &self.client),
));
errdefer _ = self.client.IUnknown_Release();
//We can force the driver to handle sample conversion, so for
// simplicity we set our sample rate to an even division of
// the gigatron clock rate. Float is used because why not.
const target_format = win32.media.audio.WAVEFORMATEX{
.wFormatTag = win32.media.multimedia.WAVE_FORMAT_IEEE_FLOAT,
.nChannels = 1,
.nSamplesPerSec = gigatron_clock_rate / 100,
.nAvgBytesPerSec = (gigatron_clock_rate / 100) * @sizeOf(f32) * 1,
.nBlockAlign = @sizeOf(f32) * 1,
.wBitsPerSample = @bitSizeOf(f32),
.cbSize = 0,
};
try hrErr(self.client.IAudioClient_Initialize(
.SHARED,
wca.AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | //should force the mixer to convert for us. Vista and above.
wca.AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY | //better quality conversion, may add latency?
wca.AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
0,
0,
&target_format,
null,
));
try hrErr(self.client.IAudioClient_GetService(
wca.IID_IAudioRenderClient,
@ptrCast(*?*anyopaque, &self.render_client),
));
errdefer _ = self.render_client.IUnknown_Release();
self.buffer_event = win32.system.threading.CreateEventExW(
null,
null,
@intToEnum(win32.system.threading.CREATE_EVENT, 0),
0x1F0003, //2031619 = EVENT_ALL_ACCESS
) orelse return error.CreateEventFailed;
errdefer _ = wf.CloseHandle(self.buffer_event);
try hrErr(self.client.IAudioClient_SetEventHandle(self.buffer_event));
try hrErr(self.client.IAudioClient_GetBufferSize(&self.buffer_frames));
self.samples = Samples.init();
self.sample_lock = false;
return self;
}
//move samples from our buffer to the actual audio buffer
pub fn writeSamples(self: *@This()) !void {
var buffer: [*]f32 = undefined;
var padding_frames: u32 = undefined;
try hrErr(self.client.IAudioClient_GetCurrentPadding(&padding_frames));
const available_frames = self.buffer_frames - padding_frames;
if(available_frames == 0) return;
if(self.samples.count == 0) return;
while (@cmpxchgWeak(bool, &self.sample_lock, false, true, .Acquire, .Monotonic) != null) {}
defer @atomicStore(bool, &self.sample_lock, false, .Release);
try hrErr(self.render_client.IAudioRenderClient_GetBuffer(available_frames, @ptrCast(*?*u8, &buffer)));
const count = self.samples.read(buffer[0..available_frames]);
try hrErr(self.render_client.IAudioRenderClient_ReleaseBuffer(@truncate(u32, count), 0));
}
//The buffer will tell us when it is hungry for more.
//@NOTE: In some cases the buffer is still hungry despite being full. SoML.
pub fn waitBuffer(self: *@This()) void {
const wait_return_cause = win32.system.threading.WaitForSingleObject(
self.buffer_event,
win32.system.windows_programming.INFINITE,
);
switch(wait_return_cause) {
win32.system.threading.WAIT_OBJECT_0 => {},
win32.system.threading.WAIT_ABANDONED,
@enumToInt(win32.foundation.WAIT_TIMEOUT),
@enumToInt(win32.foundation.WAIT_FAILED) => std.debug.panic("Wait failed: {}\n", .{wait_return_cause}),
else => std.debug.panic("Unknown wait status: {}\n", .{wait_return_cause}),
}
}
pub fn audioThread(self: *@This()) !void {
while(self.samples.count == 0) {win32.system.threading.Sleep(1);}
try hrErr(self.client.IAudioClient_Start());
while(true) {
self.waitBuffer();
try self.writeSamples();
}
}
//write a single sample to our buffer for later copying to the real one
pub fn writeSample(self: *@This(), sample: f32) !void {
while (@cmpxchgWeak(bool, &self.sample_lock, false, true, .Acquire, .Monotonic) != null) {}
defer @atomicStore(bool, &self.sample_lock, false, .Release);
try self.samples.writeItem(sample);
}
//if we start to get ahead of the audio buffer (2 sync's worth)
// then wait until we're under that.
pub fn sync(self: *@This(), sync_hz: u32) void {
const sample_hz = (gigatron_clock_rate / 100);
const samples_per_sync = sample_hz / sync_hz;
while(self.samples.count >= (2 * samples_per_sync)) {
const sleep_time = std.time.ms_per_s / sync_hz;
win32.system.threading.Sleep(sleep_time);
}
}
pub fn deinit(self: *@This()) void {
_ = wf.CloseHandle(self.buffer_event);
_ = self.client.IAudioClient_Stop();
_ = self.render_client.IUnknown_Release();
_ = self.client.IUnknown_Release();
_ = self.device.IUnknown_Release();
_ = self.device_enumerator.IUnknown_Release();
_ = win32.media.timeEndPeriod(1);
}
};
pub fn main() !void {
var vm: Gigatron.VirtualMachine = undefined;
var babelfish = Gigatron.BabelFish{};
var tape = [_]u8{0} ** 512;
babelfish.init(&tape);
var vga = Gigatron.VgaMonitor{};
var audio = Gigatron.Audio.init(gigatron_clock_rate / 100);
//@TODO: Selectable rom
const current_dir = std.fs.cwd();
const rom_file = try current_dir.openFile("gigatron.rom", .{ .read = true });
var reader = rom_file.reader();
_ = try vm.loadRom(reader);
rom_file.close();
vm.start();
try MainWindow.init(&babelfish.buttons, &babelfish);
defer main_window.destroy();
sound = try Sound.init();
defer sound.deinit();
const sound_thread = try std.Thread.spawn(.{}, Sound.audioThread, .{&sound});
_ = sound_thread;
//@NOTE: This would cause any thrown error to simply wait forever
//for a join that never happens
//defer sound_thread.join();
//@NOTE: This will glitch on rollover (except in debug, where it'll crash)
// after about 93k years or so, if running in real time
var cycle: u64 = 0;
while(true) : (cycle += 1) {
vm.cycle();
babelfish.cycle(&vm);
const render = vga.cycle(&vm);
if(render) {
const leds = Gigatron.BlinkenLights.sample(&vm);
//@TODO: skip rendering if behind on frames
try main_window.render(&vga, leds);
}
//62500hz
if(cycle % 100 == 0) {
try sound.writeSample(audio.sample(&vm));
}
//100hz
if(cycle % (gigatron_clock_rate / 100) == 0) {
main_window.handleMessages();
sound.sync(100);
}
}
} | zge-windows.zig |
const builtin = @import("builtin");
const utils = @import("utils");
const kernel = @import("root").kernel;
const print = kernel.print;
const fprint = kernel.fprint;
const io = kernel.io;
const memory = kernel.memory;
const putil = @import("util.zig");
const ata = @import("ata.zig");
const ps2 = @import("ps2.zig");
const usb = @import("usb.zig");
const Class = enum (u16) {
IDE_Controller = 0x0101,
Floppy_Controller = 0x0102,
ATA_Controller = 0x0105,
SATA_Controller = 0x0106,
Ethernet_Controller = 0x0200,
VGA_Controller = 0x0300,
PCI_Host_Bridge = 0x0600,
ISA_Bridge = 0x0601,
PCI_To_PCI_Bridge = 0x0604,
Bridge = 0x0680,
USB_Controller = 0x0C03,
Unknown = 0xFFFF,
pub fn from_u16(value: u16) ?Class {
return utils.int_to_enum(@This(), value);
}
pub fn to_string(self: Class) []const u8 {
return switch (self) {
.IDE_Controller => "IDE Controller",
.Floppy_Controller => "Floppy Controller",
.ATA_Controller => "ATA Controller",
.SATA_Controller => "SATA Controller",
.Ethernet_Controller => "Ethernet Controller",
.VGA_Controller => "VGA Controller",
.PCI_Host_Bridge => "PCI Host Bridge",
.ISA_Bridge => "ISA Bridge",
.PCI_To_PCI_Bridge => "PCI to PCI Bridge",
.Bridge => "Bridge",
.USB_Controller => "USB Controller",
.Unknown => "Unknown",
};
}
};
pub const Bus = u8;
pub const Device = u5;
pub const Function = u3;
pub const Offset = u8;
pub const Location = packed struct {
function: Function,
device: Device,
bus: Bus,
};
const Config = packed struct {
offset: Offset,
location: Location,
reserved: u7 = 0,
enabled: bool = true,
};
fn config_port(comptime Type: type, location: Location, offset: Offset) callconv(.Inline) u16 {
const config = Config{
.offset = offset & 0xFC,
.location = location,
};
putil.out(u32, 0x0CF8, @bitCast(u32, config));
return 0x0CFC + @intCast(u16, if (Type == u32) 0 else (offset & 3));
}
pub fn read_config(comptime Type: type,
location: Location, offset: Offset) callconv(.Inline) Type {
return putil.in(Type, config_port(Type, location, offset));
}
pub fn write_config(comptime Type: type,
location: Location, offset: Offset, value: Type) callconv(.Inline) void {
putil.out(Type, config_port(Type, location, offset), value);
}
pub const Header = packed struct {
pub const Kind = enum (u8) {
Normal = 0x00,
MultiFunctionNormal = 0x80,
PciToPciBridge = 0x01,
MultiFunctionPciToPciBridge = 0x81,
CardBusBridge = 0x02,
MultiFunctionCardBusBridge = 0x82,
pub fn from_u8(value: u8) ?Kind {
return utils.int_to_enum(@This(), value);
}
pub fn to_string(self: Kind) []const u8 {
return switch (self) {
.Normal => "Normal",
.MultiFunctionNormal => "Multi-Function Normal",
.PciToPciBridge => "PCI-to-PCI Bridge",
.MultiFunctionPciToPciBridge =>
"Multi-Function PCI-to-PCI Bridge",
.CardBusBridge => "CardBus Bridge",
.MultiFunctionCardBusBridge =>
"Multi-Function CardBus Bridge",
};
}
pub fn is_multifunction(self: Kind) bool {
return switch (self) {
.MultiFunctionNormal => true,
.MultiFunctionPciToPciBridge => true,
.MultiFunctionCardBusBridge => true,
else => false,
};
}
};
pub const SuperClass = enum (u8) {
UnclassifiedDevice = 0x00,
MassStorageController = 0x01,
NetworkController = 0x02,
DisplayController = 0x03,
MultimediaController = 0x04,
MemoryController = 0x05,
BridgeDevice = 0x06,
SimpleCommunicationsController = 0x07,
GenericSystemPeripheral = 0x08,
InputDeviceController = 0x09,
DockingStation = 0x0A,
Processor = 0x0B,
SerialBusController = 0x0C,
WirelessController = 0x0D,
IntelligentController = 0x0E,
SatelliteCommunicationsController = 0x0F,
EncryptionController = 0x10,
SignalProcessingController = 0x11,
ProcessingAccelerator = 0x12,
NonEssentialInstrumentation = 0x13,
Coprocessor = 0x40,
pub fn from_u8(value: u8) ?SuperClass {
return utils.int_to_enum(@This(), value);
}
pub fn to_string(self: SuperClass) []const u8 {
return switch (self) {
.UnclassifiedDevice => "Unclassified Device",
.MassStorageController => "Mass Storage Controller",
.NetworkController => "Network Controller",
.DisplayController => "Display Controller",
.MultimediaController => "Multimedia Controller",
.MemoryController => "Memory Controller",
.BridgeDevice => "Bridge Device",
.SimpleCommunicationsController =>
"Simple Communications Controller",
.GenericSystemPeripheral => "Generic System Peripheral",
.InputDeviceController => "Input Device Controller",
.DockingStation => "Docking Station",
.Processor => "Processor",
.SerialBusController => "Serial Bus Controller",
.WirelessController => "Wireless Controller",
.IntelligentController => "Intelligent Controller",
.SatelliteCommunicationsController =>
"Satellite Communications Controller",
.EncryptionController => "Encryption Controller",
.SignalProcessingController => "Signal Processing Controller",
.ProcessingAccelerator => "Processing Accelerator",
.NonEssentialInstrumentation =>
"Non-Essential Instrumentation",
.Coprocessor => "Coprocessor",
};
}
};
vendor_id: u16 = 0,
device_id: u16 = 0,
command: u16 = 0,
status: u16 = 0,
revision_id: u8 = 0,
prog_if: u8 = 0,
subclass: u8 = 0,
class: u8 = 0,
cache_line_size: u8 = 0,
latency_timer: u8 = 0,
header_type: u8 = 0,
bist: u8 = 0,
pub fn is_invalid(self: *const Header) bool {
return self.vendor_id == 0xFFFF;
}
pub fn get_header_type(self: *const Header) ?Kind {
return Kind.from_u8(self.header_type);
}
pub fn get_class(self: *const Header) ?SuperClass {
return SuperClass.from_u8(self.class);
}
pub fn print(self: *const Header, file: *io.File) io.FileError!void {
try fprint.format(file,
\\ - PCI Header:
\\ - vendor_id: {:x}
\\ - device_id: {:x}
\\ - command: {:x}
\\ - status: {:x}
\\ - revision_id: {:x}
\\ - prog_if: {:x}
\\ - subclass: {:x}
\\ - class:
, .{
self.vendor_id,
self.device_id,
self.command,
self.status,
self.revision_id,
self.prog_if,
self.subclass});
if (self.get_class()) |class| {
try fprint.format(file, " {}", .{class.to_string()});
} else {
try fprint.format(file, " Unknown Class {:x}", .{self.class});
}
try fprint.format(file,
\\
\\ - cache_line_size: {:x}
\\ - latency_timer: {:x}
\\ - header_type:
, .{
self.cache_line_size,
self.latency_timer});
if (self.get_header_type()) |header_type| {
try fprint.format(file, " {}", .{header_type.to_string()});
} else {
try fprint.format(file, " Unknown Value {:x}", .{self.header_type});
}
try fprint.format(file,
\\
\\ - bist: {:x}
\\
, .{self.bist});
}
pub fn get(location: Location) Header {
const Self = @This();
var rv: [@sizeOf(Self)]u8 = undefined;
for (rv[0..]) |*ptr, i| {
ptr.* = read_config(u8, location, @intCast(Offset, i));
}
return @bitCast(Self, rv);
}
};
pub const Dev = struct {
pub const BaseAddress = union(enum) {
// TODO
// Io: struct {
// port: u16,
// },
memory: struct {
range: memory.Range,
// TODO
// prefetchable: bool,
// is64b: bool,
},
};
location: Location,
header: Header,
base_addresses: [6]?BaseAddress = [_]?BaseAddress {null} ** 6,
fn read_base_addresses(self: *Dev) void {
for (self.base_addresses[0..]) |*ptr, i| {
const offset = @sizeOf(Header) + 4 * @intCast(Offset, i);
const raw_entry = read_config(u32, self.location, offset);
if (raw_entry == 0) {
continue;
}
if (raw_entry & 1 == 1) {
// TODO
print.format(" - BAR {}: I/O Entry (TODO)\n", .{i});
continue;
}
const address = raw_entry & ~@as(u32, 0xf);
write_config(u32, self.location, offset, 0xffffffff);
const size = ~(read_config(u32, self.location, offset) & ~@as(u32, 1)) +% 1;
write_config(u32, self.location, offset, raw_entry);
print.format(" - BAR {}: {:a}+{:x}\n", .{i, address, size}, );
ptr.* = BaseAddress{.memory = .{.range = .{.start = address, .size = size}}};
}
}
pub fn init(self: *Dev) void {
if (self.header.get_header_type()) |header_type| {
if (header_type == .Normal) {
self.read_base_addresses();
}
}
}
pub fn read(self: *Dev, comptime Type: type, offset: Offset) Type {
return read_config(Type, self.location, offset);
}
pub fn write(self: *Dev, comptime Type: type, offset: Offset, value: Type) void {
write_config(Type, self.location, offset, value);
}
};
fn check_function(location: Location, header: *const Header) void {
if (header.is_invalid()) return;
print.format(" - Bus {}, Device {}, Function {}\n",
.{location.bus, location.device, location.function});
_ = header.print(print.get_console_file().?) catch {};
if (header.get_class()) |class| {
var dev = Dev{.location = location, .header = header.*};
dev.init();
if (class == .MassStorageController and header.subclass == 0x01) {
ata.init(&dev);
} else if (class == .SerialBusController and header.subclass == 0x03 and
header.prog_if == 0x20) {
usb.init(&dev);
}
ps2.anykey();
if (class == .BridgeDevice and header.subclass == 0x04) {
check_bus(read_config(u8, location, 0x19));
}
}
}
fn check_device(bus: Bus, device: Device) void {
const root_location = Location{.bus = bus, .device = device, .function = 0};
const header = Header.get(root_location);
check_function(root_location, &header);
if (header.get_header_type()) |header_type| {
if (header_type.is_multifunction()) {
// Header Type is Multi-Function, Check Them
var i: Function = 1;
while (true) : (i += 1) {
const location = Location{
.bus = bus, .device = device, .function = i};
const subheader = Header.get(location);
check_function(location, &subheader);
if (i == 7) break;
}
}
}
}
fn check_bus(bus: u8) void {
var i: Device = 0;
while (true) : (i += 1) {
check_device(bus, i);
if (i == 31) break;
}
}
pub fn find_pci_devices() void {
print.string(" - Seaching for PCI Devices\n");
check_bus(0);
} | kernel/platform/pci.zig |
pub const SysTick = struct {
base: usize,
const Self = @This();
/// Construct a `SysTick` object using the specified MMIO base address.
pub fn withBase(base: usize) Self {
return Self{ .base = base };
}
/// SysTick Control and Status Register
pub fn regCsr(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base);
}
pub const CSR_COUNTFLAG: u32 = 1 << 16;
pub const CSR_CLKSOURCE: u32 = 1 << 2;
pub const CSR_TICKINT: u32 = 1 << 1;
pub const CSR_ENABLE: u32 = 1 << 0;
/// SysTick Reload Value Register
pub fn regRvr(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x4);
}
/// SysTick Current Value Register
pub fn regCvr(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x8);
}
/// SysTick Calibration Value Register
pub fn regCalib(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0xc);
}
};
/// Represents the SysTick instance corresponding to the current security mode.
pub const sys_tick = SysTick.withBase(0xe000e010);
/// Represents the Non-Secure SysTick instance. This register is only accessible
/// by Secure mode (Armv8-M or later).
pub const sys_tick_ns = SysTick.withBase(0xe002e010);
/// Nested Vectored Interrupt Controller.
pub const Nvic = struct {
base: usize,
const Self = @This();
/// Construct an `Nvic` object using the specified MMIO base address.
pub fn withBase(base: usize) Self {
return Self{ .base = base };
}
// Register Accessors
// -----------------------------------------------------------------------
/// Interrupt Set Enable Register.
pub fn regIser(self: Self) *volatile [16]u32 {
return @intToPtr(*volatile [16]u32, self.base);
}
/// Interrupt Clear Enable Register.
pub fn regIcer(self: Self) *volatile [16]u32 {
return @intToPtr(*volatile [16]u32, self.base + 0x80);
}
/// Interrupt Set Pending Register.
pub fn regIspr(self: Self) *volatile [16]u32 {
return @intToPtr(*volatile [16]u32, self.base + 0x100);
}
/// Interrupt Clear Pending Register.
pub fn regIcpr(self: Self) *volatile [16]u32 {
return @intToPtr(*volatile [16]u32, self.base + 0x180);
}
/// Interrupt Active Bit Register.
pub fn regIabr(self: Self) *volatile [16]u32 {
return @intToPtr(*volatile [16]u32, self.base + 0x200);
}
/// Interrupt Target Non-Secure Register (Armv8-M or later). RAZ/WI from
/// Non-Secure.
pub fn regItns(self: Self) *volatile [16]u32 {
return @intToPtr(*volatile [16]u32, self.base + 0x280);
}
/// Interrupt Priority Register.
pub fn regIpri(self: Self) *volatile [512]u8 {
return @intToPtr(*volatile [512]u8, self.base + 0x300);
}
// Helper functions
// -----------------------------------------------------------------------
// Note: Interrupt numbers are different from exception numbers.
// An exception number `Interrupt_IRQn(i)` corresponds to an interrupt
// number `i`.
/// Enable the interrupt number `irq`.
pub fn enableIrq(self: Self, irq: usize) void {
self.reg_iser()[irq >> 5] = u32(1) << @truncate(u5, irq);
}
/// Disable the interrupt number `irq`.
pub fn disableIrq(self: Self, irq: usize) void {
self.reg_icer()[irq >> 5] = u32(1) << @truncate(u5, irq);
}
/// Set the priority of the interrupt number `irq` to `pri`.
pub fn setIrqPriority(self: Self, irq: usize, pri: u8) void {
self.reg_ipri()[irq] = pri;
}
};
/// Represents the Nested Vectored Interrupt Controller instance corresponding
/// to the current security mode.
pub const nvic = Nvic.withBase(0xe000e100);
/// Represents the Non-Secure Nested Vectored Interrupt Controller instance.
/// This register is only accessible by Secure mode (Armv8-M or later).
pub const nvic_ns = Nvic.withBase(0xe002e100);
/// System Control Block.
pub const Scb = struct {
base: usize,
const Self = @This();
/// Construct an `Nvic` object using the specified MMIO base address.
pub fn withBase(base: usize) Self {
return Self{ .base = base };
}
// Register Accessors
// -----------------------------------------------------------------------
/// System Handler Control and State Register
pub fn regShcsr(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x124);
}
pub const SHCSR_MEMFAULTACT: u32 = 1 << 0;
pub const SHCSR_BUSFAULTACT: u32 = 1 << 1;
pub const SHCSR_HARDFAULTACT: u32 = 1 << 2;
pub const SHCSR_USGFAULTACT: u32 = 1 << 3;
pub const SHCSR_SECUREFAULTACT: u32 = 1 << 4;
pub const SHCSR_NMIACT: u32 = 1 << 5;
pub const SHCSR_SVCCALLACT: u32 = 1 << 7;
pub const SHCSR_MONITORACT: u32 = 1 << 8;
pub const SHCSR_PENDSVACT: u32 = 1 << 10;
pub const SHCSR_SYSTICKACT: u32 = 1 << 11;
pub const SHCSR_USGFAULTPENDED: u32 = 1 << 12;
pub const SHCSR_MEMFAULTPENDED: u32 = 1 << 13;
pub const SHCSR_BUSFAULTPENDED: u32 = 1 << 14;
pub const SHCSR_SYSCALLPENDED: u32 = 1 << 15;
pub const SHCSR_MEMFAULTENA: u32 = 1 << 16;
pub const SHCSR_BUSFAULTENA: u32 = 1 << 17;
pub const SHCSR_USGFAULTENA: u32 = 1 << 18;
pub const SHCSR_SECUREFAULTENA: u32 = 1 << 19;
pub const SHCSR_SECUREFAULTPENDED: u32 = 1 << 20;
pub const SHCSR_HARDFAULTPENDED: u32 = 1 << 21;
/// Application Interrupt and Reset Control Register
pub fn regAircr(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x10c);
}
pub const AIRCR_VECTCLRACTIVE: u32 = 1 << 1;
pub const AIRCR_SYSRESETREQ: u32 = 1 << 2;
pub const AIRCR_SYSRESETREQS: u32 = 1 << 3;
pub const AIRCR_DIT: u32 = 1 << 4;
pub const AIRCR_IESB: u32 = 1 << 5;
pub const AIRCR_PRIGROUP_SHIFT: u5 = 8;
pub const AIRCR_PRIGROUP_MASK: u32 = 0b111 << AIRCR_PRIGROUP_SHIFT;
pub const AIRCR_BFHFNMINS: u32 = 1 << 13;
pub const AIRCR_PRIS: u32 = 1 << 14;
pub const AIRCR_ENDIANNESS: u32 = 1 << 15;
pub const AIRCR_VECTKEY_SHIFT: u5 = 16;
pub const AIRCR_VECTKEY_MASK: u32 = 0xffff << AIRCR_VECTKEY_SHIFT;
pub const AIRCR_VECTKEY_MAGIC: u32 = 0x05fa;
/// Vector Table Offset Register
pub fn regVtor(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x108);
}
};
/// Represents the System Control Block instance corresponding to the current
/// security mode.
pub const scb = Scb.withBase(0xe000ec00);
/// Represents the System Control Block instance for Non-Secure mode.
/// This register is only accessible by Secure mode (Armv8-M or later).
pub const scb_ns = Scb.withBase(0xe002ec00);
/// Exception numbers defined by Arm-M.
pub const irqs = struct {
pub const Reset_IRQn: usize = 1;
pub const Nmi_IRQn: usize = 2;
pub const SecureHardFault_IRQn: usize = 3;
pub const MemManageFault_IRQn: usize = 4;
pub const BusFault_IRQn: usize = 5;
pub const UsageFault_IRQn: usize = 6;
pub const SecureFault_IRQn: usize = 7;
pub const SvCall_IRQn: usize = 11;
pub const DebugMonitor_IRQn: usize = 12;
pub const PendSv_IRQn: usize = 14;
pub const SysTick_IRQn: usize = 15;
pub const InterruptBase_IRQn: usize = 16;
pub fn interruptIRQn(i: usize) usize {
return @This().InterruptBase_IRQn + i;
}
}; | src/drivers/arm_m.zig |
const os = @import("root").os;
const std = @import("std");
const builtin = @import("builtin");
const log = os.log;
const pci = os.platform.pci;
const paging = os.memory.paging;
const pmm = os.memory.pmm;
const scheduler = os.thread.scheduler;
const page_size = os.platform.paging.page_sizes[0];
const abar_size = 0x1100;
const port_control_registers_size = 0x80;
const bf = os.lib.bitfields;
const libalign = os.lib.libalign;
const Port = packed struct {
command_list_base: [2]u32,
fis_base: [2]u32,
interrupt_status: u32,
interrupt_enable: u32,
command_status: extern union {
raw: u32,
start: bf.boolean(u32, 0),
recv_enable: bf.boolean(u32, 4),
fis_recv_running: bf.boolean(u32, 14),
command_list_running: bf.boolean(u32, 15),
},
reserved_0x1C: u32,
task_file_data: extern union {
raw: u32,
transfer_requested: bf.boolean(u32, 3),
interface_busy: bf.boolean(u32, 7),
},
signature: u32,
sata_status: u32,
sata_control: u32,
sata_error: u32,
sata_active: u32,
command_issue: u32,
sata_notification: u32,
fis_switching_control: u32,
device_sleep: u32,
reserved_0x48: [0x70 - 0x48]u8,
vendor_0x70: [0x80 - 0x70]u8,
pub fn command_headers(self: *const volatile @This()) *volatile [32]CommandTableHeader {
const addr = read_u64(&self.command_list_base);
return &os.platform.phys_ptr(*volatile CommandList).from_int(addr).get_uncached().command_headers;
}
pub fn start_command_engine(self: *volatile @This()) void {
os.log("AHCI: Starting command engine for port at 0x{X}\n", .{@ptrToInt(self)});
self.wait_ready();
self.command_status.start.write(false);
self.command_status.recv_enable.write(false);
while (self.command_status.command_list_running.read() or self.command_status.fis_recv_running.read())
scheduler.yield();
self.command_status.recv_enable.write(true);
self.command_status.start.write(true);
}
pub fn stop_command_engine(self: *volatile @This()) void {
os.log("AHCI: Stopping command engine for port at 0x{X}\n", .{@ptrToInt(self)});
self.command_status.start.write(false);
while (self.command_status.command_list_running.read())
scheduler.yield();
self.command_status.recv_enable.write(false);
while (self.command_status.fis_recv_running.read())
scheduler.yield();
}
pub fn wait_ready(self: *volatile @This()) void {
while (self.task_file_data.transfer_requested.read() or self.task_file_data.interface_busy.read())
scheduler.yield();
}
pub fn issue_commands(self: *volatile @This(), slot_bits: u32) void {
log("AHCI: Sending {} command(s) to port 0x{X}\n", .{ @popCount(u32, slot_bits), @ptrToInt(self) });
self.wait_ready();
self.command_issue |= slot_bits;
while ((self.command_issue & slot_bits) != 0)
scheduler.yield();
}
pub fn command_header(self: *const volatile @This(), slot: u5) *volatile CommandTableHeader {
return &self.command_headers()[slot];
}
pub fn command_table(self: *const volatile @This(), slot: u5) *volatile CommandTable {
return self.command_header(slot).table();
}
pub fn get_fis(self: *volatile @This(), slot: u5) *volatile CommandFis {
return &self.command_table(slot).command_fis;
}
pub fn make_h2d(self: *volatile @This(), slot: u5) *volatile FisH2D {
const fis = &self.get_fis(slot).h2d;
fis.fis_type = 0x27;
return fis;
}
pub fn prd(self: *volatile @This(), slot: u5, prd_idx: usize) *volatile PRD {
return &self.command_table(slot).prds[prd_idx];
}
pub fn buffer(self: *volatile @This(), slot: u5, prd_idx: usize) []u8 {
const prd_ptr = self.prd(slot, 0);
const buf_addr = read_u64(&prd_ptr.data_base_addr);
const buf_size = @as(usize, prd_ptr.sizem1) + 1;
return os.platform.phys_slice(u8).init(buf_addr, buf_size).to_slice_writeback();
}
pub fn read_single_sector(self: *volatile @This(), slot: u5) void {
self.issue_commands(1 << slot);
}
};
fn write_u64(mmio: anytype, value: u64) void {
mmio[0] = @truncate(u32, value);
mmio[1] = @truncate(u32, value >> 32);
}
fn read_u64(mmio: anytype) u64 {
return @as(u64, mmio[0]) | (@as(u64, mmio[1]) << 32);
}
comptime {
std.debug.assert(@sizeOf(Port) == 0x80);
}
const ABAR = struct {
hba_capabilities: u32,
global_hba_control: u32,
interrupt_status: u32,
ports_implemented: u32,
version: extern union {
value: u32,
major: bf.bitfield(u32, 16, 16),
minor_high: bf.bitfield(u32, 8, 8),
minor_low: bf.bitfield(u32, 0, 8),
pub fn format(self: *const @This(), fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
try writer.print("{}.{}", .{ self.major.read(), self.minor_high.read() });
if (self.minor_low.read() != 0)
try writer.print(".{}", .{self.minor_low.read()});
}
comptime {
std.debug.assert(@sizeOf(@This()) == 4);
std.debug.assert(@bitSizeOf(@This()) == 32);
}
},
command_completion_coalescing_control: u32,
command_completion_coalescing_port: u32,
enclosure_managment_location: u32,
enclosure_managment_control: u32,
hba_capabilities_extended: u32,
bios_handoff: extern union {
value: u32,
bios_owned: bf.boolean(u32, 4),
os_owned: bf.boolean(u32, 1),
bios_busy: bf.boolean(u32, 0),
fn set_handoff(self: *volatile @This()) void {
self.os_owned.write(true);
}
fn check_handoff(self: *volatile @This()) bool {
if (self.bios_owned.read())
return false;
if (self.bios_busy.read())
return false;
if (self.os_owned.read())
return true;
return false;
}
fn try_claim(self: *volatile @This()) bool {
self.set_handoff();
return self.check_handoff();
}
comptime {
std.debug.assert(@sizeOf(@This()) == 4);
std.debug.assert(@bitSizeOf(@This()) == 32);
}
},
reserved_0x2C: u32,
reserved_0x30: [0xA0 - 0x30]u8,
vendor_0xA0: [0x100 - 0xA0]u8,
ports: [32]Port,
};
comptime {
std.debug.assert(@sizeOf(ABAR) == 0x1100);
}
fn claim_controller(abar: *volatile ABAR) void {
{
const version = abar.version;
log("AHCI: Version: {}\n", .{version});
if (version.major.read() < 1 or version.minor_high.read() < 2) {
log("AHCI: Handoff not supported (version)\n", .{});
return;
}
}
if (abar.hba_capabilities_extended & 1 == 0) {
log("AHCI: Handoff not supported (capabilities)\n", .{});
return;
}
while (!abar.bios_handoff.try_claim()) {
scheduler.yield();
}
log("AHCI: Got handoff!\n", .{});
}
const sata_port_type = enum {
ata,
atapi,
semb,
pm,
};
const CommandTableHeader = packed struct {
command_fis_length: u5,
atapi: u1,
write: u1,
prefetchable: u1,
sata_reset_control: u1,
bist: u1,
clear: u1,
_res1_3: u1,
pmp: u4,
pdrt_count: u16,
command_table_byte_size: u32,
command_table_addr: [2]u32,
reserved: [4]u32,
pub fn table(self: *volatile @This()) *volatile CommandTable {
const addr = read_u64(&self.command_table_addr);
return os.platform.phys_ptr(*volatile CommandTable).from_int(addr).get_uncached();
}
};
comptime {
std.debug.assert(@sizeOf(CommandTableHeader) == 0x20);
}
const CommandList = struct {
command_headers: [32]CommandTableHeader,
};
const RecvFis = struct {
dma_setup: [0x1C]u8,
_res1C: [0x20 - 0x1C]u8,
pio_setup: [0x14]u8,
_res34: [0x40 - 0x34]u8,
d2h_register: [0x14]u8,
_res54: [0x58 - 0x54]u8,
set_device_bits: [8]u8,
unknown_fis: [0x40]u8,
_resA0: [0x100 - 0xA0]u8,
};
comptime {
std.debug.assert(@byteOffsetOf(RecvFis, "dma_setup") == 0);
std.debug.assert(@byteOffsetOf(RecvFis, "pio_setup") == 0x20);
std.debug.assert(@byteOffsetOf(RecvFis, "d2h_register") == 0x40);
std.debug.assert(@byteOffsetOf(RecvFis, "set_device_bits") == 0x58);
std.debug.assert(@byteOffsetOf(RecvFis, "unknown_fis") == 0x60);
std.debug.assert(@sizeOf(RecvFis) == 0x100);
}
const PRD = packed struct {
data_base_addr: [2]u32,
_res08: u32,
sizem1: u22,
_res10_22: u9,
completion_interrupt: u1,
};
comptime {
std.debug.assert(@sizeOf(PRD) == 0x10);
}
const FisH2D = packed struct {
fis_type: u8,
pmport: u4,
_res1_4: u3,
c: u1,
command: u8,
feature_low: u8,
lba_low: u24,
device: u8,
lba_high: u24,
feature_high: u8,
count: u16,
icc: u8,
control: u8,
};
comptime {
std.debug.assert(@byteOffsetOf(FisH2D, "command") == 2);
}
const CommandFis = extern union {
bytes: [0x40]u8,
h2d: FisH2D,
//d2h: FisD2H,
};
const CommandTable = struct {
command_fis: CommandFis,
atapi_command: [0x10]u8,
_res50: [0x80 - 0x50]u8,
// TODO: Maybe more(?)
// First buffer should always be pointing to a single preallocated page
// when this command table is unused. Make sure to restore it if you overwrite it
prds: [8]PRD,
};
const ReadOrWrite = enum {
Read,
Write,
};
// Our own structure for keeping track of everything we need for a port
const PortState = struct {
mmio: *volatile Port = undefined,
num_sectors: usize = undefined,
sector_size: usize = 512,
port_type: sata_port_type = undefined,
pub fn init(port: *volatile Port) !PortState {
var result: PortState = .{};
result.mmio = port;
result.port_type =
switch(result.mmio.signature) {
0x00000101 => .ata,
//0xEB140101 => .atapi, // Drop atapi for now
else => return error.UnknownSignature,
};
result.mmio.stop_command_engine();
try result.setup_command_headers();
try result.setup_prdts();
result.mmio.start_command_engine();
try result.identify();
return result;
}
fn setup_command_headers(self: *@This()) !void {
const port_io_size = @sizeOf(CommandList) + @sizeOf(RecvFis);
const commands_phys = try pmm.alloc_phys(port_io_size);
const fis_phys = commands_phys + @sizeOf(CommandList);
@memset(os.platform.phys_ptr([*]u8).from_int(commands_phys).get_uncached(), 0, port_io_size);
write_u64(&self.mmio.command_list_base, commands_phys);
write_u64(&self.mmio.fis_base, fis_phys);
}
fn setup_prdts(self: *@This()) !void {
var current_table_addr: usize = undefined;
var reamining_table_size: usize = 0;
for (self.mmio.command_headers()) |*header| {
if (reamining_table_size < @sizeOf(CommandTable)) {
reamining_table_size = page_size;
current_table_addr = try pmm.alloc_phys(page_size);
@memset(os.platform.phys_ptr([*]u8).from_int(current_table_addr).get_uncached(), 0, page_size);
}
write_u64(&header.command_table_addr, current_table_addr);
header.pdrt_count = 1;
header.command_fis_length = @sizeOf(FisH2D) / @sizeOf(u32);
header.atapi = if (self.port_type == .atapi) 1 else 0;
current_table_addr += @sizeOf(CommandTable);
reamining_table_size -= @sizeOf(CommandTable);
// First PRD is just a small preallocated single page buffer
const buf = try pmm.alloc_phys(page_size);
@memset(os.platform.phys_ptr([*]u8).from_int(buf).get_uncached(), 0, page_size);
write_u64(&header.table().prds[0].data_base_addr, buf);
header.table().prds[0].sizem1 = page_size - 1;
}
}
fn identify_command(self: *@This()) u8 {
return switch (self.port_type) {
.ata => 0xEC,
.atapi => 0xA1,
else => unreachable,
};
}
fn identify(self: *@This()) !void {
//log("AHCI: Identifying drive...\n", .{});
const identify_fis = self.mmio.make_h2d(0);
identify_fis.command = self.identify_command();
identify_fis.c = 1;
identify_fis.device = 0;
self.mmio.issue_commands(1);
const buf = self.mmio.buffer(0, 0);
//os.hexdump(buf[0..256]);
const data_valid = std.mem.readIntLittle(u16, buf[212..][0..2]);
if(data_valid & (1 << 15) == 0 and data_valid & (1 << 14) != 0 and data_valid & (1 << 12) != 0)
self.sector_size = std.mem.readIntLittle(u32, buf[234..][0..4]);
self.num_sectors = std.mem.readIntLittle(u64, buf[200..][0..8]);
if(self.num_sectors == 0)
self.num_sectors = std.mem.readIntLittle(u32, buf[120..][0..4]);
if(self.num_sectors == 0)
return error.NoSectors;
log("AHCI: Disk has 0x{X} sectors of size {}\n", .{self.num_sectors, self.sector_size});
}
fn issue_command_on_port(self: *@This(), command_slot: u5) void {
// TODO: Call this from command slot task and
// make this dispatch work to the port task
self.mmio.issue_commands(@as(u32, 1) << command_slot);
}
fn finalize_io(self: *@This(), command_slot: u5, lba: u48, sector_count: u16, mode: ReadOrWrite) void {
const fis = self.mmio.make_h2d(0);
fis.command =
switch (self.port_type) {
.ata => switch(mode) {
.Read => @as(u8, 0x25),
.Write => 0x35,
},
else => unreachable,
};
fis.device = 0xA0 | (1 << 6);
fis.control = 0x08;
fis.lba_low = @truncate(u24, lba);
fis.lba_high = @truncate(u24, lba >> 24);
fis.count = sector_count;
self.issue_command_on_port(command_slot);
}
// All the following functions will sooner or later be moved out into a general
// block dev interface, and this will just have a simple dma interface instead.
pub fn offset_to_sector(self: *@This(), offset: usize) u48 {
return @intCast(u48, offset / self.sector_size);
}
fn do_small_write(self: *@This(), command_slot: u5, buffer: []const u8, lba: u48, offset: usize) void {
self.mmio.command_header(command_slot).pdrt_count = 1;
// Read the shit we're not going to overwite
self.finalize_io(command_slot, lba, 1, .Read);
// Overwrite what we want to buffer
for(buffer) |b, i| {
self.mmio.buffer(command_slot, 0)[offset + i] = b;
}
// Write buffer to disk
self.finalize_io(command_slot, lba, 1, .Write);
}
fn do_small_read(self: *@This(), command_slot: u5, buffer: []u8, lba: u48, offset: usize) void {
self.finalize_io(command_slot, lba, 1, .Read);
for(buffer) |*b, i|
b.* = self.mmio.buffer(command_slot, 0)[offset + i];
}
fn do_large_write(self: *@This(), command_slot: u5, buffer: []const u8, lba: u48) void {
for(buffer[0..self.sector_size]) |b, i|
self.mmio.buffer(command_slot, 0)[i] = b;
self.finalize_io(command_slot, lba, 1, .Write);
}
fn do_large_read(self: *@This(), command_slot: u5, buffer: []u8, lba: u48) void {
self.finalize_io(command_slot, lba, 1, .Read);
for(buffer[0..self.sector_size]) |*b, i|
b.* = self.mmio.buffer(command_slot, 0)[i];
}
fn iterate_byte_sectors(
self: *@This(),
command_slot: u5,
buffer_in: anytype,
disk_offset_in: usize,
small_callback: anytype,
large_callback: anytype,
) void {
if(buffer_in.len == 0)
return;
self.mmio.command_header(command_slot).pdrt_count = 1;
var first_sector = self.offset_to_sector(disk_offset_in);
const last_sector = self.offset_to_sector(disk_offset_in + buffer_in.len - 1);
if(first_sector == last_sector) {
small_callback(self, command_slot, buffer_in, first_sector, disk_offset_in % self.sector_size);
return;
}
var disk_offset = disk_offset_in;
var buffer = buffer_in;
// We need to preserve data on the first sector
if(!libalign.is_aligned(usize, self.sector_size, disk_offset)) {
const step = libalign.align_up(usize, self.sector_size, disk_offset) - disk_offset;
small_callback(self, command_slot, buffer[0..step], first_sector, self.sector_size - step);
buffer.ptr += step;
buffer.len -= step;
disk_offset += step;
first_sector += 1;
}
// Now we're sector aligned, we can do the transfer sector by sector
// TODO: make this faster, doing multiple sectors at a time
while(buffer.len > self.sector_size) {
os.log("Doing entire sector {}\n", .{first_sector});
large_callback(self, command_slot, buffer, first_sector);
buffer.ptr += self.sector_size;
buffer.len -= self.sector_size;
first_sector += 1;
}
if(buffer.len == 0)
return;
os.log("Doing last partial sector {}\n", .{first_sector});
// Last sector, partial
small_callback(self, command_slot, buffer, first_sector, 0);
}
pub fn do_io_bytes_write(self: *@This(), command_slot: u5, buffer: []const u8, disk_offset: usize) void {
self.iterate_byte_sectors(command_slot, buffer, disk_offset, do_small_write, do_large_write);
}
pub fn do_io_bytes_read(self: *@This(), command_slot: u5, buffer: []u8, disk_offset: usize) void {
self.iterate_byte_sectors(command_slot, buffer, disk_offset, do_small_read, do_large_read);
}
};
comptime {
std.debug.assert(@sizeOf(CommandTable) == 0x100);
}
fn command(port: *volatile Port, slot: u5) void {}
fn command_with_buffer(port: *volatile Port, slot: u5, buf: usize, bufsize: usize) void {
const header = &port.command_headers()[slot];
//const oldbuf = header.;
//const oldsize = ;
}
var test_buf: [4096]u8 = undefined;
fn sata_port_task(port_type: sata_port_type, port: *volatile Port) !void {
switch (port_type) {
.ata, .atapi => {},
else => return,
}
log("AHCI: {s} task started for port at 0x{X}\n", .{ @tagName(port_type), @ptrToInt(port) });
var port_state = try PortState.init(port);
// Put 0x204 'x's across 3 sectors if sector size is 0x200
//port_state.do_io_bytes_write(0, "x" ** 0x204, port_state.sector_size - 2);
//port_state.finalize_io(0, 0, 3, .Read);
//os.hexdump(port_state.mmio.buffer(0, 0)[port_state.sector_size - 0x10..port_state.sector_size * 2 + 0x10]);
// Read first disk sector
port_state.finalize_io(0, 0, 1, .Read);
os.hexdump(port_state.mmio.buffer(0, 0)[0..port_state.sector_size]);
// Read first sector into buffer
//port_state.do_io_bytes_read(0, test_buf[0..512], 0);
//os.hexdump(test_buf[0..512]);
}
fn controller_task(abar: *volatile ABAR) !void {
claim_controller(abar);
log("AHCI: Claimed controller.\n", .{});
const ports_implemented = abar.ports_implemented;
for (abar.ports) |*port, i| {
if ((ports_implemented >> @intCast(u5, i)) & 1 == 0)
continue;
{
const sata_status = port.sata_status;
{
const com_status = sata_status & 0xF;
if (com_status == 0)
continue;
if (com_status != 3) {
log("AHCI: Warning: Unknown port com_status: {}\n", .{com_status});
continue;
}
}
{
const ipm_status = (sata_status >> 8) & 0xF;
if (ipm_status != 1) {
log("AHCI: Warning: Device sleeping: {}\n", .{ipm_status});
continue;
}
}
}
switch (port.signature) {
0x00000101 => try scheduler.spawn_task(sata_port_task, .{ .ata, port }),
//0xEB140101 => try scheduler.spawn_task(sata_port_task, .{.atapi, port}),
0xC33C0101, 0x96690101 => {
log("AHCI: Known TODO port signature: 0x{X}\n", .{port.signature});
//scheduler.spawn_task(sata_port_task, .{.semb, port})
//scheduler.spawn_task(sata_port_task, .{.pm, port})
},
else => {
log("AHCI: Unknown port signature: 0x{X}\n", .{port.signature});
return;
},
}
}
}
pub fn register_controller(addr: pci.Addr) void {
// Busty master bit
addr.command().write(addr.command().read() | 0x6);
const abar = os.platform.phys_ptr(*volatile ABAR).from_int(addr.barinfo(5).phy & 0xFFFFF000).get_uncached();
const cap = abar.hba_capabilities;
if ((cap & (1 << 31)) == 0) {
log("AHCI: Controller is 32 bit only, ignoring.\n", .{});
return;
}
if (abar.global_hba_control & (1 << 31) == 0) {
log("AHCI: AE not set!\n", .{});
return;
}
scheduler.spawn_task(controller_task, .{abar}) catch |err| {
log("AHCI: Failed to make controller task: {s}\n", .{@errorName(err)});
};
} | src/drivers/disk/ahci.zig |
pub const grammar =
\\Root <- skip ContainerMembers eof
\\
\\# *** Top level ***
\\ContainerMembers
\\ <- TestDecl ContainerMembers
\\ / TopLevelComptime ContainerMembers
\\ / KEYWORD_pub? TopLevelDecl ContainerMembers
\\ / ContainerField COMMA ContainerMembers
\\ / ContainerField
\\ /
\\
\\TestDecl <- KEYWORD_test STRINGLITERALSINGLE Block
\\
\\TopLevelComptime <- KEYWORD_comptime BlockExpr
\\
\\TopLevelDecl
\\ <- (KEYWORD_export / KEYWORD_extern STRINGLITERALSINGLE? / KEYWORD_inline)? FnProto (SEMICOLON / Block)
\\ / (KEYWORD_export / KEYWORD_extern STRINGLITERALSINGLE?)? KEYWORD_threadlocal? VarDecl
\\ / KEYWORD_usingnamespace Expr SEMICOLON
\\
\\FnProto <- KEYWORD_fn IDENTIFIER? LPAREN ParamDeclList RPAREN ByteAlign? LinkSection? EXCLAMATIONMARK? (KEYWORD_anytype / TypeExpr)
\\
\\VarDecl <- (KEYWORD_const / KEYWORD_var) IDENTIFIER (COLON TypeExpr)? ByteAlign? LinkSection? (EQUAL Expr)? SEMICOLON
\\
\\ContainerField <- KEYWORD_comptime? IDENTIFIER (COLON TypeExpr)? (EQUAL Expr)?
\\
\\# *** Block Level ***
\\Statement
\\ <- KEYWORD_comptime? VarDecl
\\ / KEYWORD_comptime BlockExprStatement
\\ / KEYWORD_nosuspend BlockExprStatement
\\ / KEYWORD_suspend (SEMICOLON / BlockExprStatement)
\\ / KEYWORD_defer BlockExprStatement
\\ / KEYWORD_errdefer BlockExprStatement
\\ / IfStatement
\\ / LabeledStatement
\\ / SwitchExpr
\\ / AssignExpr SEMICOLON
\\
\\IfStatement
\\ <- IfPrefix BlockExpr ( KEYWORD_else Payload? Statement )?
\\ / IfPrefix AssignExpr ( SEMICOLON / KEYWORD_else Payload? Statement )
\\
\\LabeledStatement <- BlockLabel? (Block / LoopStatement)
\\
\\LoopStatement <- KEYWORD_inline? (ForStatement / WhileStatement)
\\
\\ForStatement
\\ <- ForPrefix BlockExpr ( KEYWORD_else Statement )?
\\ / ForPrefix AssignExpr ( SEMICOLON / KEYWORD_else Statement )
\\
\\WhileStatement
\\ <- WhilePrefix BlockExpr ( KEYWORD_else Payload? Statement )?
\\ / WhilePrefix AssignExpr ( SEMICOLON / KEYWORD_else Payload? Statement )
\\
\\BlockExprStatement
\\ <- BlockExpr
\\ / AssignExpr SEMICOLON
\\
\\BlockExpr <- BlockLabel? Block
\\
\\# *** Expression Level ***
\\AssignExpr <- Expr (AssignOp Expr)?
\\
\\Expr <- KEYWORD_try* BoolOrExpr
\\
\\BoolOrExpr <- BoolAndExpr (KEYWORD_or BoolAndExpr)*
\\
\\BoolAndExpr <- CompareExpr (KEYWORD_and CompareExpr)*
\\
\\CompareExpr <- BitwiseExpr (CompareOp BitwiseExpr)?
\\
\\BitwiseExpr <- BitShiftExpr (BitwiseOp BitShiftExpr)*
\\
\\BitShiftExpr <- AdditionExpr (BitShiftOp AdditionExpr)*
\\
\\AdditionExpr <- MultiplyExpr (AdditionOp MultiplyExpr)*
\\
\\MultiplyExpr <- PrefixExpr (MultiplyOp PrefixExpr)*
\\
\\PrefixExpr <- PrefixOp* PrimaryExpr
\\
\\PrimaryExpr
\\ <- AsmExpr
\\ / IfExpr
\\ / KEYWORD_break BreakLabel? Expr?
\\ / KEYWORD_comptime Expr
\\ / KEYWORD_nosuspend Expr
\\ / KEYWORD_continue BreakLabel?
\\ / KEYWORD_resume Expr
\\ / KEYWORD_return Expr?
\\ / BlockLabel? LoopExpr
\\ / Block
\\ / CurlySuffixExpr
\\
\\IfExpr <- IfPrefix Expr (KEYWORD_else Payload? Expr)?
\\
\\Block <- LBRACE Statement* RBRACE
\\
\\LoopExpr <- KEYWORD_inline? (ForExpr / WhileExpr)
\\
\\ForExpr <- ForPrefix Expr (KEYWORD_else Expr)?
\\
\\WhileExpr <- WhilePrefix Expr (KEYWORD_else Payload? Expr)?
\\
\\CurlySuffixExpr <- TypeExpr InitList?
\\
\\InitList
\\ <- LBRACE FieldInit (COMMA FieldInit)* COMMA? RBRACE
\\ / LBRACE Expr (COMMA Expr)* COMMA? RBRACE
\\ / LBRACE RBRACE
\\
\\TypeExpr <- PrefixTypeOp* ErrorUnionExpr
\\
\\ErrorUnionExpr <- SuffixExpr (EXCLAMATIONMARK TypeExpr)?
\\
\\SuffixExpr
\\ <- KEYWORD_async PrimaryTypeExpr SuffixOp* FnCallArguments
\\ / PrimaryTypeExpr (SuffixOp / FnCallArguments)*
\\
\\PrimaryTypeExpr
\\ <- BUILTINIDENTIFIER FnCallArguments
\\ / CHAR_LITERAL
\\ / ContainerDecl
\\ / DOT IDENTIFIER
\\ / DOT InitList
\\ / ErrorSetDecl
\\ / FLOAT
\\ / FnProto
\\ / GroupedExpr
\\ / LabeledTypeExpr
\\ / IDENTIFIER
\\ / IfTypeExpr
\\ / INTEGER
\\ / KEYWORD_comptime TypeExpr
\\ / KEYWORD_error DOT IDENTIFIER
\\ / KEYWORD_false
\\ / KEYWORD_null
\\ / KEYWORD_anyframe
\\ / KEYWORD_true
\\ / KEYWORD_undefined
\\ / KEYWORD_unreachable
\\ / STRINGLITERAL
\\ / SwitchExpr
\\
\\ContainerDecl <- (KEYWORD_extern / KEYWORD_packed)? ContainerDeclAuto
\\
\\ErrorSetDecl <- KEYWORD_error LBRACE IdentifierList RBRACE
\\
\\GroupedExpr <- LPAREN Expr RPAREN
\\
\\IfTypeExpr <- IfPrefix TypeExpr (KEYWORD_else Payload? TypeExpr)?
\\
\\LabeledTypeExpr
\\ <- BlockLabel Block
\\ / BlockLabel? LoopTypeExpr
\\
\\LoopTypeExpr <- KEYWORD_inline? (ForTypeExpr / WhileTypeExpr)
\\
\\ForTypeExpr <- ForPrefix TypeExpr (KEYWORD_else TypeExpr)?
\\
\\WhileTypeExpr <- WhilePrefix TypeExpr (KEYWORD_else Payload? TypeExpr)?
\\
\\SwitchExpr <- KEYWORD_switch LPAREN Expr RPAREN LBRACE SwitchProngList RBRACE
\\
\\# *** Assembly ***
\\AsmExpr <- KEYWORD_asm KEYWORD_volatile? LPAREN STRINGLITERAL AsmOutput? RPAREN
\\
\\AsmOutput <- COLON AsmOutputList AsmInput?
\\
\\AsmOutputItem <- LBRACKET IDENTIFIER RBRACKET STRINGLITERAL LPAREN (MINUSRARROW TypeExpr / IDENTIFIER) RPAREN
\\
\\AsmInput <- COLON AsmInputList AsmClobbers?
\\
\\AsmInputItem <- LBRACKET IDENTIFIER RBRACKET STRINGLITERAL LPAREN Expr RPAREN
\\
\\AsmClobbers <- COLON StringList
\\
\\# *** Helper grammar ***
\\BreakLabel <- COLON IDENTIFIER
\\
\\BlockLabel <- IDENTIFIER COLON
\\
\\FieldInit <- DOT IDENTIFIER EQUAL Expr
\\
\\WhileContinueExpr <- COLON LPAREN AssignExpr RPAREN
\\
\\LinkSection <- KEYWORD_linksection LPAREN Expr RPAREN
\\
\\ParamDecl <- (KEYWORD_noalias / KEYWORD_comptime)? (IDENTIFIER COLON)? ParamType
\\
\\ParamType
\\ <- KEYWORD_anytype
\\ / DOT3
\\ / TypeExpr
\\
\\# Control flow prefixes
\\IfPrefix <- KEYWORD_if LPAREN Expr RPAREN PtrPayload?
\\
\\WhilePrefix <- KEYWORD_while LPAREN Expr RPAREN PtrPayload? WhileContinueExpr?
\\
\\ForPrefix <- KEYWORD_for LPAREN Expr RPAREN PtrIndexPayload
\\
\\# Payloads
\\Payload <- PIPE IDENTIFIER PIPE
\\
\\PtrPayload <- PIPE ASTERISK? IDENTIFIER PIPE
\\
\\PtrIndexPayload <- PIPE ASTERISK? IDENTIFIER (COMMA IDENTIFIER)? PIPE
\\
\\
\\# Switch specific
\\SwitchProng <- SwitchCase EQUALRARROW PtrPayload? AssignExpr
\\
\\SwitchCase
\\ <- SwitchItem (COMMA SwitchItem)* COMMA?
\\ / KEYWORD_else
\\
\\SwitchItem <- Expr (DOT3 Expr)?
\\
\\# Operators
\\AssignOp
\\ <- ASTERISKEQUAL
\\ / SLASHEQUAL
\\ / PERCENTEQUAL
\\ / PLUSEQUAL
\\ / MINUSEQUAL
\\ / LARROW2EQUAL
\\ / RARROW2EQUAL
\\ / AMPERSANDEQUAL
\\ / CARETEQUAL
\\ / PIPEEQUAL
\\ / ASTERISKPERCENTEQUAL
\\ / PLUSPERCENTEQUAL
\\ / MINUSPERCENTEQUAL
\\ / EQUAL
\\
\\CompareOp
\\ <- EQUALEQUAL
\\ / EXCLAMATIONMARKEQUAL
\\ / LARROW
\\ / RARROW
\\ / LARROWEQUAL
\\ / RARROWEQUAL
\\
\\BitwiseOp
\\ <- AMPERSAND
\\ / CARET
\\ / PIPE
\\ / KEYWORD_orelse
\\ / KEYWORD_catch Payload?
\\
\\BitShiftOp
\\ <- LARROW2
\\ / RARROW2
\\
\\AdditionOp
\\ <- PLUS
\\ / MINUS
\\ / PLUS2
\\ / PLUSPERCENT
\\ / MINUSPERCENT
\\
\\MultiplyOp
\\ <- PIPE2
\\ / ASTERISK
\\ / SLASH
\\ / PERCENT
\\ / ASTERISK2
\\ / ASTERISKPERCENT
\\
\\PrefixOp
\\ <- EXCLAMATIONMARK
\\ / MINUS
\\ / TILDE
\\ / MINUSPERCENT
\\ / AMPERSAND
\\ / KEYWORD_try
\\ / KEYWORD_await
\\
\\PrefixTypeOp
\\ <- QUESTIONMARK
\\ / KEYWORD_anyframe MINUSRARROW
\\ / ArrayTypeStart (ByteAlign / KEYWORD_const / KEYWORD_volatile / KEYWORD_allowzero)*
\\ / PtrTypeStart (KEYWORD_align LPAREN Expr (COLON INTEGER COLON INTEGER)? RPAREN / KEYWORD_const / KEYWORD_volatile / KEYWORD_allowzero)*
\\
\\SuffixOp
\\ <- LBRACKET Expr (DOT2 Expr?)? RBRACKET
\\ / DOT IDENTIFIER
\\ / DOTASTERISK
\\ / DOTQUESTIONMARK
\\
\\FnCallArguments <- LPAREN ExprList RPAREN
\\
\\# Ptr specific
\\ArrayTypeStart <- LBRACKET Expr? RBRACKET
\\
\\PtrTypeStart
\\ <- ASTERISK
\\ / ASTERISK2
\\ / PTRUNKNOWN
\\ / PTRC
\\
\\# ContainerDecl specific
\\ContainerDeclAuto <- ContainerDeclType LBRACE ContainerMembers RBRACE
\\
\\ContainerDeclType
\\ <- (KEYWORD_struct / KEYWORD_enum) (LPAREN Expr RPAREN)?
\\ / KEYWORD_union (LPAREN (KEYWORD_enum (LPAREN Expr RPAREN)? / Expr) RPAREN)?
\\
\\# Alignment
\\ByteAlign <- KEYWORD_align LPAREN Expr RPAREN
\\
\\# Lists
\\IdentifierList <- (IDENTIFIER COMMA)* IDENTIFIER?
\\
\\SwitchProngList <- (SwitchProng COMMA)* SwitchProng?
\\
\\AsmOutputList <- (AsmOutputItem COMMA)* AsmOutputItem?
\\
\\AsmInputList <- (AsmInputItem COMMA)* AsmInputItem?
\\
\\StringList <- (STRINGLITERAL COMMA)* STRINGLITERAL?
\\
\\ParamDeclList <- (ParamDecl COMMA)* ParamDecl?
\\
\\ExprList <- (Expr COMMA)* Expr?
\\
\\# *** Tokens ***
\\eof <- !.
\\hex <- [0-9a-fA-F]
\\char_escape
\\ <- "\\x" hex hex
\\ / "\\u{" hex+ "}"
\\ / "\\" [nr\\t'"]
\\char_char
\\ <- char_escape
\\ / [^\\'\n]
\\string_char
\\ <- char_escape
\\ / [^\\"\n]
\\
\\line_comment <- '//'[^\n]*
\\line_string <- ("\\\\" [^\n]* [ \n]*)+
\\skip <- ([ \n] / line_comment)*
\\
\\CHAR_LITERAL <- "'" char_char "'" skip
\\FLOAT
\\ <- "0x" hex+ "." hex+ ([pP] [-+]? hex+)? skip
\\ / [0-9]+ "." [0-9]+ ([eE] [-+]? [0-9]+)? skip
\\ / "0x" hex+ "."? [pP] [-+]? hex+ skip
\\ / [0-9]+ "."? [eE] [-+]? [0-9]+ skip
\\INTEGER
\\ <- "0b" [01]+ skip
\\ / "0o" [0-7]+ skip
\\ / "0x" hex+ skip
\\ / [0-9]+ skip
\\STRINGLITERALSINGLE <- "\"" string_char* "\"" skip
\\STRINGLITERAL
\\ <- STRINGLITERALSINGLE
\\ / line_string skip
\\IDENTIFIER
\\ <- !keyword [A-Za-z_] [A-Za-z0-9_]* skip
\\ / "@\"" string_char* "\"" skip
\\BUILTINIDENTIFIER <- "@"[A-Za-z_][A-Za-z0-9_]* skip
\\
\\
\\AMPERSAND <- '&' ![=] skip
\\AMPERSANDEQUAL <- '&=' skip
\\ASTERISK <- '*' ![*%=] skip
\\ASTERISK2 <- '**' skip
\\ASTERISKEQUAL <- '*=' skip
\\ASTERISKPERCENT <- '*%' ![=] skip
\\ASTERISKPERCENTEQUAL <- '*%=' skip
\\CARET <- '^' ![=] skip
\\CARETEQUAL <- '^=' skip
\\COLON <- ':' skip
\\COMMA <- ',' skip
\\DOT <- '.' ![*.?] skip
\\DOT2 <- '..' ![.] skip
\\DOT3 <- '...' skip
\\DOTASTERISK <- '.*' skip
\\DOTQUESTIONMARK <- '.?' skip
\\EQUAL <- '=' ![>=] skip
\\EQUALEQUAL <- '==' skip
\\EQUALRARROW <- '=>' skip
\\EXCLAMATIONMARK <- '!' ![=] skip
\\EXCLAMATIONMARKEQUAL <- '!=' skip
\\LARROW <- '<' ![<=] skip
\\LARROW2 <- '<<' ![=] skip
\\LARROW2EQUAL <- '<<=' skip
\\LARROWEQUAL <- '<=' skip
\\LBRACE <- '{' skip
\\LBRACKET <- '[' ![*] skip
\\LPAREN <- '(' skip
\\MINUS <- '-' ![%=>] skip
\\MINUSEQUAL <- '-=' skip
\\MINUSPERCENT <- '-%' ![=] skip
\\MINUSPERCENTEQUAL <- '-%=' skip
\\MINUSRARROW <- '->' skip
\\PERCENT <- '%' ![=] skip
\\PERCENTEQUAL <- '%=' skip
\\PIPE <- '|' ![|=] skip
\\PIPE2 <- '||' skip
\\PIPEEQUAL <- '|=' skip
\\PLUS <- '+' ![%+=] skip
\\PLUS2 <- '++' skip
\\PLUSEQUAL <- '+=' skip
\\PLUSPERCENT <- '+%' ![=] skip
\\PLUSPERCENTEQUAL <- '+%=' skip
\\PTRC <- '[*c]' skip
\\PTRUNKNOWN <- '[*]' skip
\\QUESTIONMARK <- '?' skip
\\RARROW <- '>' ![>=] skip
\\RARROW2 <- '>>' ![=] skip
\\RARROW2EQUAL <- '>>=' skip
\\RARROWEQUAL <- '>=' skip
\\RBRACE <- '}' skip
\\RBRACKET <- ']' skip
\\RPAREN <- ')' skip
\\SEMICOLON <- ';' skip
\\SLASH <- '/' ![=] skip
\\SLASHEQUAL <- '/=' skip
\\TILDE <- '~' skip
\\
\\end_of_word <- ![a-zA-Z0-9_] skip
\\KEYWORD_align <- 'align' end_of_word
\\KEYWORD_allowzero <- 'allowzero' end_of_word
\\KEYWORD_and <- 'and' end_of_word
\\KEYWORD_anyframe <- 'anyframe' end_of_word
\\KEYWORD_anytype <- 'anytype' end_of_word
\\KEYWORD_asm <- 'asm' end_of_word
\\KEYWORD_async <- 'async' end_of_word
\\KEYWORD_await <- 'await' end_of_word
\\KEYWORD_break <- 'break' end_of_word
\\KEYWORD_catch <- 'catch' end_of_word
\\KEYWORD_comptime <- 'comptime' end_of_word
\\KEYWORD_const <- 'const' end_of_word
\\KEYWORD_continue <- 'continue' end_of_word
\\KEYWORD_defer <- 'defer' end_of_word
\\KEYWORD_else <- 'else' end_of_word
\\KEYWORD_enum <- 'enum' end_of_word
\\KEYWORD_errdefer <- 'errdefer' end_of_word
\\KEYWORD_error <- 'error' end_of_word
\\KEYWORD_export <- 'export' end_of_word
\\KEYWORD_extern <- 'extern' end_of_word
\\KEYWORD_false <- 'false' end_of_word
\\KEYWORD_fn <- 'fn' end_of_word
\\KEYWORD_for <- 'for' end_of_word
\\KEYWORD_if <- 'if' end_of_word
\\KEYWORD_inline <- 'inline' end_of_word
\\KEYWORD_noalias <- 'noalias' end_of_word
\\KEYWORD_nosuspend <- 'nosuspend' end_of_word
\\KEYWORD_null <- 'null' end_of_word
\\KEYWORD_or <- 'or' end_of_word
\\KEYWORD_orelse <- 'orelse' end_of_word
\\KEYWORD_packed <- 'packed' end_of_word
\\KEYWORD_pub <- 'pub' end_of_word
\\KEYWORD_resume <- 'resume' end_of_word
\\KEYWORD_return <- 'return' end_of_word
\\KEYWORD_linksection <- 'linksection' end_of_word
\\KEYWORD_struct <- 'struct' end_of_word
\\KEYWORD_suspend <- 'suspend' end_of_word
\\KEYWORD_switch <- 'switch' end_of_word
\\KEYWORD_test <- 'test' end_of_word
\\KEYWORD_threadlocal <- 'threadlocal' end_of_word
\\KEYWORD_true <- 'true' end_of_word
\\KEYWORD_try <- 'try' end_of_word
\\KEYWORD_undefined <- 'undefined' end_of_word
\\KEYWORD_union <- 'union' end_of_word
\\KEYWORD_unreachable <- 'unreachable' end_of_word
\\KEYWORD_usingnamespace <- 'usingnamespace' end_of_word
\\KEYWORD_var <- 'var' end_of_word
\\KEYWORD_volatile <- 'volatile' end_of_word
\\KEYWORD_while <- 'while' end_of_word
\\
\\keyword <- KEYWORD_align / KEYWORD_and / KEYWORD_anyframe / KEYWORD_anytype
\\ / KEYWORD_allowzero / KEYWORD_asm / KEYWORD_async / KEYWORD_await / KEYWORD_break
\\ / KEYWORD_catch / KEYWORD_comptime / KEYWORD_const / KEYWORD_continue
\\ / KEYWORD_defer / KEYWORD_else / KEYWORD_enum / KEYWORD_errdefer
\\ / KEYWORD_error / KEYWORD_export / KEYWORD_extern / KEYWORD_false
\\ / KEYWORD_fn / KEYWORD_for / KEYWORD_if / KEYWORD_inline
\\ / KEYWORD_noalias / KEYWORD_null / KEYWORD_or
\\ / KEYWORD_orelse / KEYWORD_packed / KEYWORD_pub
\\ / KEYWORD_resume / KEYWORD_return / KEYWORD_linksection
\\ / KEYWORD_struct / KEYWORD_suspend
\\ / KEYWORD_switch / KEYWORD_test / KEYWORD_threadlocal / KEYWORD_true / KEYWORD_try
\\ / KEYWORD_undefined / KEYWORD_union / KEYWORD_unreachable
\\ / KEYWORD_usingnamespace / KEYWORD_var / KEYWORD_volatile / KEYWORD_while
; | src/example_data.zig |
const builtin = @import("builtin");
const std = @import("std");
const c = @import("c.zig");
const shaderc = @import("shaderc.zig");
const ft = @import("ft.zig");
const Blit = @import("blit.zig").Blit;
const Preview = @import("preview.zig").Preview;
const Shader = @import("shaderc.zig").Shader;
pub const Renderer = struct {
const Self = @This();
tex: c.WGPUTextureId,
tex_view: c.WGPUTextureViewId,
tex_sampler: c.WGPUSamplerId,
swap_chain: c.WGPUSwapChainId,
width: u32,
height: u32,
device: c.WGPUDeviceId,
surface: c.WGPUSurfaceId,
queue: c.WGPUQueueId,
bind_group: c.WGPUBindGroupId,
uniform_buffer: c.WGPUBufferId,
char_grid_buffer: c.WGPUBufferId,
render_pipeline: c.WGPURenderPipelineId,
preview: ?*Preview,
blit: Blit,
// We track the last few preview times; if the media is under 30 FPS,
// then we switch to tiled rendering
dt: [5]i64,
dt_index: usize,
pub fn init(alloc: *std.mem.Allocator, window: *c.GLFWwindow, font: *const ft.Atlas) !Self {
var arena = std.heap.ArenaAllocator.init(alloc);
const tmp_alloc: *std.mem.Allocator = &arena.allocator;
defer arena.deinit();
// Extract the WGPU Surface from the platform-specific window
const platform = builtin.os.tag;
const surface = if (platform == .macos) surf: {
// Time to do hilarious Objective-C runtime hacks, equivalent to
// [ns_window.contentView setWantsLayer:YES];
// id metal_layer = [CAMetalLayer layer];
// [ns_window.contentView setLayer:metal_layer];
const objc = @import("objc.zig");
const darwin = @import("darwin.zig");
const cocoa_window = darwin.glfwGetCocoaWindow(window);
const ns_window = @ptrCast(c.id, @alignCast(8, cocoa_window));
const cv = objc.call(ns_window, "contentView");
_ = objc.call_(cv, "setWantsLayer:", true);
const ca_metal = objc.class("CAMetalLayer");
const metal_layer = objc.call(ca_metal, "layer");
_ = objc.call_(cv, "setLayer:", metal_layer);
break :surf c.wgpu_create_surface_from_metal_layer(metal_layer);
} else {
std.debug.panic("Unimplemented on platform {}", .{platform});
};
////////////////////////////////////////////////////////////////////////////
// WGPU initial setup
var adapter: c.WGPUAdapterId = 0;
c.wgpu_request_adapter_async(&(c.WGPURequestAdapterOptions){
.power_preference = c.WGPUPowerPreference_HighPerformance,
.compatible_surface = surface,
}, 2 | 4 | 8, false, adapter_cb, &adapter);
const device = c.wgpu_adapter_request_device(
adapter,
0,
&(c.WGPUCLimits){
.max_bind_groups = 1,
},
true,
null,
);
////////////////////////////////////////////////////////////////////////////
// Build the shaders using shaderc
const vert_spv = try shaderc.build_shader_from_file(tmp_alloc, "shaders/grid.vert");
const vert_shader = c.wgpu_device_create_shader_module(
device,
(c.WGPUShaderSource){
.bytes = vert_spv.ptr,
.length = vert_spv.len,
},
);
defer c.wgpu_shader_module_destroy(vert_shader);
const frag_spv = try shaderc.build_shader_from_file(tmp_alloc, "shaders/grid.frag");
const frag_shader = c.wgpu_device_create_shader_module(
device,
(c.WGPUShaderSource){
.bytes = frag_spv.ptr,
.length = frag_spv.len,
},
);
defer c.wgpu_shader_module_destroy(frag_shader);
////////////////////////////////////////////////////////////////////////////
// Upload the font atlas texture
const tex_size = (c.WGPUExtent3d){
.width = @intCast(u32, font.tex_size),
.height = @intCast(u32, font.tex_size),
.depth = 1,
};
const tex = c.wgpu_device_create_texture(
device,
&(c.WGPUTextureDescriptor){
.size = tex_size,
.mip_level_count = 1,
.sample_count = 1,
.dimension = c.WGPUTextureDimension_D2,
.format = c.WGPUTextureFormat_Rgba8Unorm,
// SAMPLED tells wgpu that we want to use this texture in shaders
// COPY_DST means that we want to copy data to this texture
.usage = c.WGPUTextureUsage_SAMPLED | c.WGPUTextureUsage_COPY_DST,
.label = "font_atlas",
},
);
const tex_view = c.wgpu_texture_create_view(
tex,
&(c.WGPUTextureViewDescriptor){
.label = "font_atlas_view",
.dimension = c.WGPUTextureViewDimension_D2,
.format = c.WGPUTextureFormat_Rgba8Unorm,
.aspect = c.WGPUTextureAspect_All,
.base_mip_level = 0,
.level_count = 1,
.base_array_layer = 0,
.array_layer_count = 1,
},
);
const tex_sampler = c.wgpu_device_create_sampler(
device,
&(c.WGPUSamplerDescriptor){
.next_in_chain = null,
.label = "font_atlas_sampler",
.address_mode_u = c.WGPUAddressMode_ClampToEdge,
.address_mode_v = c.WGPUAddressMode_ClampToEdge,
.address_mode_w = c.WGPUAddressMode_ClampToEdge,
.mag_filter = c.WGPUFilterMode_Linear,
.min_filter = c.WGPUFilterMode_Nearest,
.mipmap_filter = c.WGPUFilterMode_Nearest,
.lod_min_clamp = 0.0,
.lod_max_clamp = std.math.f32_max,
.compare = c.WGPUCompareFunction_Undefined,
},
);
////////////////////////////////////////////////////////////////////////////
// Uniform buffers
const uniform_buffer = c.wgpu_device_create_buffer(
device,
&(c.WGPUBufferDescriptor){
.label = "Uniforms",
.size = @sizeOf(c.fpUniforms),
.usage = c.WGPUBufferUsage_UNIFORM | c.WGPUBufferUsage_COPY_DST,
.mapped_at_creation = false,
},
);
const char_grid_buffer = c.wgpu_device_create_buffer(
device,
&(c.WGPUBufferDescriptor){
.label = "Character grid",
.size = @sizeOf(u32) * 512 * 512,
.usage = c.WGPUBufferUsage_STORAGE | c.WGPUBufferUsage_COPY_DST,
.mapped_at_creation = false,
},
);
////////////////////////////////////////////////////////////////////////////
// Bind groups (?!)
const bind_group_layout_entries = [_]c.WGPUBindGroupLayoutEntry{
(c.WGPUBindGroupLayoutEntry){
.binding = 0,
.visibility = c.WGPUShaderStage_FRAGMENT,
.ty = c.WGPUBindingType_SampledTexture,
.multisampled = false,
.view_dimension = c.WGPUTextureViewDimension_D2,
.texture_component_type = c.WGPUTextureComponentType_Uint,
.storage_texture_format = c.WGPUTextureFormat_Rgba8Unorm,
.count = undefined,
.has_dynamic_offset = undefined,
.min_buffer_binding_size = undefined,
},
(c.WGPUBindGroupLayoutEntry){
.binding = 1,
.visibility = c.WGPUShaderStage_FRAGMENT,
.ty = c.WGPUBindingType_Sampler,
.multisampled = undefined,
.view_dimension = undefined,
.texture_component_type = undefined,
.storage_texture_format = undefined,
.count = undefined,
.has_dynamic_offset = undefined,
.min_buffer_binding_size = undefined,
},
(c.WGPUBindGroupLayoutEntry){
.binding = 2,
.visibility = c.WGPUShaderStage_VERTEX | c.WGPUShaderStage_FRAGMENT,
.ty = c.WGPUBindingType_UniformBuffer,
.has_dynamic_offset = false,
.min_buffer_binding_size = 0,
.multisampled = undefined,
.view_dimension = undefined,
.texture_component_type = undefined,
.storage_texture_format = undefined,
.count = undefined,
},
(c.WGPUBindGroupLayoutEntry){
.binding = 3,
.visibility = c.WGPUShaderStage_VERTEX,
.ty = c.WGPUBindingType_StorageBuffer,
.has_dynamic_offset = false,
.min_buffer_binding_size = 0,
.multisampled = undefined,
.view_dimension = undefined,
.texture_component_type = undefined,
.storage_texture_format = undefined,
.count = undefined,
},
};
const bind_group_layout = c.wgpu_device_create_bind_group_layout(
device,
&(c.WGPUBindGroupLayoutDescriptor){
.label = "bind group layout",
.entries = &bind_group_layout_entries,
.entries_length = bind_group_layout_entries.len,
},
);
defer c.wgpu_bind_group_layout_destroy(bind_group_layout);
const bind_group_entries = [_]c.WGPUBindGroupEntry{
(c.WGPUBindGroupEntry){
.binding = 0,
.texture_view = tex_view,
.sampler = 0, // None
.buffer = 0, // None
.offset = undefined,
.size = undefined,
},
(c.WGPUBindGroupEntry){
.binding = 1,
.sampler = tex_sampler,
.texture_view = 0, // None
.buffer = 0, // None
.offset = undefined,
.size = undefined,
},
(c.WGPUBindGroupEntry){
.binding = 2,
.buffer = uniform_buffer,
.offset = 0,
.size = @sizeOf(c.fpUniforms),
.sampler = 0, // None
.texture_view = 0, // None
},
(c.WGPUBindGroupEntry){
.binding = 3,
.buffer = char_grid_buffer,
.offset = 0,
.size = @sizeOf(u32) * 512 * 512,
.sampler = 0, // None
.texture_view = 0, // None
},
};
const bind_group = c.wgpu_device_create_bind_group(
device,
&(c.WGPUBindGroupDescriptor){
.label = "bind group",
.layout = bind_group_layout,
.entries = &bind_group_entries,
.entries_length = bind_group_entries.len,
},
);
const bind_group_layouts = [_]c.WGPUBindGroupId{bind_group_layout};
////////////////////////////////////////////////////////////////////////////
// Render pipelines (?!?)
const pipeline_layout = c.wgpu_device_create_pipeline_layout(
device,
&(c.WGPUPipelineLayoutDescriptor){
.bind_group_layouts = &bind_group_layouts,
.bind_group_layouts_length = bind_group_layouts.len,
},
);
defer c.wgpu_pipeline_layout_destroy(pipeline_layout);
const render_pipeline = c.wgpu_device_create_render_pipeline(
device,
&(c.WGPURenderPipelineDescriptor){
.layout = pipeline_layout,
.vertex_stage = (c.WGPUProgrammableStageDescriptor){
.module = vert_shader,
.entry_point = "main",
},
.fragment_stage = &(c.WGPUProgrammableStageDescriptor){
.module = frag_shader,
.entry_point = "main",
},
.rasterization_state = &(c.WGPURasterizationStateDescriptor){
.front_face = c.WGPUFrontFace_Ccw,
.cull_mode = c.WGPUCullMode_None,
.depth_bias = 0,
.depth_bias_slope_scale = 0.0,
.depth_bias_clamp = 0.0,
},
.primitive_topology = c.WGPUPrimitiveTopology_TriangleList,
.color_states = &(c.WGPUColorStateDescriptor){
.format = c.WGPUTextureFormat_Bgra8Unorm,
.alpha_blend = (c.WGPUBlendDescriptor){
.src_factor = c.WGPUBlendFactor_One,
.dst_factor = c.WGPUBlendFactor_Zero,
.operation = c.WGPUBlendOperation_Add,
},
.color_blend = (c.WGPUBlendDescriptor){
.src_factor = c.WGPUBlendFactor_One,
.dst_factor = c.WGPUBlendFactor_Zero,
.operation = c.WGPUBlendOperation_Add,
},
.write_mask = c.WGPUColorWrite_ALL,
},
.color_states_length = 1,
.depth_stencil_state = null,
.vertex_state = (c.WGPUVertexStateDescriptor){
.index_format = c.WGPUIndexFormat_Uint16,
.vertex_buffers = null,
.vertex_buffers_length = 0,
},
.sample_count = 1,
.sample_mask = 0,
.alpha_to_coverage_enabled = false,
},
);
var out = Renderer{
.tex = tex,
.tex_view = tex_view,
.tex_sampler = tex_sampler,
.swap_chain = undefined, // assigned in resize_swap_chain below
.width = undefined,
.height = undefined,
.device = device,
.surface = surface,
.queue = c.wgpu_device_get_default_queue(device),
.bind_group = bind_group,
.uniform_buffer = uniform_buffer,
.char_grid_buffer = char_grid_buffer,
.render_pipeline = render_pipeline,
.preview = null,
.blit = try Blit.init(alloc, device),
.dt = undefined,
.dt_index = 0,
};
out.reset_dt();
out.update_font_tex(font);
return out;
}
pub fn clear_preview(self: *Self, alloc: *std.mem.Allocator) void {
if (self.preview) |p| {
p.deinit();
alloc.destroy(p);
self.preview = null;
}
}
fn reset_dt(self: *Self) void {
var i: usize = 0;
while (i < self.dt.len) : (i += 1) {
self.dt[i] = 0;
}
self.dt_index = 0;
}
pub fn update_preview(self: *Self, alloc: *std.mem.Allocator, s: Shader) !void {
self.clear_preview(alloc);
// Construct a new Preview with our current state
var p = try alloc.create(Preview);
p.* = try Preview.init(alloc, self.device, s.spirv, s.has_time);
p.set_size(self.width, self.height);
self.preview = p;
self.blit.bind_to_tex(p.tex_view[1]);
self.reset_dt();
}
pub fn update_font_tex(self: *Self, font: *const ft.Atlas) void {
const tex_size = (c.WGPUExtent3d){
.width = @intCast(u32, font.tex_size),
.height = @intCast(u32, font.tex_size),
.depth = 1,
};
c.wgpu_queue_write_texture(
self.queue,
&(c.WGPUTextureCopyView){
.texture = self.tex,
.mip_level = 0,
.origin = (c.WGPUOrigin3d){ .x = 0, .y = 0, .z = 0 },
},
@ptrCast([*]const u8, font.tex.ptr),
font.tex.len * @sizeOf(u32),
&(c.WGPUTextureDataLayout){
.offset = 0,
.bytes_per_row = @intCast(u32, font.tex_size) * @sizeOf(u32),
.rows_per_image = @intCast(u32, font.tex_size) * @sizeOf(u32),
},
&tex_size,
);
}
pub fn redraw(self: *Self, total_tiles: u32) void {
const start_ms = std.time.milliTimestamp();
// Render the preview to its internal texture, then blit from that
// texture to the main swap chain. This lets us render the preview
// at a different resolution from the rest of the UI.
if (self.preview) |p| {
p.redraw();
if ((p.uniforms._tiles_per_side > 1 and p.uniforms._tile_num != 0) or
p.draw_continuously)
{
c.glfwPostEmptyEvent();
}
}
// Begin the main render operation
const next_texture = c.wgpu_swap_chain_get_next_texture(self.swap_chain);
if (next_texture.view_id == 0) {
std.debug.panic("Cannot acquire next swap chain texture", .{});
}
const cmd_encoder = c.wgpu_device_create_command_encoder(
self.device,
&(c.WGPUCommandEncoderDescriptor){ .label = "main encoder" },
);
const color_attachments = [_]c.WGPURenderPassColorAttachmentDescriptor{
(c.WGPURenderPassColorAttachmentDescriptor){
.attachment = next_texture.view_id,
.resolve_target = 0,
.channel = (c.WGPUPassChannel_Color){
.load_op = c.WGPULoadOp_Clear,
.store_op = c.WGPUStoreOp_Store,
.clear_value = (c.WGPUColor){
.r = 0.0,
.g = 0.0,
.b = 0.0,
.a = 1.0,
},
.read_only = false,
},
},
};
const rpass = c.wgpu_command_encoder_begin_render_pass(
cmd_encoder,
&(c.WGPURenderPassDescriptor){
.color_attachments = &color_attachments,
.color_attachments_length = color_attachments.len,
.depth_stencil_attachment = null,
},
);
c.wgpu_render_pass_set_pipeline(rpass, self.render_pipeline);
c.wgpu_render_pass_set_bind_group(rpass, 0, self.bind_group, null, 0);
c.wgpu_render_pass_draw(rpass, total_tiles * 6, 1, 0, 0);
c.wgpu_render_pass_end_pass(rpass);
if (self.preview != null) {
self.blit.redraw(next_texture, cmd_encoder);
}
const cmd_buf = c.wgpu_command_encoder_finish(cmd_encoder, null);
c.wgpu_queue_submit(self.queue, &cmd_buf, 1);
c.wgpu_swap_chain_present(self.swap_chain);
const end_ms = std.time.milliTimestamp();
self.dt[self.dt_index] = end_ms - start_ms;
self.dt_index = (self.dt_index + 1) % self.dt.len;
var dt_local = self.dt;
const asc = comptime std.sort.asc(i64);
std.sort.sort(i64, dt_local[0..], {}, asc);
const dt = dt_local[self.dt.len / 2];
if (dt > 33) {
if (self.preview) |p| {
p.adjust_tiles(dt);
self.reset_dt();
}
}
}
pub fn deinit(self: *Self, alloc: *std.mem.Allocator) void {
c.wgpu_texture_destroy(self.tex);
c.wgpu_texture_view_destroy(self.tex_view);
c.wgpu_sampler_destroy(self.tex_sampler);
c.wgpu_bind_group_destroy(self.bind_group);
c.wgpu_buffer_destroy(self.uniform_buffer);
c.wgpu_buffer_destroy(self.char_grid_buffer);
c.wgpu_render_pipeline_destroy(self.render_pipeline);
if (self.preview) |p| {
p.deinit();
alloc.destroy(p);
}
self.blit.deinit();
}
pub fn update_grid(self: *Self, char_grid: []u32) void {
c.wgpu_queue_write_buffer(
self.queue,
self.char_grid_buffer,
0,
@ptrCast([*c]const u8, char_grid.ptr),
char_grid.len * @sizeOf(u32),
);
}
pub fn resize_swap_chain(self: *Self, width: u32, height: u32) void {
self.swap_chain = c.wgpu_device_create_swap_chain(
self.device,
self.surface,
&(c.WGPUSwapChainDescriptor){
.usage = c.WGPUTextureUsage_OUTPUT_ATTACHMENT,
.format = c.WGPUTextureFormat_Bgra8Unorm,
.width = width,
.height = height,
.present_mode = c.WGPUPresentMode_Fifo,
},
);
// Track width and height so that we can set them in a Preview
// (even if one isn't loaded right now)
self.width = width;
self.height = height;
if (self.preview) |p| {
p.set_size(width, height);
self.blit.bind_to_tex(p.tex_view[1]);
}
}
pub fn update_uniforms(self: *Self, u: *const c.fpUniforms) void {
c.wgpu_queue_write_buffer(
self.queue,
self.uniform_buffer,
0,
@ptrCast([*c]const u8, u),
@sizeOf(c.fpUniforms),
);
}
};
export fn adapter_cb(received: c.WGPUAdapterId, data: ?*c_void) void {
@ptrCast(*c.WGPUAdapterId, @alignCast(8, data)).* = received;
} | src/renderer.zig |
const std = @import("std");
const util = @import("util.zig");
const data = @embedFile("../data/day13.txt");
pub const FoldAxis = union(enum) {
horizontal: i32,
vertical: i32,
};
/// Structure used to store which cells have dots on the paper grid. Because the input we were given
/// is _sparse_ (eg. the number of points with dots is very few compared to the overall total
/// number of points on the grid), we'll store dots in a map instead of some sort of array structure.
pub const Paper = struct {
const Self = @This();
dots: util.Map(util.Point(i32), void),
fold_buffer: util.List(util.Point(i32)),
pub fn init(allocator: *util.Allocator) Self {
return .{
.dots = util.Map(util.Point(i32), void).init(allocator),
.fold_buffer = util.List(util.Point(i32)).init(allocator),
};
}
pub fn deinit(self: *Self) void {
self.dots.deinit();
self.fold_buffer.deinit();
}
pub fn addDot(self: *Self, point: util.Point(i32)) !void {
try self.dots.put(point, {});
}
pub fn performFold(self: *Self, fold: FoldAxis) !void {
// TODO: Fix lots of duplication of code
switch (fold) {
.horizontal => |val| {
// Create a list of the points affected by the fold, so we can iterate over them
// and also change the map inthe process
var values_it = self.dots.keyIterator();
while (values_it.next()) |dot| {
if (dot.y > val) {
try self.fold_buffer.append(dot.*);
}
}
for (self.fold_buffer.items) |dot| {
// Calculate how far the dot is from the fold line on the appropriate axis,
// and calculate its mirrored position on the other side of the fold line.
const diff = dot.y - val;
const mirror_y = val - diff;
// If the folded point isn't off the edge of the map, place it
if (mirror_y >= 0) {
try self.addDot(.{ .x = dot.x, .y = mirror_y });
}
// Remove the original dot from the map
_ = self.dots.remove(dot);
}
},
.vertical => |val| {
// Create a list of the points affected by the fold, so we can iterate over them
// and also change the map inthe process
var values_it = self.dots.keyIterator();
while (values_it.next()) |dot| {
if (dot.x > val) {
try self.fold_buffer.append(dot.*);
}
}
for (self.fold_buffer.items) |dot| {
// Calculate how far the dot is from the fold line on the appropriate axis,
// and calculate its mirrored position on the other side of the fold line.
const diff = dot.x - val;
const mirror_x = val - diff;
// If the folded point isn't off the edge of the map, place it
if (mirror_x >= 0) {
try self.addDot(.{ .x = mirror_x, .y = dot.y });
}
// Remove the original dot from the map
_ = self.dots.remove(dot);
}
},
}
// Clear fold buffer for next time
self.fold_buffer.clearRetainingCapacity();
}
/// Displays the map in the format AoC demonstrates.
pub fn display(self: Self) void {
// Find x/y max
var max = util.Point(i32){ .x = 0, .y = 0 };
var it = self.dots.keyIterator();
while (it.next()) |dot| {
if (dot.x > max.x) max.x = dot.x;
if (dot.y > max.y) max.y = dot.y;
}
// Print
var y: i32 = 0;
while (y <= max.y) : (y += 1) {
var x: i32 = 0;
while (x <= max.x) : (x += 1) {
const ch: u8 = if (self.dots.get(.{ .x = x, .y = y })) |_| '#' else '.';
util.print("{c}", .{ch});
}
util.print("\n", .{});
}
}
};
pub fn main() !void {
defer {
const leaks = util.gpa_impl.deinit();
std.debug.assert(!leaks);
}
// Our map structure.
var map = Paper.init(util.gpa);
defer map.deinit();
// List of axis to fold on
var folds = util.List(FoldAxis).init(util.gpa);
defer folds.deinit();
// Parse input
var it = util.tokenize(u8, data, "\n");
while (it.next()) |line| {
// Handle fold or point as applicable
if (std.mem.startsWith(u8, line, "fold along")) {
var fold_it = util.tokenize(u8, line, " =");
// Ignore "fold" and "along"
_ = fold_it.next() orelse return error.InvalidInput;
_ = fold_it.next() orelse return error.InvalidInput;
const axis = fold_it.next() orelse return error.InvalidInput;
const value = util.parseInt(i32, fold_it.next() orelse return error.InvalidInput, 10) catch {
return error.InvalidInput;
};
if (axis.len != 1) return error.InvalidInput;
const fold = switch (axis[0]) {
'x' => FoldAxis{ .vertical = value },
'y' => FoldAxis{ .horizontal = value },
else => return error.InvalidInput,
};
try folds.append(fold);
} else {
var xy_it = util.tokenize(u8, line, ",");
const point = util.Point(i32){
.x = util.parseInt(i32, xy_it.next() orelse return error.InvalidInput, 10) catch {
return error.InvalidInput;
},
.y = util.parseInt(i32, xy_it.next() orelse return error.InvalidInput, 10) catch {
return error.InvalidInput;
},
};
try map.addDot(point);
}
}
if (folds.items.len == 0) return error.InvalidInput;
// Perform all folds
var dots_after_first: usize = 0;
for (folds.items) |fold, idx| {
// Perform fold
try map.performFold(fold);
// Record answer to part 1 as we go
if (idx == 0) dots_after_first = map.dots.count();
}
util.print("Part 1: dots after first fold: {d}\n", .{dots_after_first});
util.print("Part 2: Displayed value:\n", .{});
map.display();
} | src/day13.zig |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.