code
stringlengths 38
801k
| repo_path
stringlengths 6
263
|
---|---|
/// Construct a Fenwick type for the given numeric type. Note that this is an implicit tree, where
/// an array is used to maintain prefix sums. Sum queries and point updates are done in log(n) time.
pub fn Fenwick(comptime T: type) type {
return struct {
data: []T = undefined,
/// Returns an a Fenwick tree initialized to all zeros using `buffer` as backing memory
pub fn initZero(buffer: []T) @This() {
var instance: @This() = .{
.data = buffer,
};
instance.clear();
return instance;
}
/// Given an array of numbers, produce a Fenwick tree using `buffer` as backing memory
/// The initialization is done in O(n log(n)) time
pub fn initFrom(buffer: []T, numbers: []T) @This() {
var instance: @This() = .{
.data = buffer,
};
instance.clear();
var i: usize = 0;
while (i < instance.data.len) : (i += 1) {
instance.update(i, numbers[@intCast(usize, i)]);
}
return instance;
}
/// Initialize all items in the tree to zero
pub fn clear(self: *@This()) void {
for (self.data) |*item| {
item.* = 0;
}
}
/// The cumulutative sum up to `index`
pub fn sum(self: *@This(), index: usize) T {
var cumulative_sum: T = 0;
var i: isize = @intCast(isize, index);
// While this implements 0-based indexing, it's easier to visualize the algorithm with
// 1-based indexing representing a tree of partial sums. Every item at an index that's a
// power of two is the prefix sum of the [0..index] numbers. Clearing the LSB yields the
// parent "node" in the prefix tree, which is added to the sum. The process repeats
// until the root node is found.
while (i >= 0) {
cumulative_sum += self.data[@intCast(usize, i)];
i = (i & (i + 1)) - 1;
}
return cumulative_sum;
}
/// Returns the cumulutative sum in the range [left..right] (both indices are inclusive)
pub fn sumRange(self: *@This(), left_index: usize, right_index: usize) T {
return self.sum(right_index) - if (left_index > 0) self.sum(left_index - 1) else 0;
}
/// Add `delta` at `index`
/// Note that `delta` can be negative for signed Ts, effectively subtracting at `index`
pub fn update(self: *@This(), index: usize, delta: T) void {
var i = index;
while (i < self.data.len) : (i |= (i + 1)) {
self.data[i] += delta;
}
}
/// Return a single element's value
pub fn get(self: *@This(), index: usize) T {
var val: T = self.data[index];
var i: isize = @intCast(isize, index);
var pow_of_two: isize = 1;
while ((i & pow_of_two) == pow_of_two) : (pow_of_two <<= 1) {
val -= self.data[@intCast(usize, i - pow_of_two)];
}
return val;
}
/// Set a single element's value and recalculate prefix sums
pub fn set(self: *@This(), index: usize, value: T) void {
self.update(index, value - self.get(index));
}
};
}
const std = @import("std");
const expectEqual = std.testing.expectEqual;
/// Sum of sequence from 1 to `n`
fn gauss(n: anytype) @TypeOf(n) {
return @divExact(n * (n + 1), 2);
}
test "update" {
var buffer = [_]i32{0} ** 10;
var fenwick = Fenwick(i32).initZero(&buffer);
fenwick.update(5, 10);
try expectEqual(fenwick.sum(5), 10);
fenwick.update(0, 2);
try expectEqual(fenwick.sum(5), 12);
fenwick.update(9, 2);
try expectEqual(fenwick.sum(9), 14);
fenwick.update(9, -2);
try expectEqual(fenwick.sum(9), 12);
try expectEqual(fenwick.get(5), 10);
fenwick.set(5, 9);
try expectEqual(fenwick.get(5), 9);
try expectEqual(fenwick.sum(9), 11);
}
test "set" {
const N = 50;
var buffer = [_]i32{0} ** N;
var fenwick = Fenwick(i32).initZero(&buffer);
var i: i32 = 0;
while (i < N) : (i += 1) {
fenwick.set(@intCast(usize, i), i + 1);
}
i = 0;
while (i < N) : (i += 1) {
fenwick.set(@intCast(usize, i), i + 1);
}
try expectEqual(fenwick.sum(N-1), gauss(N));
i = 0;
while (i < N) : (i += 1) {
try expectEqual(fenwick.get(@intCast(usize, i)), i + 1);
}
}
test "empty" {
var data: [0]i32 = .{};
var buffer = [_]i32{0} ** 0;
var fenwick = Fenwick(i32).initFrom(&buffer, &data);
fenwick.clear();
}
test "array with negative culumative sums" {
var data: [5]i32 = .{ -1, -5, -1, 0, 5 };
var buffer = [_]i32{0} ** 5;
var fenwick = Fenwick(i32).initFrom(&buffer, &data);
try expectEqual(fenwick.sum(0), -1);
try expectEqual(fenwick.sum(4), -2);
try expectEqual(fenwick.sum(1), -6);
try expectEqual(fenwick.sumRange(0, 1), -6);
try expectEqual(fenwick.sumRange(1, 2), -6);
try expectEqual(fenwick.sumRange(0, 4), -2);
try expectEqual(fenwick.sumRange(4, 4), 5);
fenwick.clear();
try expectEqual(fenwick.sumRange(0, 4), 0);
}
test "range backwards" {
var data: [5]u16 = .{ 5, 4, 3, 2, 1 };
var buffer = [_]u16{0} ** 5;
var fenwick = Fenwick(u16).initFrom(&buffer, &data);
try expectEqual(fenwick.sum(4), 15);
try expectEqual(fenwick.sum(3), 14);
try expectEqual(fenwick.sum(2), 12);
try expectEqual(fenwick.sum(1), 9);
try expectEqual(fenwick.sum(0), 5);
}
test "range floats" {
var data: [5]f16 = .{ 1.5, 2.5, 3.5, 4.5, 5.5 };
var buffer = [_]f16{0} ** 5;
var fenwick = Fenwick(f16).initFrom(&buffer, &data);
try expectEqual(fenwick.sum(4), 17.5);
try expectEqual(fenwick.sum(3), 12);
try expectEqual(fenwick.sum(2), 7.5);
try expectEqual(fenwick.sum(1), 4);
try expectEqual(fenwick.sum(0), 1.5);
}
test "larger range" {
var data: [264]u16 = .{
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
65, 66, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62,
63, 64, 65, 66, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
61, 62, 63, 64, 65, 66, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58,
59, 60, 61, 62, 63, 64, 65, 66,
};
var buffer = [_]u16{0} ** (264);
var fenwick = Fenwick(u16).initFrom(&buffer, &data);
try expectEqual(fenwick.sum(0), 1);
try expectEqual(fenwick.sum(263), 8844);
try expectEqual(fenwick.sum(262), 8844 - 66);
try expectEqual(fenwick.sumRange(1,263), 8843);
try expectEqual(fenwick.sumRange(10, 12), 36);
try expectEqual(fenwick.sumRange(82, 129), 1944);
try expectEqual(fenwick.sumRange(82, 83), 17 + 18);
} | src/main.zig |
pub const MAX_COUNTER_PATH = @as(u32, 256);
pub const PDH_MAX_COUNTER_NAME = @as(u32, 1024);
pub const PDH_MAX_INSTANCE_NAME = @as(u32, 1024);
pub const PDH_MAX_COUNTER_PATH = @as(u32, 2048);
pub const PDH_MAX_DATASOURCE_PATH = @as(u32, 1024);
pub const PDH_MAX_SCALE = @as(i32, 7);
pub const PDH_MIN_SCALE = @as(i32, -7);
pub const PDH_NOEXPANDCOUNTERS = @as(u32, 1);
pub const PDH_NOEXPANDINSTANCES = @as(u32, 2);
pub const PDH_REFRESHCOUNTERS = @as(u32, 4);
pub const PDH_LOG_TYPE_RETIRED_BIN = @as(u32, 3);
pub const PDH_LOG_TYPE_TRACE_KERNEL = @as(u32, 4);
pub const PDH_LOG_TYPE_TRACE_GENERIC = @as(u32, 5);
pub const PERF_PROVIDER_USER_MODE = @as(u32, 0);
pub const PERF_PROVIDER_KERNEL_MODE = @as(u32, 1);
pub const PERF_PROVIDER_DRIVER = @as(u32, 2);
pub const PERF_COUNTERSET_FLAG_MULTIPLE = @as(u32, 2);
pub const PERF_COUNTERSET_FLAG_AGGREGATE = @as(u32, 4);
pub const PERF_COUNTERSET_FLAG_HISTORY = @as(u32, 8);
pub const PERF_COUNTERSET_FLAG_INSTANCE = @as(u32, 16);
pub const PERF_COUNTERSET_SINGLE_INSTANCE = @as(u32, 0);
pub const PERF_AGGREGATE_MAX = @as(u32, 4);
pub const PERF_ATTRIB_BY_REFERENCE = @as(u64, 1);
pub const PERF_ATTRIB_NO_DISPLAYABLE = @as(u64, 2);
pub const PERF_ATTRIB_NO_GROUP_SEPARATOR = @as(u64, 4);
pub const PERF_ATTRIB_DISPLAY_AS_REAL = @as(u64, 8);
pub const PERF_ATTRIB_DISPLAY_AS_HEX = @as(u64, 16);
pub const PERF_WILDCARD_COUNTER = @as(u32, 4294967295);
pub const PERF_MAX_INSTANCE_NAME = @as(u32, 1024);
pub const PERF_ADD_COUNTER = @as(u32, 1);
pub const PERF_REMOVE_COUNTER = @as(u32, 2);
pub const PERF_ENUM_INSTANCES = @as(u32, 3);
pub const PERF_COLLECT_START = @as(u32, 5);
pub const PERF_COLLECT_END = @as(u32, 6);
pub const PERF_FILTER = @as(u32, 9);
pub const PERF_DATA_VERSION = @as(u32, 1);
pub const PERF_DATA_REVISION = @as(u32, 1);
pub const PERF_NO_INSTANCES = @as(i32, -1);
pub const PERF_SIZE_DWORD = @as(u32, 0);
pub const PERF_SIZE_LARGE = @as(u32, 256);
pub const PERF_SIZE_ZERO = @as(u32, 512);
pub const PERF_SIZE_VARIABLE_LEN = @as(u32, 768);
pub const PERF_TYPE_NUMBER = @as(u32, 0);
pub const PERF_TYPE_COUNTER = @as(u32, 1024);
pub const PERF_TYPE_TEXT = @as(u32, 2048);
pub const PERF_TYPE_ZERO = @as(u32, 3072);
pub const PERF_NUMBER_HEX = @as(u32, 0);
pub const PERF_NUMBER_DECIMAL = @as(u32, 65536);
pub const PERF_NUMBER_DEC_1000 = @as(u32, 131072);
pub const PERF_COUNTER_VALUE = @as(u32, 0);
pub const PERF_COUNTER_RATE = @as(u32, 65536);
pub const PERF_COUNTER_FRACTION = @as(u32, 131072);
pub const PERF_COUNTER_BASE = @as(u32, 196608);
pub const PERF_COUNTER_ELAPSED = @as(u32, 262144);
pub const PERF_COUNTER_QUEUELEN = @as(u32, 327680);
pub const PERF_COUNTER_HISTOGRAM = @as(u32, 393216);
pub const PERF_COUNTER_PRECISION = @as(u32, 458752);
pub const PERF_TEXT_UNICODE = @as(u32, 0);
pub const PERF_TEXT_ASCII = @as(u32, 65536);
pub const PERF_TIMER_TICK = @as(u32, 0);
pub const PERF_TIMER_100NS = @as(u32, 1048576);
pub const PERF_OBJECT_TIMER = @as(u32, 2097152);
pub const PERF_DELTA_COUNTER = @as(u32, 4194304);
pub const PERF_DELTA_BASE = @as(u32, 8388608);
pub const PERF_INVERSE_COUNTER = @as(u32, 16777216);
pub const PERF_MULTI_COUNTER = @as(u32, 33554432);
pub const PERF_DISPLAY_NO_SUFFIX = @as(u32, 0);
pub const PERF_DISPLAY_PER_SEC = @as(u32, 268435456);
pub const PERF_DISPLAY_PERCENT = @as(u32, 536870912);
pub const PERF_DISPLAY_SECONDS = @as(u32, 805306368);
pub const PERF_DISPLAY_NOSHOW = @as(u32, 1073741824);
pub const PERF_COUNTER_HISTOGRAM_TYPE = @as(u32, 2147483648);
pub const PERF_NO_UNIQUE_ID = @as(i32, -1);
pub const MAX_PERF_OBJECTS_IN_QUERY_FUNCTION = @as(i32, 64);
pub const WINPERF_LOG_NONE = @as(u32, 0);
pub const WINPERF_LOG_USER = @as(u32, 1);
pub const WINPERF_LOG_DEBUG = @as(u32, 2);
pub const WINPERF_LOG_VERBOSE = @as(u32, 3);
pub const PLA_CAPABILITY_LOCAL = @as(u32, 268435456);
pub const PLA_CAPABILITY_V1_SVC = @as(u32, 1);
pub const PLA_CAPABILITY_V1_SESSION = @as(u32, 2);
pub const PLA_CAPABILITY_V1_SYSTEM = @as(u32, 4);
pub const PLA_CAPABILITY_LEGACY_SESSION = @as(u32, 8);
pub const PLA_CAPABILITY_LEGACY_SVC = @as(u32, 16);
pub const PLA_CAPABILITY_AUTOLOGGER = @as(u32, 32);
//--------------------------------------------------------------------------------
// Section: Types (112)
//--------------------------------------------------------------------------------
pub const PERF_DETAIL = enum(u32) {
NOVICE = 100,
ADVANCED = 200,
EXPERT = 300,
WIZARD = 400,
};
pub const PERF_DETAIL_NOVICE = PERF_DETAIL.NOVICE;
pub const PERF_DETAIL_ADVANCED = PERF_DETAIL.ADVANCED;
pub const PERF_DETAIL_EXPERT = PERF_DETAIL.EXPERT;
pub const PERF_DETAIL_WIZARD = PERF_DETAIL.WIZARD;
pub const REAL_TIME_DATA_SOURCE_ID_FLAGS = enum(u32) {
REGISTRY = 1,
WBEM = 4,
};
pub const DATA_SOURCE_REGISTRY = REAL_TIME_DATA_SOURCE_ID_FLAGS.REGISTRY;
pub const DATA_SOURCE_WBEM = REAL_TIME_DATA_SOURCE_ID_FLAGS.WBEM;
pub const PDH_PATH_FLAGS = enum(u32) {
RESULT = 1,
INPUT = 2,
NONE = 0,
};
pub const PDH_PATH_WBEM_RESULT = PDH_PATH_FLAGS.RESULT;
pub const PDH_PATH_WBEM_INPUT = PDH_PATH_FLAGS.INPUT;
pub const PDH_PATH_WBEM_NONE = PDH_PATH_FLAGS.NONE;
pub const PDH_FMT = enum(u32) {
DOUBLE = 512,
LARGE = 1024,
LONG = 256,
};
pub const PDH_FMT_DOUBLE = PDH_FMT.DOUBLE;
pub const PDH_FMT_LARGE = PDH_FMT.LARGE;
pub const PDH_FMT_LONG = PDH_FMT.LONG;
pub const PDH_LOG_TYPE = enum(u32) {
UNDEFINED = 0,
CSV = 1,
SQL = 7,
TSV = 2,
BINARY = 8,
PERFMON = 6,
};
pub const PDH_LOG_TYPE_UNDEFINED = PDH_LOG_TYPE.UNDEFINED;
pub const PDH_LOG_TYPE_CSV = PDH_LOG_TYPE.CSV;
pub const PDH_LOG_TYPE_SQL = PDH_LOG_TYPE.SQL;
pub const PDH_LOG_TYPE_TSV = PDH_LOG_TYPE.TSV;
pub const PDH_LOG_TYPE_BINARY = PDH_LOG_TYPE.BINARY;
pub const PDH_LOG_TYPE_PERFMON = PDH_LOG_TYPE.PERFMON;
pub const PDH_LOG = enum(u32) {
READ_ACCESS = 65536,
WRITE_ACCESS = 131072,
UPDATE_ACCESS = 262144,
};
pub const PDH_LOG_READ_ACCESS = PDH_LOG.READ_ACCESS;
pub const PDH_LOG_WRITE_ACCESS = PDH_LOG.WRITE_ACCESS;
pub const PDH_LOG_UPDATE_ACCESS = PDH_LOG.UPDATE_ACCESS;
pub const PDH_SELECT_DATA_SOURCE_FLAGS = enum(u32) {
FILE_BROWSER_ONLY = 1,
NONE = 0,
};
pub const PDH_FLAGS_FILE_BROWSER_ONLY = PDH_SELECT_DATA_SOURCE_FLAGS.FILE_BROWSER_ONLY;
pub const PDH_FLAGS_NONE = PDH_SELECT_DATA_SOURCE_FLAGS.NONE;
pub const PDH_DLL_VERSION = enum(u32) {
CVERSION_WIN50 = 1280,
VERSION = 1283,
};
pub const PDH_CVERSION_WIN50 = PDH_DLL_VERSION.CVERSION_WIN50;
pub const PDH_VERSION = PDH_DLL_VERSION.VERSION;
pub const PERF_COUNTER_AGGREGATE_FUNC = enum(u32) {
UNDEFINED = 0,
TOTAL = 1,
AVG = 2,
MIN = 3,
};
pub const PERF_AGGREGATE_UNDEFINED = PERF_COUNTER_AGGREGATE_FUNC.UNDEFINED;
pub const PERF_AGGREGATE_TOTAL = PERF_COUNTER_AGGREGATE_FUNC.TOTAL;
pub const PERF_AGGREGATE_AVG = PERF_COUNTER_AGGREGATE_FUNC.AVG;
pub const PERF_AGGREGATE_MIN = PERF_COUNTER_AGGREGATE_FUNC.MIN;
// TODO: this type has a FreeFunc 'PerfStopProvider', what can Zig do with this information?
pub const PerfProviderHandle = isize;
// TODO: this type has a FreeFunc 'PerfCloseQueryHandle', what can Zig do with this information?
pub const PerfQueryHandle = isize;
pub const PERF_COUNTERSET_INFO = extern struct {
CounterSetGuid: Guid,
ProviderGuid: Guid,
NumCounters: u32,
InstanceType: u32,
};
pub const PERF_COUNTER_INFO = extern struct {
CounterId: u32,
Type: u32,
Attrib: u64,
Size: u32,
DetailLevel: u32,
Scale: i32,
Offset: u32,
};
pub const PERF_COUNTERSET_INSTANCE = extern struct {
CounterSetGuid: Guid,
dwSize: u32,
InstanceId: u32,
InstanceNameOffset: u32,
InstanceNameSize: u32,
};
pub const PERF_COUNTER_IDENTITY = extern struct {
CounterSetGuid: Guid,
BufferSize: u32,
CounterId: u32,
InstanceId: u32,
MachineOffset: u32,
NameOffset: u32,
Reserved: u32,
};
pub const PERFLIBREQUEST = fn(
RequestCode: u32,
Buffer: ?*c_void,
BufferSize: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const PERF_MEM_ALLOC = fn(
AllocSize: usize,
pContext: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) ?*c_void;
pub const PERF_MEM_FREE = fn(
pBuffer: ?*c_void,
pContext: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub const PERF_PROVIDER_CONTEXT = extern struct {
ContextSize: u32,
Reserved: u32,
ControlCallback: ?PERFLIBREQUEST,
MemAllocRoutine: ?PERF_MEM_ALLOC,
MemFreeRoutine: ?PERF_MEM_FREE,
pMemContext: ?*c_void,
};
pub const PERF_INSTANCE_HEADER = extern struct {
Size: u32,
InstanceId: u32,
};
pub const PerfRegInfoType = enum(i32) {
COUNTERSET_STRUCT = 1,
COUNTER_STRUCT = 2,
COUNTERSET_NAME_STRING = 3,
COUNTERSET_HELP_STRING = 4,
COUNTER_NAME_STRINGS = 5,
COUNTER_HELP_STRINGS = 6,
PROVIDER_NAME = 7,
PROVIDER_GUID = 8,
COUNTERSET_ENGLISH_NAME = 9,
COUNTER_ENGLISH_NAMES = 10,
};
pub const PERF_REG_COUNTERSET_STRUCT = PerfRegInfoType.COUNTERSET_STRUCT;
pub const PERF_REG_COUNTER_STRUCT = PerfRegInfoType.COUNTER_STRUCT;
pub const PERF_REG_COUNTERSET_NAME_STRING = PerfRegInfoType.COUNTERSET_NAME_STRING;
pub const PERF_REG_COUNTERSET_HELP_STRING = PerfRegInfoType.COUNTERSET_HELP_STRING;
pub const PERF_REG_COUNTER_NAME_STRINGS = PerfRegInfoType.COUNTER_NAME_STRINGS;
pub const PERF_REG_COUNTER_HELP_STRINGS = PerfRegInfoType.COUNTER_HELP_STRINGS;
pub const PERF_REG_PROVIDER_NAME = PerfRegInfoType.PROVIDER_NAME;
pub const PERF_REG_PROVIDER_GUID = PerfRegInfoType.PROVIDER_GUID;
pub const PERF_REG_COUNTERSET_ENGLISH_NAME = PerfRegInfoType.COUNTERSET_ENGLISH_NAME;
pub const PERF_REG_COUNTER_ENGLISH_NAMES = PerfRegInfoType.COUNTER_ENGLISH_NAMES;
pub const PERF_COUNTERSET_REG_INFO = extern struct {
CounterSetGuid: Guid,
CounterSetType: u32,
DetailLevel: u32,
NumCounters: u32,
InstanceType: u32,
};
pub const PERF_COUNTER_REG_INFO = extern struct {
CounterId: u32,
Type: u32,
Attrib: u64,
DetailLevel: u32,
DefaultScale: i32,
BaseCounterId: u32,
PerfTimeId: u32,
PerfFreqId: u32,
MultiId: u32,
AggregateFunc: PERF_COUNTER_AGGREGATE_FUNC,
Reserved: u32,
};
pub const PERF_STRING_BUFFER_HEADER = extern struct {
dwSize: u32,
dwCounters: u32,
};
pub const PERF_STRING_COUNTER_HEADER = extern struct {
dwCounterId: u32,
dwOffset: u32,
};
pub const PERF_COUNTER_IDENTIFIER = extern struct {
CounterSetGuid: Guid,
Status: u32,
Size: u32,
CounterId: u32,
InstanceId: u32,
Index: u32,
Reserved: u32,
};
pub const PERF_DATA_HEADER = extern struct {
dwTotalSize: u32,
dwNumCounters: u32,
PerfTimeStamp: i64,
PerfTime100NSec: i64,
PerfFreq: i64,
SystemTime: SYSTEMTIME,
};
pub const PerfCounterDataType = enum(i32) {
ERROR_RETURN = 0,
SINGLE_COUNTER = 1,
MULTIPLE_COUNTERS = 2,
MULTIPLE_INSTANCES = 4,
COUNTERSET = 6,
};
pub const PERF_ERROR_RETURN = PerfCounterDataType.ERROR_RETURN;
pub const PERF_SINGLE_COUNTER = PerfCounterDataType.SINGLE_COUNTER;
pub const PERF_MULTIPLE_COUNTERS = PerfCounterDataType.MULTIPLE_COUNTERS;
pub const PERF_MULTIPLE_INSTANCES = PerfCounterDataType.MULTIPLE_INSTANCES;
pub const PERF_COUNTERSET = PerfCounterDataType.COUNTERSET;
pub const PERF_COUNTER_HEADER = extern struct {
dwStatus: u32,
dwType: PerfCounterDataType,
dwSize: u32,
Reserved: u32,
};
pub const PERF_MULTI_INSTANCES = extern struct {
dwTotalSize: u32,
dwInstances: u32,
};
pub const PERF_MULTI_COUNTERS = extern struct {
dwSize: u32,
dwCounters: u32,
};
pub const PERF_COUNTER_DATA = extern struct {
dwDataSize: u32,
dwSize: u32,
};
pub const PERF_DATA_BLOCK = extern struct {
Signature: [4]u16,
LittleEndian: u32,
Version: u32,
Revision: u32,
TotalByteLength: u32,
HeaderLength: u32,
NumObjectTypes: u32,
DefaultObject: i32,
SystemTime: SYSTEMTIME,
PerfTime: LARGE_INTEGER,
PerfFreq: LARGE_INTEGER,
PerfTime100nSec: LARGE_INTEGER,
SystemNameLength: u32,
SystemNameOffset: u32,
};
pub const PERF_INSTANCE_DEFINITION = extern struct {
ByteLength: u32,
ParentObjectTitleIndex: u32,
ParentObjectInstance: u32,
UniqueID: i32,
NameOffset: u32,
NameLength: u32,
};
pub const PERF_COUNTER_BLOCK = extern struct {
ByteLength: u32,
};
pub const PM_OPEN_PROC = fn(
param0: ?PWSTR,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const PM_COLLECT_PROC = fn(
lpValueName: ?PWSTR,
lppData: ?*?*c_void,
lpcbTotalBytes: ?*u32,
lpNumObjectTypes: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const PM_CLOSE_PROC = fn(
) callconv(@import("std").os.windows.WINAPI) u32;
pub const PM_QUERY_PROC = fn(
param0: ?*u32,
param1: ?*?*c_void,
param2: ?*u32,
param3: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const PDH_RAW_COUNTER = extern struct {
CStatus: u32,
TimeStamp: FILETIME,
FirstValue: i64,
SecondValue: i64,
MultiCount: u32,
};
pub const PDH_RAW_COUNTER_ITEM_A = extern struct {
szName: ?PSTR,
RawValue: PDH_RAW_COUNTER,
};
pub const PDH_RAW_COUNTER_ITEM_W = extern struct {
szName: ?PWSTR,
RawValue: PDH_RAW_COUNTER,
};
pub const PDH_FMT_COUNTERVALUE = extern struct {
CStatus: u32,
Anonymous: extern union {
longValue: i32,
doubleValue: f64,
largeValue: i64,
AnsiStringValue: ?[*:0]const u8,
WideStringValue: ?[*:0]const u16,
},
};
pub const PDH_FMT_COUNTERVALUE_ITEM_A = extern struct {
szName: ?PSTR,
FmtValue: PDH_FMT_COUNTERVALUE,
};
pub const PDH_FMT_COUNTERVALUE_ITEM_W = extern struct {
szName: ?PWSTR,
FmtValue: PDH_FMT_COUNTERVALUE,
};
pub const PDH_STATISTICS = extern struct {
dwFormat: u32,
count: u32,
min: PDH_FMT_COUNTERVALUE,
max: PDH_FMT_COUNTERVALUE,
mean: PDH_FMT_COUNTERVALUE,
};
pub const PDH_COUNTER_PATH_ELEMENTS_A = extern struct {
szMachineName: ?PSTR,
szObjectName: ?PSTR,
szInstanceName: ?PSTR,
szParentInstance: ?PSTR,
dwInstanceIndex: u32,
szCounterName: ?PSTR,
};
pub const PDH_COUNTER_PATH_ELEMENTS_W = extern struct {
szMachineName: ?PWSTR,
szObjectName: ?PWSTR,
szInstanceName: ?PWSTR,
szParentInstance: ?PWSTR,
dwInstanceIndex: u32,
szCounterName: ?PWSTR,
};
pub const PDH_DATA_ITEM_PATH_ELEMENTS_A = extern struct {
szMachineName: ?PSTR,
ObjectGUID: Guid,
dwItemId: u32,
szInstanceName: ?PSTR,
};
pub const PDH_DATA_ITEM_PATH_ELEMENTS_W = extern struct {
szMachineName: ?PWSTR,
ObjectGUID: Guid,
dwItemId: u32,
szInstanceName: ?PWSTR,
};
pub const PDH_COUNTER_INFO_A = extern struct {
dwLength: u32,
dwType: u32,
CVersion: u32,
CStatus: u32,
lScale: i32,
lDefaultScale: i32,
dwUserData: usize,
dwQueryUserData: usize,
szFullPath: ?PSTR,
Anonymous: extern union {
DataItemPath: PDH_DATA_ITEM_PATH_ELEMENTS_A,
CounterPath: PDH_COUNTER_PATH_ELEMENTS_A,
Anonymous: extern struct {
szMachineName: ?PSTR,
szObjectName: ?PSTR,
szInstanceName: ?PSTR,
szParentInstance: ?PSTR,
dwInstanceIndex: u32,
szCounterName: ?PSTR,
},
},
szExplainText: ?PSTR,
DataBuffer: [1]u32,
};
pub const PDH_COUNTER_INFO_W = extern struct {
dwLength: u32,
dwType: u32,
CVersion: u32,
CStatus: u32,
lScale: i32,
lDefaultScale: i32,
dwUserData: usize,
dwQueryUserData: usize,
szFullPath: ?PWSTR,
Anonymous: extern union {
DataItemPath: PDH_DATA_ITEM_PATH_ELEMENTS_W,
CounterPath: PDH_COUNTER_PATH_ELEMENTS_W,
Anonymous: extern struct {
szMachineName: ?PWSTR,
szObjectName: ?PWSTR,
szInstanceName: ?PWSTR,
szParentInstance: ?PWSTR,
dwInstanceIndex: u32,
szCounterName: ?PWSTR,
},
},
szExplainText: ?PWSTR,
DataBuffer: [1]u32,
};
pub const PDH_TIME_INFO = extern struct {
StartTime: i64,
EndTime: i64,
SampleCount: u32,
};
pub const PDH_RAW_LOG_RECORD = extern struct {
dwStructureSize: u32,
dwRecordType: PDH_LOG_TYPE,
dwItems: u32,
RawBytes: [1]u8,
};
pub const PDH_LOG_SERVICE_QUERY_INFO_A = extern struct {
dwSize: u32,
dwFlags: u32,
dwLogQuota: u32,
szLogFileCaption: ?PSTR,
szDefaultDir: ?PSTR,
szBaseFileName: ?PSTR,
dwFileType: u32,
dwReserved: u32,
Anonymous: extern union {
Anonymous1: extern struct {
PdlAutoNameInterval: u32,
PdlAutoNameUnits: u32,
PdlCommandFilename: ?PSTR,
PdlCounterList: ?PSTR,
PdlAutoNameFormat: u32,
PdlSampleInterval: u32,
PdlLogStartTime: FILETIME,
PdlLogEndTime: FILETIME,
},
Anonymous2: extern struct {
TlNumberOfBuffers: u32,
TlMinimumBuffers: u32,
TlMaximumBuffers: u32,
TlFreeBuffers: u32,
TlBufferSize: u32,
TlEventsLost: u32,
TlLoggerThreadId: u32,
TlBuffersWritten: u32,
TlLogHandle: u32,
TlLogFileName: ?PSTR,
},
},
};
pub const PDH_LOG_SERVICE_QUERY_INFO_W = extern struct {
dwSize: u32,
dwFlags: u32,
dwLogQuota: u32,
szLogFileCaption: ?PWSTR,
szDefaultDir: ?PWSTR,
szBaseFileName: ?PWSTR,
dwFileType: u32,
dwReserved: u32,
Anonymous: extern union {
Anonymous1: extern struct {
PdlAutoNameInterval: u32,
PdlAutoNameUnits: u32,
PdlCommandFilename: ?PWSTR,
PdlCounterList: ?PWSTR,
PdlAutoNameFormat: u32,
PdlSampleInterval: u32,
PdlLogStartTime: FILETIME,
PdlLogEndTime: FILETIME,
},
Anonymous2: extern struct {
TlNumberOfBuffers: u32,
TlMinimumBuffers: u32,
TlMaximumBuffers: u32,
TlFreeBuffers: u32,
TlBufferSize: u32,
TlEventsLost: u32,
TlLoggerThreadId: u32,
TlBuffersWritten: u32,
TlLogHandle: u32,
TlLogFileName: ?PWSTR,
},
},
};
pub const CounterPathCallBack = fn(
param0: usize,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const PDH_BROWSE_DLG_CONFIG_HW = extern struct {
_bitfield: u32,
hWndOwner: ?HWND,
hDataSource: isize,
szReturnPathBuffer: ?PWSTR,
cchReturnPathLength: u32,
pCallBack: ?CounterPathCallBack,
dwCallBackArg: usize,
CallBackStatus: i32,
dwDefaultDetailLevel: PERF_DETAIL,
szDialogBoxCaption: ?PWSTR,
};
pub const PDH_BROWSE_DLG_CONFIG_HA = extern struct {
_bitfield: u32,
hWndOwner: ?HWND,
hDataSource: isize,
szReturnPathBuffer: ?PSTR,
cchReturnPathLength: u32,
pCallBack: ?CounterPathCallBack,
dwCallBackArg: usize,
CallBackStatus: i32,
dwDefaultDetailLevel: PERF_DETAIL,
szDialogBoxCaption: ?PSTR,
};
pub const PDH_BROWSE_DLG_CONFIG_W = extern struct {
_bitfield: u32,
hWndOwner: ?HWND,
szDataSource: ?PWSTR,
szReturnPathBuffer: ?PWSTR,
cchReturnPathLength: u32,
pCallBack: ?CounterPathCallBack,
dwCallBackArg: usize,
CallBackStatus: i32,
dwDefaultDetailLevel: PERF_DETAIL,
szDialogBoxCaption: ?PWSTR,
};
pub const PDH_BROWSE_DLG_CONFIG_A = extern struct {
_bitfield: u32,
hWndOwner: ?HWND,
szDataSource: ?PSTR,
szReturnPathBuffer: ?PSTR,
cchReturnPathLength: u32,
pCallBack: ?CounterPathCallBack,
dwCallBackArg: usize,
CallBackStatus: i32,
dwDefaultDetailLevel: PERF_DETAIL,
szDialogBoxCaption: ?PSTR,
};
const CLSID_DataCollectorSet_Value = @import("../zig.zig").Guid.initString("03837521-098b-11d8-9414-505054503030");
pub const CLSID_DataCollectorSet = &CLSID_DataCollectorSet_Value;
const CLSID_TraceSession_Value = @import("../zig.zig").Guid.initString("0383751c-098b-11d8-9414-505054503030");
pub const CLSID_TraceSession = &CLSID_TraceSession_Value;
const CLSID_TraceSessionCollection_Value = @import("../zig.zig").Guid.initString("03837530-098b-11d8-9414-505054503030");
pub const CLSID_TraceSessionCollection = &CLSID_TraceSessionCollection_Value;
const CLSID_TraceDataProvider_Value = @import("../zig.zig").Guid.initString("03837513-098b-11d8-9414-505054503030");
pub const CLSID_TraceDataProvider = &CLSID_TraceDataProvider_Value;
const CLSID_TraceDataProviderCollection_Value = @import("../zig.zig").Guid.initString("03837511-098b-11d8-9414-505054503030");
pub const CLSID_TraceDataProviderCollection = &CLSID_TraceDataProviderCollection_Value;
const CLSID_DataCollectorSetCollection_Value = @import("../zig.zig").Guid.initString("03837525-098b-11d8-9414-505054503030");
pub const CLSID_DataCollectorSetCollection = &CLSID_DataCollectorSetCollection_Value;
const CLSID_LegacyDataCollectorSet_Value = @import("../zig.zig").Guid.initString("03837526-098b-11d8-9414-505054503030");
pub const CLSID_LegacyDataCollectorSet = &CLSID_LegacyDataCollectorSet_Value;
const CLSID_LegacyDataCollectorSetCollection_Value = @import("../zig.zig").Guid.initString("03837527-098b-11d8-9414-505054503030");
pub const CLSID_LegacyDataCollectorSetCollection = &CLSID_LegacyDataCollectorSetCollection_Value;
const CLSID_LegacyTraceSession_Value = @import("../zig.zig").Guid.initString("03837528-098b-11d8-9414-505054503030");
pub const CLSID_LegacyTraceSession = &CLSID_LegacyTraceSession_Value;
const CLSID_LegacyTraceSessionCollection_Value = @import("../zig.zig").Guid.initString("03837529-098b-11d8-9414-505054503030");
pub const CLSID_LegacyTraceSessionCollection = &CLSID_LegacyTraceSessionCollection_Value;
const CLSID_ServerDataCollectorSet_Value = @import("../zig.zig").Guid.initString("03837531-098b-11d8-9414-505054503030");
pub const CLSID_ServerDataCollectorSet = &CLSID_ServerDataCollectorSet_Value;
const CLSID_ServerDataCollectorSetCollection_Value = @import("../zig.zig").Guid.initString("03837532-098b-11d8-9414-505054503030");
pub const CLSID_ServerDataCollectorSetCollection = &CLSID_ServerDataCollectorSetCollection_Value;
const CLSID_SystemDataCollectorSet_Value = @import("../zig.zig").Guid.initString("03837546-098b-11d8-9414-505054503030");
pub const CLSID_SystemDataCollectorSet = &CLSID_SystemDataCollectorSet_Value;
const CLSID_SystemDataCollectorSetCollection_Value = @import("../zig.zig").Guid.initString("03837547-098b-11d8-9414-505054503030");
pub const CLSID_SystemDataCollectorSetCollection = &CLSID_SystemDataCollectorSetCollection_Value;
const CLSID_BootTraceSession_Value = @import("../zig.zig").Guid.initString("03837538-098b-11d8-9414-505054503030");
pub const CLSID_BootTraceSession = &CLSID_BootTraceSession_Value;
const CLSID_BootTraceSessionCollection_Value = @import("../zig.zig").Guid.initString("03837539-098b-11d8-9414-505054503030");
pub const CLSID_BootTraceSessionCollection = &CLSID_BootTraceSessionCollection_Value;
pub const DataCollectorType = enum(i32) {
PerformanceCounter = 0,
Trace = 1,
Configuration = 2,
Alert = 3,
ApiTrace = 4,
};
pub const plaPerformanceCounter = DataCollectorType.PerformanceCounter;
pub const plaTrace = DataCollectorType.Trace;
pub const plaConfiguration = DataCollectorType.Configuration;
pub const plaAlert = DataCollectorType.Alert;
pub const plaApiTrace = DataCollectorType.ApiTrace;
pub const FileFormat = enum(i32) {
CommaSeparated = 0,
TabSeparated = 1,
Sql = 2,
Binary = 3,
};
pub const plaCommaSeparated = FileFormat.CommaSeparated;
pub const plaTabSeparated = FileFormat.TabSeparated;
pub const plaSql = FileFormat.Sql;
pub const plaBinary = FileFormat.Binary;
pub const AutoPathFormat = enum(i32) {
None = 0,
Pattern = 1,
Computer = 2,
MonthDayHour = 256,
SerialNumber = 512,
YearDayOfYear = 1024,
YearMonth = 2048,
YearMonthDay = 4096,
YearMonthDayHour = 8192,
MonthDayHourMinute = 16384,
};
pub const plaNone = AutoPathFormat.None;
pub const plaPattern = AutoPathFormat.Pattern;
pub const plaComputer = AutoPathFormat.Computer;
pub const plaMonthDayHour = AutoPathFormat.MonthDayHour;
pub const plaSerialNumber = AutoPathFormat.SerialNumber;
pub const plaYearDayOfYear = AutoPathFormat.YearDayOfYear;
pub const plaYearMonth = AutoPathFormat.YearMonth;
pub const plaYearMonthDay = AutoPathFormat.YearMonthDay;
pub const plaYearMonthDayHour = AutoPathFormat.YearMonthDayHour;
pub const plaMonthDayHourMinute = AutoPathFormat.MonthDayHourMinute;
pub const DataCollectorSetStatus = enum(i32) {
Stopped = 0,
Running = 1,
Compiling = 2,
Pending = 3,
Undefined = 4,
};
pub const plaStopped = DataCollectorSetStatus.Stopped;
pub const plaRunning = DataCollectorSetStatus.Running;
pub const plaCompiling = DataCollectorSetStatus.Compiling;
pub const plaPending = DataCollectorSetStatus.Pending;
pub const plaUndefined = DataCollectorSetStatus.Undefined;
pub const ClockType = enum(i32) {
TimeStamp = 0,
Performance = 1,
System = 2,
Cycle = 3,
};
pub const plaTimeStamp = ClockType.TimeStamp;
pub const plaPerformance = ClockType.Performance;
pub const plaSystem = ClockType.System;
pub const plaCycle = ClockType.Cycle;
pub const StreamMode = enum(i32) {
File = 1,
RealTime = 2,
Both = 3,
Buffering = 4,
};
pub const plaFile = StreamMode.File;
pub const plaRealTime = StreamMode.RealTime;
pub const plaBoth = StreamMode.Both;
pub const plaBuffering = StreamMode.Buffering;
pub const CommitMode = enum(i32) {
CreateNew = 1,
Modify = 2,
CreateOrModify = 3,
UpdateRunningInstance = 16,
FlushTrace = 32,
ValidateOnly = 4096,
};
pub const plaCreateNew = CommitMode.CreateNew;
pub const plaModify = CommitMode.Modify;
pub const plaCreateOrModify = CommitMode.CreateOrModify;
pub const plaUpdateRunningInstance = CommitMode.UpdateRunningInstance;
pub const plaFlushTrace = CommitMode.FlushTrace;
pub const plaValidateOnly = CommitMode.ValidateOnly;
pub const ValueMapType = enum(i32) {
Index = 1,
Flag = 2,
FlagArray = 3,
Validation = 4,
};
pub const plaIndex = ValueMapType.Index;
pub const plaFlag = ValueMapType.Flag;
pub const plaFlagArray = ValueMapType.FlagArray;
pub const plaValidation = ValueMapType.Validation;
pub const WeekDays = enum(i32) {
RunOnce = 0,
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64,
Everyday = 127,
};
pub const plaRunOnce = WeekDays.RunOnce;
pub const plaSunday = WeekDays.Sunday;
pub const plaMonday = WeekDays.Monday;
pub const plaTuesday = WeekDays.Tuesday;
pub const plaWednesday = WeekDays.Wednesday;
pub const plaThursday = WeekDays.Thursday;
pub const plaFriday = WeekDays.Friday;
pub const plaSaturday = WeekDays.Saturday;
pub const plaEveryday = WeekDays.Everyday;
pub const ResourcePolicy = enum(i32) {
Largest = 0,
Oldest = 1,
};
pub const plaDeleteLargest = ResourcePolicy.Largest;
pub const plaDeleteOldest = ResourcePolicy.Oldest;
pub const DataManagerSteps = enum(i32) {
CreateReport = 1,
RunRules = 2,
CreateHtml = 4,
FolderActions = 8,
ResourceFreeing = 16,
};
pub const plaCreateReport = DataManagerSteps.CreateReport;
pub const plaRunRules = DataManagerSteps.RunRules;
pub const plaCreateHtml = DataManagerSteps.CreateHtml;
pub const plaFolderActions = DataManagerSteps.FolderActions;
pub const plaResourceFreeing = DataManagerSteps.ResourceFreeing;
pub const FolderActionSteps = enum(i32) {
CreateCab = 1,
DeleteData = 2,
SendCab = 4,
DeleteCab = 8,
DeleteReport = 16,
};
pub const plaCreateCab = FolderActionSteps.CreateCab;
pub const plaDeleteData = FolderActionSteps.DeleteData;
pub const plaSendCab = FolderActionSteps.SendCab;
pub const plaDeleteCab = FolderActionSteps.DeleteCab;
pub const plaDeleteReport = FolderActionSteps.DeleteReport;
pub const PLA_CABEXTRACT_CALLBACK = fn(
FileName: ?[*:0]const u16,
Context: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IDataCollectorSet_Value = @import("../zig.zig").Guid.initString("03837520-098b-11d8-9414-505054503030");
pub const IID_IDataCollectorSet = &IID_IDataCollectorSet_Value;
pub const IDataCollectorSet = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_DataCollectors: fn(
self: *const IDataCollectorSet,
collectors: ?*?*IDataCollectorCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Duration: fn(
self: *const IDataCollectorSet,
seconds: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Duration: fn(
self: *const IDataCollectorSet,
seconds: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Description: fn(
self: *const IDataCollectorSet,
description: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Description: fn(
self: *const IDataCollectorSet,
description: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_DescriptionUnresolved: fn(
self: *const IDataCollectorSet,
Descr: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_DisplayName: fn(
self: *const IDataCollectorSet,
DisplayName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_DisplayName: fn(
self: *const IDataCollectorSet,
DisplayName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_DisplayNameUnresolved: fn(
self: *const IDataCollectorSet,
name: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Keywords: fn(
self: *const IDataCollectorSet,
keywords: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Keywords: fn(
self: *const IDataCollectorSet,
keywords: ?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_LatestOutputLocation: fn(
self: *const IDataCollectorSet,
path: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_LatestOutputLocation: fn(
self: *const IDataCollectorSet,
path: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Name: fn(
self: *const IDataCollectorSet,
name: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_OutputLocation: fn(
self: *const IDataCollectorSet,
path: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_RootPath: fn(
self: *const IDataCollectorSet,
folder: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_RootPath: fn(
self: *const IDataCollectorSet,
folder: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Segment: fn(
self: *const IDataCollectorSet,
segment: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Segment: fn(
self: *const IDataCollectorSet,
segment: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SegmentMaxDuration: fn(
self: *const IDataCollectorSet,
seconds: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_SegmentMaxDuration: fn(
self: *const IDataCollectorSet,
seconds: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SegmentMaxSize: fn(
self: *const IDataCollectorSet,
size: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_SegmentMaxSize: fn(
self: *const IDataCollectorSet,
size: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SerialNumber: fn(
self: *const IDataCollectorSet,
index: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_SerialNumber: fn(
self: *const IDataCollectorSet,
index: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Server: fn(
self: *const IDataCollectorSet,
server: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Status: fn(
self: *const IDataCollectorSet,
status: ?*DataCollectorSetStatus,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Subdirectory: fn(
self: *const IDataCollectorSet,
folder: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Subdirectory: fn(
self: *const IDataCollectorSet,
folder: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SubdirectoryFormat: fn(
self: *const IDataCollectorSet,
format: ?*AutoPathFormat,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_SubdirectoryFormat: fn(
self: *const IDataCollectorSet,
format: AutoPathFormat,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SubdirectoryFormatPattern: fn(
self: *const IDataCollectorSet,
pattern: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_SubdirectoryFormatPattern: fn(
self: *const IDataCollectorSet,
pattern: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Task: fn(
self: *const IDataCollectorSet,
task: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Task: fn(
self: *const IDataCollectorSet,
task: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_TaskRunAsSelf: fn(
self: *const IDataCollectorSet,
RunAsSelf: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_TaskRunAsSelf: fn(
self: *const IDataCollectorSet,
RunAsSelf: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_TaskArguments: fn(
self: *const IDataCollectorSet,
task: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_TaskArguments: fn(
self: *const IDataCollectorSet,
task: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_TaskUserTextArguments: fn(
self: *const IDataCollectorSet,
UserText: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_TaskUserTextArguments: fn(
self: *const IDataCollectorSet,
UserText: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Schedules: fn(
self: *const IDataCollectorSet,
ppSchedules: ?*?*IScheduleCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SchedulesEnabled: fn(
self: *const IDataCollectorSet,
enabled: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_SchedulesEnabled: fn(
self: *const IDataCollectorSet,
enabled: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_UserAccount: fn(
self: *const IDataCollectorSet,
user: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Xml: fn(
self: *const IDataCollectorSet,
xml: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Security: fn(
self: *const IDataCollectorSet,
pbstrSecurity: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Security: fn(
self: *const IDataCollectorSet,
bstrSecurity: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StopOnCompletion: fn(
self: *const IDataCollectorSet,
Stop: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_StopOnCompletion: fn(
self: *const IDataCollectorSet,
Stop: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_DataManager: fn(
self: *const IDataCollectorSet,
DataManager: ?*?*IDataManager,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCredentials: fn(
self: *const IDataCollectorSet,
user: ?BSTR,
password: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Query: fn(
self: *const IDataCollectorSet,
name: ?BSTR,
server: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Commit: fn(
self: *const IDataCollectorSet,
name: ?BSTR,
server: ?BSTR,
mode: CommitMode,
validation: ?*?*IValueMap,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Delete: fn(
self: *const IDataCollectorSet,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Start: fn(
self: *const IDataCollectorSet,
Synchronous: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Stop: fn(
self: *const IDataCollectorSet,
Synchronous: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetXml: fn(
self: *const IDataCollectorSet,
xml: ?BSTR,
validation: ?*?*IValueMap,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetValue: fn(
self: *const IDataCollectorSet,
key: ?BSTR,
value: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetValue: fn(
self: *const IDataCollectorSet,
key: ?BSTR,
value: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_DataCollectors(self: *const T, collectors: ?*?*IDataCollectorCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_DataCollectors(@ptrCast(*const IDataCollectorSet, self), collectors);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_Duration(self: *const T, seconds: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_Duration(@ptrCast(*const IDataCollectorSet, self), seconds);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_put_Duration(self: *const T, seconds: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_Duration(@ptrCast(*const IDataCollectorSet, self), seconds);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_Description(self: *const T, description: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_Description(@ptrCast(*const IDataCollectorSet, self), description);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_put_Description(self: *const T, description: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_Description(@ptrCast(*const IDataCollectorSet, self), description);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_DescriptionUnresolved(self: *const T, Descr: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_DescriptionUnresolved(@ptrCast(*const IDataCollectorSet, self), Descr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_DisplayName(self: *const T, DisplayName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_DisplayName(@ptrCast(*const IDataCollectorSet, self), DisplayName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_put_DisplayName(self: *const T, DisplayName: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_DisplayName(@ptrCast(*const IDataCollectorSet, self), DisplayName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_DisplayNameUnresolved(self: *const T, name: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_DisplayNameUnresolved(@ptrCast(*const IDataCollectorSet, self), name);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_Keywords(self: *const T, keywords: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_Keywords(@ptrCast(*const IDataCollectorSet, self), keywords);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_put_Keywords(self: *const T, keywords: ?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_Keywords(@ptrCast(*const IDataCollectorSet, self), keywords);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_LatestOutputLocation(self: *const T, path: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_LatestOutputLocation(@ptrCast(*const IDataCollectorSet, self), path);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_put_LatestOutputLocation(self: *const T, path: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_LatestOutputLocation(@ptrCast(*const IDataCollectorSet, self), path);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_Name(self: *const T, name: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_Name(@ptrCast(*const IDataCollectorSet, self), name);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_OutputLocation(self: *const T, path: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_OutputLocation(@ptrCast(*const IDataCollectorSet, self), path);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_RootPath(self: *const T, folder: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_RootPath(@ptrCast(*const IDataCollectorSet, self), folder);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_put_RootPath(self: *const T, folder: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_RootPath(@ptrCast(*const IDataCollectorSet, self), folder);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_Segment(self: *const T, segment: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_Segment(@ptrCast(*const IDataCollectorSet, self), segment);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_put_Segment(self: *const T, segment: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_Segment(@ptrCast(*const IDataCollectorSet, self), segment);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_SegmentMaxDuration(self: *const T, seconds: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_SegmentMaxDuration(@ptrCast(*const IDataCollectorSet, self), seconds);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_put_SegmentMaxDuration(self: *const T, seconds: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_SegmentMaxDuration(@ptrCast(*const IDataCollectorSet, self), seconds);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_SegmentMaxSize(self: *const T, size: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_SegmentMaxSize(@ptrCast(*const IDataCollectorSet, self), size);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_put_SegmentMaxSize(self: *const T, size: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_SegmentMaxSize(@ptrCast(*const IDataCollectorSet, self), size);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_SerialNumber(self: *const T, index: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_SerialNumber(@ptrCast(*const IDataCollectorSet, self), index);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_put_SerialNumber(self: *const T, index: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_SerialNumber(@ptrCast(*const IDataCollectorSet, self), index);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_Server(self: *const T, server: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_Server(@ptrCast(*const IDataCollectorSet, self), server);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_Status(self: *const T, status: ?*DataCollectorSetStatus) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_Status(@ptrCast(*const IDataCollectorSet, self), status);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_Subdirectory(self: *const T, folder: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_Subdirectory(@ptrCast(*const IDataCollectorSet, self), folder);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_put_Subdirectory(self: *const T, folder: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_Subdirectory(@ptrCast(*const IDataCollectorSet, self), folder);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_SubdirectoryFormat(self: *const T, format: ?*AutoPathFormat) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_SubdirectoryFormat(@ptrCast(*const IDataCollectorSet, self), format);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_put_SubdirectoryFormat(self: *const T, format: AutoPathFormat) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_SubdirectoryFormat(@ptrCast(*const IDataCollectorSet, self), format);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_SubdirectoryFormatPattern(self: *const T, pattern: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_SubdirectoryFormatPattern(@ptrCast(*const IDataCollectorSet, self), pattern);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_put_SubdirectoryFormatPattern(self: *const T, pattern: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_SubdirectoryFormatPattern(@ptrCast(*const IDataCollectorSet, self), pattern);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_Task(self: *const T, task: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_Task(@ptrCast(*const IDataCollectorSet, self), task);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_put_Task(self: *const T, task: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_Task(@ptrCast(*const IDataCollectorSet, self), task);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_TaskRunAsSelf(self: *const T, RunAsSelf: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_TaskRunAsSelf(@ptrCast(*const IDataCollectorSet, self), RunAsSelf);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_put_TaskRunAsSelf(self: *const T, RunAsSelf: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_TaskRunAsSelf(@ptrCast(*const IDataCollectorSet, self), RunAsSelf);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_TaskArguments(self: *const T, task: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_TaskArguments(@ptrCast(*const IDataCollectorSet, self), task);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_put_TaskArguments(self: *const T, task: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_TaskArguments(@ptrCast(*const IDataCollectorSet, self), task);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_TaskUserTextArguments(self: *const T, UserText: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_TaskUserTextArguments(@ptrCast(*const IDataCollectorSet, self), UserText);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_put_TaskUserTextArguments(self: *const T, UserText: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_TaskUserTextArguments(@ptrCast(*const IDataCollectorSet, self), UserText);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_Schedules(self: *const T, ppSchedules: ?*?*IScheduleCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_Schedules(@ptrCast(*const IDataCollectorSet, self), ppSchedules);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_SchedulesEnabled(self: *const T, enabled: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_SchedulesEnabled(@ptrCast(*const IDataCollectorSet, self), enabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_put_SchedulesEnabled(self: *const T, enabled: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_SchedulesEnabled(@ptrCast(*const IDataCollectorSet, self), enabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_UserAccount(self: *const T, user: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_UserAccount(@ptrCast(*const IDataCollectorSet, self), user);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_Xml(self: *const T, xml: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_Xml(@ptrCast(*const IDataCollectorSet, self), xml);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_Security(self: *const T, pbstrSecurity: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_Security(@ptrCast(*const IDataCollectorSet, self), pbstrSecurity);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_put_Security(self: *const T, bstrSecurity: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_Security(@ptrCast(*const IDataCollectorSet, self), bstrSecurity);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_StopOnCompletion(self: *const T, Stop: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_StopOnCompletion(@ptrCast(*const IDataCollectorSet, self), Stop);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_put_StopOnCompletion(self: *const T, Stop: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).put_StopOnCompletion(@ptrCast(*const IDataCollectorSet, self), Stop);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_get_DataManager(self: *const T, DataManager: ?*?*IDataManager) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).get_DataManager(@ptrCast(*const IDataCollectorSet, self), DataManager);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_SetCredentials(self: *const T, user: ?BSTR, password: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).SetCredentials(@ptrCast(*const IDataCollectorSet, self), user, password);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_Query(self: *const T, name: ?BSTR, server: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).Query(@ptrCast(*const IDataCollectorSet, self), name, server);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_Commit(self: *const T, name: ?BSTR, server: ?BSTR, mode: CommitMode, validation: ?*?*IValueMap) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).Commit(@ptrCast(*const IDataCollectorSet, self), name, server, mode, validation);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_Delete(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).Delete(@ptrCast(*const IDataCollectorSet, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_Start(self: *const T, Synchronous: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).Start(@ptrCast(*const IDataCollectorSet, self), Synchronous);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_Stop(self: *const T, Synchronous: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).Stop(@ptrCast(*const IDataCollectorSet, self), Synchronous);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_SetXml(self: *const T, xml: ?BSTR, validation: ?*?*IValueMap) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).SetXml(@ptrCast(*const IDataCollectorSet, self), xml, validation);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_SetValue(self: *const T, key: ?BSTR, value: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).SetValue(@ptrCast(*const IDataCollectorSet, self), key, value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSet_GetValue(self: *const T, key: ?BSTR, value: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSet.VTable, self.vtable).GetValue(@ptrCast(*const IDataCollectorSet, self), key, value);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IDataManager_Value = @import("../zig.zig").Guid.initString("03837541-098b-11d8-9414-505054503030");
pub const IID_IDataManager = &IID_IDataManager_Value;
pub const IDataManager = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Enabled: fn(
self: *const IDataManager,
pfEnabled: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Enabled: fn(
self: *const IDataManager,
fEnabled: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_CheckBeforeRunning: fn(
self: *const IDataManager,
pfCheck: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_CheckBeforeRunning: fn(
self: *const IDataManager,
fCheck: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_MinFreeDisk: fn(
self: *const IDataManager,
MinFreeDisk: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_MinFreeDisk: fn(
self: *const IDataManager,
MinFreeDisk: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_MaxSize: fn(
self: *const IDataManager,
pulMaxSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_MaxSize: fn(
self: *const IDataManager,
ulMaxSize: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_MaxFolderCount: fn(
self: *const IDataManager,
pulMaxFolderCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_MaxFolderCount: fn(
self: *const IDataManager,
ulMaxFolderCount: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ResourcePolicy: fn(
self: *const IDataManager,
pPolicy: ?*ResourcePolicy,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_ResourcePolicy: fn(
self: *const IDataManager,
Policy: ResourcePolicy,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_FolderActions: fn(
self: *const IDataManager,
Actions: ?*?*IFolderActionCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ReportSchema: fn(
self: *const IDataManager,
ReportSchema: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_ReportSchema: fn(
self: *const IDataManager,
ReportSchema: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ReportFileName: fn(
self: *const IDataManager,
pbstrFilename: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_ReportFileName: fn(
self: *const IDataManager,
pbstrFilename: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_RuleTargetFileName: fn(
self: *const IDataManager,
Filename: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_RuleTargetFileName: fn(
self: *const IDataManager,
Filename: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_EventsFileName: fn(
self: *const IDataManager,
pbstrFilename: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_EventsFileName: fn(
self: *const IDataManager,
pbstrFilename: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Rules: fn(
self: *const IDataManager,
pbstrXml: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Rules: fn(
self: *const IDataManager,
bstrXml: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Run: fn(
self: *const IDataManager,
Steps: DataManagerSteps,
bstrFolder: ?BSTR,
Errors: ?*?*IValueMap,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Extract: fn(
self: *const IDataManager,
CabFilename: ?BSTR,
DestinationPath: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataManager_get_Enabled(self: *const T, pfEnabled: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataManager.VTable, self.vtable).get_Enabled(@ptrCast(*const IDataManager, self), pfEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataManager_put_Enabled(self: *const T, fEnabled: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataManager.VTable, self.vtable).put_Enabled(@ptrCast(*const IDataManager, self), fEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataManager_get_CheckBeforeRunning(self: *const T, pfCheck: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataManager.VTable, self.vtable).get_CheckBeforeRunning(@ptrCast(*const IDataManager, self), pfCheck);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataManager_put_CheckBeforeRunning(self: *const T, fCheck: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataManager.VTable, self.vtable).put_CheckBeforeRunning(@ptrCast(*const IDataManager, self), fCheck);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataManager_get_MinFreeDisk(self: *const T, MinFreeDisk: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataManager.VTable, self.vtable).get_MinFreeDisk(@ptrCast(*const IDataManager, self), MinFreeDisk);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataManager_put_MinFreeDisk(self: *const T, MinFreeDisk: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataManager.VTable, self.vtable).put_MinFreeDisk(@ptrCast(*const IDataManager, self), MinFreeDisk);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataManager_get_MaxSize(self: *const T, pulMaxSize: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataManager.VTable, self.vtable).get_MaxSize(@ptrCast(*const IDataManager, self), pulMaxSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataManager_put_MaxSize(self: *const T, ulMaxSize: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataManager.VTable, self.vtable).put_MaxSize(@ptrCast(*const IDataManager, self), ulMaxSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataManager_get_MaxFolderCount(self: *const T, pulMaxFolderCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataManager.VTable, self.vtable).get_MaxFolderCount(@ptrCast(*const IDataManager, self), pulMaxFolderCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataManager_put_MaxFolderCount(self: *const T, ulMaxFolderCount: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataManager.VTable, self.vtable).put_MaxFolderCount(@ptrCast(*const IDataManager, self), ulMaxFolderCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataManager_get_ResourcePolicy(self: *const T, pPolicy: ?*ResourcePolicy) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataManager.VTable, self.vtable).get_ResourcePolicy(@ptrCast(*const IDataManager, self), pPolicy);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataManager_put_ResourcePolicy(self: *const T, Policy: ResourcePolicy) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataManager.VTable, self.vtable).put_ResourcePolicy(@ptrCast(*const IDataManager, self), Policy);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataManager_get_FolderActions(self: *const T, Actions: ?*?*IFolderActionCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataManager.VTable, self.vtable).get_FolderActions(@ptrCast(*const IDataManager, self), Actions);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataManager_get_ReportSchema(self: *const T, ReportSchema: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataManager.VTable, self.vtable).get_ReportSchema(@ptrCast(*const IDataManager, self), ReportSchema);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataManager_put_ReportSchema(self: *const T, ReportSchema: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataManager.VTable, self.vtable).put_ReportSchema(@ptrCast(*const IDataManager, self), ReportSchema);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataManager_get_ReportFileName(self: *const T, pbstrFilename: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataManager.VTable, self.vtable).get_ReportFileName(@ptrCast(*const IDataManager, self), pbstrFilename);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataManager_put_ReportFileName(self: *const T, pbstrFilename: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataManager.VTable, self.vtable).put_ReportFileName(@ptrCast(*const IDataManager, self), pbstrFilename);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataManager_get_RuleTargetFileName(self: *const T, Filename: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataManager.VTable, self.vtable).get_RuleTargetFileName(@ptrCast(*const IDataManager, self), Filename);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataManager_put_RuleTargetFileName(self: *const T, Filename: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataManager.VTable, self.vtable).put_RuleTargetFileName(@ptrCast(*const IDataManager, self), Filename);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataManager_get_EventsFileName(self: *const T, pbstrFilename: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataManager.VTable, self.vtable).get_EventsFileName(@ptrCast(*const IDataManager, self), pbstrFilename);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataManager_put_EventsFileName(self: *const T, pbstrFilename: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataManager.VTable, self.vtable).put_EventsFileName(@ptrCast(*const IDataManager, self), pbstrFilename);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataManager_get_Rules(self: *const T, pbstrXml: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataManager.VTable, self.vtable).get_Rules(@ptrCast(*const IDataManager, self), pbstrXml);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataManager_put_Rules(self: *const T, bstrXml: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataManager.VTable, self.vtable).put_Rules(@ptrCast(*const IDataManager, self), bstrXml);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataManager_Run(self: *const T, Steps: DataManagerSteps, bstrFolder: ?BSTR, Errors: ?*?*IValueMap) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataManager.VTable, self.vtable).Run(@ptrCast(*const IDataManager, self), Steps, bstrFolder, Errors);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataManager_Extract(self: *const T, CabFilename: ?BSTR, DestinationPath: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataManager.VTable, self.vtable).Extract(@ptrCast(*const IDataManager, self), CabFilename, DestinationPath);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IFolderAction_Value = @import("../zig.zig").Guid.initString("03837543-098b-11d8-9414-505054503030");
pub const IID_IFolderAction = &IID_IFolderAction_Value;
pub const IFolderAction = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Age: fn(
self: *const IFolderAction,
pulAge: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Age: fn(
self: *const IFolderAction,
ulAge: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Size: fn(
self: *const IFolderAction,
pulAge: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Size: fn(
self: *const IFolderAction,
ulAge: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Actions: fn(
self: *const IFolderAction,
Steps: ?*FolderActionSteps,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Actions: fn(
self: *const IFolderAction,
Steps: FolderActionSteps,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SendCabTo: fn(
self: *const IFolderAction,
pbstrDestination: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_SendCabTo: fn(
self: *const IFolderAction,
bstrDestination: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFolderAction_get_Age(self: *const T, pulAge: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IFolderAction.VTable, self.vtable).get_Age(@ptrCast(*const IFolderAction, self), pulAge);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFolderAction_put_Age(self: *const T, ulAge: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IFolderAction.VTable, self.vtable).put_Age(@ptrCast(*const IFolderAction, self), ulAge);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFolderAction_get_Size(self: *const T, pulAge: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IFolderAction.VTable, self.vtable).get_Size(@ptrCast(*const IFolderAction, self), pulAge);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFolderAction_put_Size(self: *const T, ulAge: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IFolderAction.VTable, self.vtable).put_Size(@ptrCast(*const IFolderAction, self), ulAge);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFolderAction_get_Actions(self: *const T, Steps: ?*FolderActionSteps) callconv(.Inline) HRESULT {
return @ptrCast(*const IFolderAction.VTable, self.vtable).get_Actions(@ptrCast(*const IFolderAction, self), Steps);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFolderAction_put_Actions(self: *const T, Steps: FolderActionSteps) callconv(.Inline) HRESULT {
return @ptrCast(*const IFolderAction.VTable, self.vtable).put_Actions(@ptrCast(*const IFolderAction, self), Steps);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFolderAction_get_SendCabTo(self: *const T, pbstrDestination: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFolderAction.VTable, self.vtable).get_SendCabTo(@ptrCast(*const IFolderAction, self), pbstrDestination);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFolderAction_put_SendCabTo(self: *const T, bstrDestination: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFolderAction.VTable, self.vtable).put_SendCabTo(@ptrCast(*const IFolderAction, self), bstrDestination);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IFolderActionCollection_Value = @import("../zig.zig").Guid.initString("03837544-098b-11d8-9414-505054503030");
pub const IID_IFolderActionCollection = &IID_IFolderActionCollection_Value;
pub const IFolderActionCollection = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Count: fn(
self: *const IFolderActionCollection,
Count: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Item: fn(
self: *const IFolderActionCollection,
Index: VARIANT,
Action: ?*?*IFolderAction,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get__NewEnum: fn(
self: *const IFolderActionCollection,
Enum: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Add: fn(
self: *const IFolderActionCollection,
Action: ?*IFolderAction,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Remove: fn(
self: *const IFolderActionCollection,
Index: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clear: fn(
self: *const IFolderActionCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddRange: fn(
self: *const IFolderActionCollection,
Actions: ?*IFolderActionCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateFolderAction: fn(
self: *const IFolderActionCollection,
FolderAction: ?*?*IFolderAction,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFolderActionCollection_get_Count(self: *const T, Count: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IFolderActionCollection.VTable, self.vtable).get_Count(@ptrCast(*const IFolderActionCollection, self), Count);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFolderActionCollection_get_Item(self: *const T, Index: VARIANT, Action: ?*?*IFolderAction) callconv(.Inline) HRESULT {
return @ptrCast(*const IFolderActionCollection.VTable, self.vtable).get_Item(@ptrCast(*const IFolderActionCollection, self), Index, Action);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFolderActionCollection_get__NewEnum(self: *const T, Enum: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IFolderActionCollection.VTable, self.vtable).get__NewEnum(@ptrCast(*const IFolderActionCollection, self), Enum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFolderActionCollection_Add(self: *const T, Action: ?*IFolderAction) callconv(.Inline) HRESULT {
return @ptrCast(*const IFolderActionCollection.VTable, self.vtable).Add(@ptrCast(*const IFolderActionCollection, self), Action);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFolderActionCollection_Remove(self: *const T, Index: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IFolderActionCollection.VTable, self.vtable).Remove(@ptrCast(*const IFolderActionCollection, self), Index);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFolderActionCollection_Clear(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IFolderActionCollection.VTable, self.vtable).Clear(@ptrCast(*const IFolderActionCollection, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFolderActionCollection_AddRange(self: *const T, Actions: ?*IFolderActionCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IFolderActionCollection.VTable, self.vtable).AddRange(@ptrCast(*const IFolderActionCollection, self), Actions);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFolderActionCollection_CreateFolderAction(self: *const T, FolderAction: ?*?*IFolderAction) callconv(.Inline) HRESULT {
return @ptrCast(*const IFolderActionCollection.VTable, self.vtable).CreateFolderAction(@ptrCast(*const IFolderActionCollection, self), FolderAction);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IDataCollector_Value = @import("../zig.zig").Guid.initString("038374ff-098b-11d8-9414-505054503030");
pub const IID_IDataCollector = &IID_IDataCollector_Value;
pub const IDataCollector = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_DataCollectorSet: fn(
self: *const IDataCollector,
group: ?*?*IDataCollectorSet,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_DataCollectorSet: fn(
self: *const IDataCollector,
group: ?*IDataCollectorSet,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_DataCollectorType: fn(
self: *const IDataCollector,
type: ?*DataCollectorType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_FileName: fn(
self: *const IDataCollector,
name: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_FileName: fn(
self: *const IDataCollector,
name: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_FileNameFormat: fn(
self: *const IDataCollector,
format: ?*AutoPathFormat,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_FileNameFormat: fn(
self: *const IDataCollector,
format: AutoPathFormat,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_FileNameFormatPattern: fn(
self: *const IDataCollector,
pattern: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_FileNameFormatPattern: fn(
self: *const IDataCollector,
pattern: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_LatestOutputLocation: fn(
self: *const IDataCollector,
path: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_LatestOutputLocation: fn(
self: *const IDataCollector,
path: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_LogAppend: fn(
self: *const IDataCollector,
append: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_LogAppend: fn(
self: *const IDataCollector,
append: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_LogCircular: fn(
self: *const IDataCollector,
circular: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_LogCircular: fn(
self: *const IDataCollector,
circular: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_LogOverwrite: fn(
self: *const IDataCollector,
overwrite: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_LogOverwrite: fn(
self: *const IDataCollector,
overwrite: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Name: fn(
self: *const IDataCollector,
name: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Name: fn(
self: *const IDataCollector,
name: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_OutputLocation: fn(
self: *const IDataCollector,
path: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Index: fn(
self: *const IDataCollector,
index: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Index: fn(
self: *const IDataCollector,
index: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Xml: fn(
self: *const IDataCollector,
Xml: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetXml: fn(
self: *const IDataCollector,
Xml: ?BSTR,
Validation: ?*?*IValueMap,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateOutputLocation: fn(
self: *const IDataCollector,
Latest: i16,
Location: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollector_get_DataCollectorSet(self: *const T, group: ?*?*IDataCollectorSet) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollector.VTable, self.vtable).get_DataCollectorSet(@ptrCast(*const IDataCollector, self), group);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollector_put_DataCollectorSet(self: *const T, group: ?*IDataCollectorSet) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollector.VTable, self.vtable).put_DataCollectorSet(@ptrCast(*const IDataCollector, self), group);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollector_get_DataCollectorType(self: *const T, type_: ?*DataCollectorType) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollector.VTable, self.vtable).get_DataCollectorType(@ptrCast(*const IDataCollector, self), type_);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollector_get_FileName(self: *const T, name: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollector.VTable, self.vtable).get_FileName(@ptrCast(*const IDataCollector, self), name);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollector_put_FileName(self: *const T, name: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollector.VTable, self.vtable).put_FileName(@ptrCast(*const IDataCollector, self), name);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollector_get_FileNameFormat(self: *const T, format: ?*AutoPathFormat) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollector.VTable, self.vtable).get_FileNameFormat(@ptrCast(*const IDataCollector, self), format);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollector_put_FileNameFormat(self: *const T, format: AutoPathFormat) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollector.VTable, self.vtable).put_FileNameFormat(@ptrCast(*const IDataCollector, self), format);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollector_get_FileNameFormatPattern(self: *const T, pattern: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollector.VTable, self.vtable).get_FileNameFormatPattern(@ptrCast(*const IDataCollector, self), pattern);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollector_put_FileNameFormatPattern(self: *const T, pattern: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollector.VTable, self.vtable).put_FileNameFormatPattern(@ptrCast(*const IDataCollector, self), pattern);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollector_get_LatestOutputLocation(self: *const T, path: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollector.VTable, self.vtable).get_LatestOutputLocation(@ptrCast(*const IDataCollector, self), path);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollector_put_LatestOutputLocation(self: *const T, path: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollector.VTable, self.vtable).put_LatestOutputLocation(@ptrCast(*const IDataCollector, self), path);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollector_get_LogAppend(self: *const T, append: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollector.VTable, self.vtable).get_LogAppend(@ptrCast(*const IDataCollector, self), append);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollector_put_LogAppend(self: *const T, append: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollector.VTable, self.vtable).put_LogAppend(@ptrCast(*const IDataCollector, self), append);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollector_get_LogCircular(self: *const T, circular: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollector.VTable, self.vtable).get_LogCircular(@ptrCast(*const IDataCollector, self), circular);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollector_put_LogCircular(self: *const T, circular: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollector.VTable, self.vtable).put_LogCircular(@ptrCast(*const IDataCollector, self), circular);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollector_get_LogOverwrite(self: *const T, overwrite: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollector.VTable, self.vtable).get_LogOverwrite(@ptrCast(*const IDataCollector, self), overwrite);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollector_put_LogOverwrite(self: *const T, overwrite: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollector.VTable, self.vtable).put_LogOverwrite(@ptrCast(*const IDataCollector, self), overwrite);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollector_get_Name(self: *const T, name: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollector.VTable, self.vtable).get_Name(@ptrCast(*const IDataCollector, self), name);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollector_put_Name(self: *const T, name: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollector.VTable, self.vtable).put_Name(@ptrCast(*const IDataCollector, self), name);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollector_get_OutputLocation(self: *const T, path: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollector.VTable, self.vtable).get_OutputLocation(@ptrCast(*const IDataCollector, self), path);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollector_get_Index(self: *const T, index: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollector.VTable, self.vtable).get_Index(@ptrCast(*const IDataCollector, self), index);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollector_put_Index(self: *const T, index: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollector.VTable, self.vtable).put_Index(@ptrCast(*const IDataCollector, self), index);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollector_get_Xml(self: *const T, Xml: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollector.VTable, self.vtable).get_Xml(@ptrCast(*const IDataCollector, self), Xml);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollector_SetXml(self: *const T, Xml: ?BSTR, Validation: ?*?*IValueMap) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollector.VTable, self.vtable).SetXml(@ptrCast(*const IDataCollector, self), Xml, Validation);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollector_CreateOutputLocation(self: *const T, Latest: i16, Location: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollector.VTable, self.vtable).CreateOutputLocation(@ptrCast(*const IDataCollector, self), Latest, Location);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IPerformanceCounterDataCollector_Value = @import("../zig.zig").Guid.initString("03837506-098b-11d8-9414-505054503030");
pub const IID_IPerformanceCounterDataCollector = &IID_IPerformanceCounterDataCollector_Value;
pub const IPerformanceCounterDataCollector = extern struct {
pub const VTable = extern struct {
base: IDataCollector.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_DataSourceName: fn(
self: *const IPerformanceCounterDataCollector,
dsn: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_DataSourceName: fn(
self: *const IPerformanceCounterDataCollector,
dsn: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_PerformanceCounters: fn(
self: *const IPerformanceCounterDataCollector,
counters: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_PerformanceCounters: fn(
self: *const IPerformanceCounterDataCollector,
counters: ?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_LogFileFormat: fn(
self: *const IPerformanceCounterDataCollector,
format: ?*FileFormat,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_LogFileFormat: fn(
self: *const IPerformanceCounterDataCollector,
format: FileFormat,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SampleInterval: fn(
self: *const IPerformanceCounterDataCollector,
interval: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_SampleInterval: fn(
self: *const IPerformanceCounterDataCollector,
interval: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SegmentMaxRecords: fn(
self: *const IPerformanceCounterDataCollector,
records: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_SegmentMaxRecords: fn(
self: *const IPerformanceCounterDataCollector,
records: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDataCollector.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPerformanceCounterDataCollector_get_DataSourceName(self: *const T, dsn: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IPerformanceCounterDataCollector.VTable, self.vtable).get_DataSourceName(@ptrCast(*const IPerformanceCounterDataCollector, self), dsn);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPerformanceCounterDataCollector_put_DataSourceName(self: *const T, dsn: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IPerformanceCounterDataCollector.VTable, self.vtable).put_DataSourceName(@ptrCast(*const IPerformanceCounterDataCollector, self), dsn);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPerformanceCounterDataCollector_get_PerformanceCounters(self: *const T, counters: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IPerformanceCounterDataCollector.VTable, self.vtable).get_PerformanceCounters(@ptrCast(*const IPerformanceCounterDataCollector, self), counters);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPerformanceCounterDataCollector_put_PerformanceCounters(self: *const T, counters: ?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IPerformanceCounterDataCollector.VTable, self.vtable).put_PerformanceCounters(@ptrCast(*const IPerformanceCounterDataCollector, self), counters);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPerformanceCounterDataCollector_get_LogFileFormat(self: *const T, format: ?*FileFormat) callconv(.Inline) HRESULT {
return @ptrCast(*const IPerformanceCounterDataCollector.VTable, self.vtable).get_LogFileFormat(@ptrCast(*const IPerformanceCounterDataCollector, self), format);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPerformanceCounterDataCollector_put_LogFileFormat(self: *const T, format: FileFormat) callconv(.Inline) HRESULT {
return @ptrCast(*const IPerformanceCounterDataCollector.VTable, self.vtable).put_LogFileFormat(@ptrCast(*const IPerformanceCounterDataCollector, self), format);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPerformanceCounterDataCollector_get_SampleInterval(self: *const T, interval: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IPerformanceCounterDataCollector.VTable, self.vtable).get_SampleInterval(@ptrCast(*const IPerformanceCounterDataCollector, self), interval);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPerformanceCounterDataCollector_put_SampleInterval(self: *const T, interval: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IPerformanceCounterDataCollector.VTable, self.vtable).put_SampleInterval(@ptrCast(*const IPerformanceCounterDataCollector, self), interval);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPerformanceCounterDataCollector_get_SegmentMaxRecords(self: *const T, records: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IPerformanceCounterDataCollector.VTable, self.vtable).get_SegmentMaxRecords(@ptrCast(*const IPerformanceCounterDataCollector, self), records);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IPerformanceCounterDataCollector_put_SegmentMaxRecords(self: *const T, records: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IPerformanceCounterDataCollector.VTable, self.vtable).put_SegmentMaxRecords(@ptrCast(*const IPerformanceCounterDataCollector, self), records);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_ITraceDataCollector_Value = @import("../zig.zig").Guid.initString("0383750b-098b-11d8-9414-505054503030");
pub const IID_ITraceDataCollector = &IID_ITraceDataCollector_Value;
pub const ITraceDataCollector = extern struct {
pub const VTable = extern struct {
base: IDataCollector.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_BufferSize: fn(
self: *const ITraceDataCollector,
size: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_BufferSize: fn(
self: *const ITraceDataCollector,
size: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_BuffersLost: fn(
self: *const ITraceDataCollector,
buffers: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_BuffersLost: fn(
self: *const ITraceDataCollector,
buffers: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_BuffersWritten: fn(
self: *const ITraceDataCollector,
buffers: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_BuffersWritten: fn(
self: *const ITraceDataCollector,
buffers: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ClockType: fn(
self: *const ITraceDataCollector,
clock: ?*ClockType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_ClockType: fn(
self: *const ITraceDataCollector,
clock: ClockType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_EventsLost: fn(
self: *const ITraceDataCollector,
events: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_EventsLost: fn(
self: *const ITraceDataCollector,
events: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ExtendedModes: fn(
self: *const ITraceDataCollector,
mode: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_ExtendedModes: fn(
self: *const ITraceDataCollector,
mode: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_FlushTimer: fn(
self: *const ITraceDataCollector,
seconds: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_FlushTimer: fn(
self: *const ITraceDataCollector,
seconds: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_FreeBuffers: fn(
self: *const ITraceDataCollector,
buffers: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_FreeBuffers: fn(
self: *const ITraceDataCollector,
buffers: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Guid: fn(
self: *const ITraceDataCollector,
guid: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Guid: fn(
self: *const ITraceDataCollector,
guid: Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_IsKernelTrace: fn(
self: *const ITraceDataCollector,
kernel: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_MaximumBuffers: fn(
self: *const ITraceDataCollector,
buffers: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_MaximumBuffers: fn(
self: *const ITraceDataCollector,
buffers: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_MinimumBuffers: fn(
self: *const ITraceDataCollector,
buffers: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_MinimumBuffers: fn(
self: *const ITraceDataCollector,
buffers: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_NumberOfBuffers: fn(
self: *const ITraceDataCollector,
buffers: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_NumberOfBuffers: fn(
self: *const ITraceDataCollector,
buffers: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_PreallocateFile: fn(
self: *const ITraceDataCollector,
allocate: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_PreallocateFile: fn(
self: *const ITraceDataCollector,
allocate: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ProcessMode: fn(
self: *const ITraceDataCollector,
process: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_ProcessMode: fn(
self: *const ITraceDataCollector,
process: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_RealTimeBuffersLost: fn(
self: *const ITraceDataCollector,
buffers: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_RealTimeBuffersLost: fn(
self: *const ITraceDataCollector,
buffers: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SessionId: fn(
self: *const ITraceDataCollector,
id: ?*u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_SessionId: fn(
self: *const ITraceDataCollector,
id: u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SessionName: fn(
self: *const ITraceDataCollector,
name: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_SessionName: fn(
self: *const ITraceDataCollector,
name: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SessionThreadId: fn(
self: *const ITraceDataCollector,
tid: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_SessionThreadId: fn(
self: *const ITraceDataCollector,
tid: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StreamMode: fn(
self: *const ITraceDataCollector,
mode: ?*StreamMode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_StreamMode: fn(
self: *const ITraceDataCollector,
mode: StreamMode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_TraceDataProviders: fn(
self: *const ITraceDataCollector,
providers: ?*?*ITraceDataProviderCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDataCollector.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_get_BufferSize(self: *const T, size: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_BufferSize(@ptrCast(*const ITraceDataCollector, self), size);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_put_BufferSize(self: *const T, size: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_BufferSize(@ptrCast(*const ITraceDataCollector, self), size);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_get_BuffersLost(self: *const T, buffers: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_BuffersLost(@ptrCast(*const ITraceDataCollector, self), buffers);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_put_BuffersLost(self: *const T, buffers: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_BuffersLost(@ptrCast(*const ITraceDataCollector, self), buffers);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_get_BuffersWritten(self: *const T, buffers: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_BuffersWritten(@ptrCast(*const ITraceDataCollector, self), buffers);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_put_BuffersWritten(self: *const T, buffers: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_BuffersWritten(@ptrCast(*const ITraceDataCollector, self), buffers);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_get_ClockType(self: *const T, clock: ?*ClockType) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_ClockType(@ptrCast(*const ITraceDataCollector, self), clock);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_put_ClockType(self: *const T, clock: ClockType) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_ClockType(@ptrCast(*const ITraceDataCollector, self), clock);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_get_EventsLost(self: *const T, events: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_EventsLost(@ptrCast(*const ITraceDataCollector, self), events);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_put_EventsLost(self: *const T, events: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_EventsLost(@ptrCast(*const ITraceDataCollector, self), events);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_get_ExtendedModes(self: *const T, mode: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_ExtendedModes(@ptrCast(*const ITraceDataCollector, self), mode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_put_ExtendedModes(self: *const T, mode: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_ExtendedModes(@ptrCast(*const ITraceDataCollector, self), mode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_get_FlushTimer(self: *const T, seconds: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_FlushTimer(@ptrCast(*const ITraceDataCollector, self), seconds);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_put_FlushTimer(self: *const T, seconds: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_FlushTimer(@ptrCast(*const ITraceDataCollector, self), seconds);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_get_FreeBuffers(self: *const T, buffers: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_FreeBuffers(@ptrCast(*const ITraceDataCollector, self), buffers);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_put_FreeBuffers(self: *const T, buffers: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_FreeBuffers(@ptrCast(*const ITraceDataCollector, self), buffers);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_get_Guid(self: *const T, guid: ?*Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_Guid(@ptrCast(*const ITraceDataCollector, self), guid);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_put_Guid(self: *const T, guid: Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_Guid(@ptrCast(*const ITraceDataCollector, self), guid);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_get_IsKernelTrace(self: *const T, kernel: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_IsKernelTrace(@ptrCast(*const ITraceDataCollector, self), kernel);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_get_MaximumBuffers(self: *const T, buffers: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_MaximumBuffers(@ptrCast(*const ITraceDataCollector, self), buffers);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_put_MaximumBuffers(self: *const T, buffers: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_MaximumBuffers(@ptrCast(*const ITraceDataCollector, self), buffers);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_get_MinimumBuffers(self: *const T, buffers: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_MinimumBuffers(@ptrCast(*const ITraceDataCollector, self), buffers);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_put_MinimumBuffers(self: *const T, buffers: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_MinimumBuffers(@ptrCast(*const ITraceDataCollector, self), buffers);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_get_NumberOfBuffers(self: *const T, buffers: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_NumberOfBuffers(@ptrCast(*const ITraceDataCollector, self), buffers);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_put_NumberOfBuffers(self: *const T, buffers: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_NumberOfBuffers(@ptrCast(*const ITraceDataCollector, self), buffers);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_get_PreallocateFile(self: *const T, allocate: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_PreallocateFile(@ptrCast(*const ITraceDataCollector, self), allocate);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_put_PreallocateFile(self: *const T, allocate: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_PreallocateFile(@ptrCast(*const ITraceDataCollector, self), allocate);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_get_ProcessMode(self: *const T, process: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_ProcessMode(@ptrCast(*const ITraceDataCollector, self), process);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_put_ProcessMode(self: *const T, process: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_ProcessMode(@ptrCast(*const ITraceDataCollector, self), process);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_get_RealTimeBuffersLost(self: *const T, buffers: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_RealTimeBuffersLost(@ptrCast(*const ITraceDataCollector, self), buffers);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_put_RealTimeBuffersLost(self: *const T, buffers: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_RealTimeBuffersLost(@ptrCast(*const ITraceDataCollector, self), buffers);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_get_SessionId(self: *const T, id: ?*u64) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_SessionId(@ptrCast(*const ITraceDataCollector, self), id);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_put_SessionId(self: *const T, id: u64) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_SessionId(@ptrCast(*const ITraceDataCollector, self), id);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_get_SessionName(self: *const T, name: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_SessionName(@ptrCast(*const ITraceDataCollector, self), name);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_put_SessionName(self: *const T, name: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_SessionName(@ptrCast(*const ITraceDataCollector, self), name);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_get_SessionThreadId(self: *const T, tid: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_SessionThreadId(@ptrCast(*const ITraceDataCollector, self), tid);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_put_SessionThreadId(self: *const T, tid: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_SessionThreadId(@ptrCast(*const ITraceDataCollector, self), tid);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_get_StreamMode(self: *const T, mode: ?*StreamMode) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_StreamMode(@ptrCast(*const ITraceDataCollector, self), mode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_put_StreamMode(self: *const T, mode: StreamMode) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).put_StreamMode(@ptrCast(*const ITraceDataCollector, self), mode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataCollector_get_TraceDataProviders(self: *const T, providers: ?*?*ITraceDataProviderCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataCollector.VTable, self.vtable).get_TraceDataProviders(@ptrCast(*const ITraceDataCollector, self), providers);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IConfigurationDataCollector_Value = @import("../zig.zig").Guid.initString("03837514-098b-11d8-9414-505054503030");
pub const IID_IConfigurationDataCollector = &IID_IConfigurationDataCollector_Value;
pub const IConfigurationDataCollector = extern struct {
pub const VTable = extern struct {
base: IDataCollector.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_FileMaxCount: fn(
self: *const IConfigurationDataCollector,
count: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_FileMaxCount: fn(
self: *const IConfigurationDataCollector,
count: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_FileMaxRecursiveDepth: fn(
self: *const IConfigurationDataCollector,
depth: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_FileMaxRecursiveDepth: fn(
self: *const IConfigurationDataCollector,
depth: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_FileMaxTotalSize: fn(
self: *const IConfigurationDataCollector,
size: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_FileMaxTotalSize: fn(
self: *const IConfigurationDataCollector,
size: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Files: fn(
self: *const IConfigurationDataCollector,
Files: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Files: fn(
self: *const IConfigurationDataCollector,
Files: ?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ManagementQueries: fn(
self: *const IConfigurationDataCollector,
Queries: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_ManagementQueries: fn(
self: *const IConfigurationDataCollector,
Queries: ?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_QueryNetworkAdapters: fn(
self: *const IConfigurationDataCollector,
network: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_QueryNetworkAdapters: fn(
self: *const IConfigurationDataCollector,
network: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_RegistryKeys: fn(
self: *const IConfigurationDataCollector,
query: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_RegistryKeys: fn(
self: *const IConfigurationDataCollector,
query: ?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_RegistryMaxRecursiveDepth: fn(
self: *const IConfigurationDataCollector,
depth: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_RegistryMaxRecursiveDepth: fn(
self: *const IConfigurationDataCollector,
depth: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SystemStateFile: fn(
self: *const IConfigurationDataCollector,
FileName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_SystemStateFile: fn(
self: *const IConfigurationDataCollector,
FileName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDataCollector.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IConfigurationDataCollector_get_FileMaxCount(self: *const T, count: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).get_FileMaxCount(@ptrCast(*const IConfigurationDataCollector, self), count);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IConfigurationDataCollector_put_FileMaxCount(self: *const T, count: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).put_FileMaxCount(@ptrCast(*const IConfigurationDataCollector, self), count);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IConfigurationDataCollector_get_FileMaxRecursiveDepth(self: *const T, depth: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).get_FileMaxRecursiveDepth(@ptrCast(*const IConfigurationDataCollector, self), depth);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IConfigurationDataCollector_put_FileMaxRecursiveDepth(self: *const T, depth: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).put_FileMaxRecursiveDepth(@ptrCast(*const IConfigurationDataCollector, self), depth);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IConfigurationDataCollector_get_FileMaxTotalSize(self: *const T, size: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).get_FileMaxTotalSize(@ptrCast(*const IConfigurationDataCollector, self), size);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IConfigurationDataCollector_put_FileMaxTotalSize(self: *const T, size: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).put_FileMaxTotalSize(@ptrCast(*const IConfigurationDataCollector, self), size);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IConfigurationDataCollector_get_Files(self: *const T, Files: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).get_Files(@ptrCast(*const IConfigurationDataCollector, self), Files);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IConfigurationDataCollector_put_Files(self: *const T, Files: ?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).put_Files(@ptrCast(*const IConfigurationDataCollector, self), Files);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IConfigurationDataCollector_get_ManagementQueries(self: *const T, Queries: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).get_ManagementQueries(@ptrCast(*const IConfigurationDataCollector, self), Queries);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IConfigurationDataCollector_put_ManagementQueries(self: *const T, Queries: ?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).put_ManagementQueries(@ptrCast(*const IConfigurationDataCollector, self), Queries);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IConfigurationDataCollector_get_QueryNetworkAdapters(self: *const T, network: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).get_QueryNetworkAdapters(@ptrCast(*const IConfigurationDataCollector, self), network);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IConfigurationDataCollector_put_QueryNetworkAdapters(self: *const T, network: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).put_QueryNetworkAdapters(@ptrCast(*const IConfigurationDataCollector, self), network);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IConfigurationDataCollector_get_RegistryKeys(self: *const T, query: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).get_RegistryKeys(@ptrCast(*const IConfigurationDataCollector, self), query);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IConfigurationDataCollector_put_RegistryKeys(self: *const T, query: ?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).put_RegistryKeys(@ptrCast(*const IConfigurationDataCollector, self), query);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IConfigurationDataCollector_get_RegistryMaxRecursiveDepth(self: *const T, depth: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).get_RegistryMaxRecursiveDepth(@ptrCast(*const IConfigurationDataCollector, self), depth);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IConfigurationDataCollector_put_RegistryMaxRecursiveDepth(self: *const T, depth: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).put_RegistryMaxRecursiveDepth(@ptrCast(*const IConfigurationDataCollector, self), depth);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IConfigurationDataCollector_get_SystemStateFile(self: *const T, FileName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).get_SystemStateFile(@ptrCast(*const IConfigurationDataCollector, self), FileName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IConfigurationDataCollector_put_SystemStateFile(self: *const T, FileName: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IConfigurationDataCollector.VTable, self.vtable).put_SystemStateFile(@ptrCast(*const IConfigurationDataCollector, self), FileName);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IAlertDataCollector_Value = @import("../zig.zig").Guid.initString("03837516-098b-11d8-9414-505054503030");
pub const IID_IAlertDataCollector = &IID_IAlertDataCollector_Value;
pub const IAlertDataCollector = extern struct {
pub const VTable = extern struct {
base: IDataCollector.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_AlertThresholds: fn(
self: *const IAlertDataCollector,
alerts: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_AlertThresholds: fn(
self: *const IAlertDataCollector,
alerts: ?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_EventLog: fn(
self: *const IAlertDataCollector,
log: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_EventLog: fn(
self: *const IAlertDataCollector,
log: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SampleInterval: fn(
self: *const IAlertDataCollector,
interval: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_SampleInterval: fn(
self: *const IAlertDataCollector,
interval: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Task: fn(
self: *const IAlertDataCollector,
task: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Task: fn(
self: *const IAlertDataCollector,
task: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_TaskRunAsSelf: fn(
self: *const IAlertDataCollector,
RunAsSelf: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_TaskRunAsSelf: fn(
self: *const IAlertDataCollector,
RunAsSelf: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_TaskArguments: fn(
self: *const IAlertDataCollector,
task: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_TaskArguments: fn(
self: *const IAlertDataCollector,
task: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_TaskUserTextArguments: fn(
self: *const IAlertDataCollector,
task: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_TaskUserTextArguments: fn(
self: *const IAlertDataCollector,
task: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_TriggerDataCollectorSet: fn(
self: *const IAlertDataCollector,
name: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_TriggerDataCollectorSet: fn(
self: *const IAlertDataCollector,
name: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDataCollector.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAlertDataCollector_get_AlertThresholds(self: *const T, alerts: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).get_AlertThresholds(@ptrCast(*const IAlertDataCollector, self), alerts);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAlertDataCollector_put_AlertThresholds(self: *const T, alerts: ?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).put_AlertThresholds(@ptrCast(*const IAlertDataCollector, self), alerts);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAlertDataCollector_get_EventLog(self: *const T, log: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).get_EventLog(@ptrCast(*const IAlertDataCollector, self), log);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAlertDataCollector_put_EventLog(self: *const T, log: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).put_EventLog(@ptrCast(*const IAlertDataCollector, self), log);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAlertDataCollector_get_SampleInterval(self: *const T, interval: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).get_SampleInterval(@ptrCast(*const IAlertDataCollector, self), interval);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAlertDataCollector_put_SampleInterval(self: *const T, interval: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).put_SampleInterval(@ptrCast(*const IAlertDataCollector, self), interval);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAlertDataCollector_get_Task(self: *const T, task: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).get_Task(@ptrCast(*const IAlertDataCollector, self), task);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAlertDataCollector_put_Task(self: *const T, task: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).put_Task(@ptrCast(*const IAlertDataCollector, self), task);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAlertDataCollector_get_TaskRunAsSelf(self: *const T, RunAsSelf: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).get_TaskRunAsSelf(@ptrCast(*const IAlertDataCollector, self), RunAsSelf);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAlertDataCollector_put_TaskRunAsSelf(self: *const T, RunAsSelf: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).put_TaskRunAsSelf(@ptrCast(*const IAlertDataCollector, self), RunAsSelf);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAlertDataCollector_get_TaskArguments(self: *const T, task: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).get_TaskArguments(@ptrCast(*const IAlertDataCollector, self), task);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAlertDataCollector_put_TaskArguments(self: *const T, task: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).put_TaskArguments(@ptrCast(*const IAlertDataCollector, self), task);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAlertDataCollector_get_TaskUserTextArguments(self: *const T, task: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).get_TaskUserTextArguments(@ptrCast(*const IAlertDataCollector, self), task);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAlertDataCollector_put_TaskUserTextArguments(self: *const T, task: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).put_TaskUserTextArguments(@ptrCast(*const IAlertDataCollector, self), task);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAlertDataCollector_get_TriggerDataCollectorSet(self: *const T, name: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).get_TriggerDataCollectorSet(@ptrCast(*const IAlertDataCollector, self), name);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAlertDataCollector_put_TriggerDataCollectorSet(self: *const T, name: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IAlertDataCollector.VTable, self.vtable).put_TriggerDataCollectorSet(@ptrCast(*const IAlertDataCollector, self), name);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IApiTracingDataCollector_Value = @import("../zig.zig").Guid.initString("0383751a-098b-11d8-9414-505054503030");
pub const IID_IApiTracingDataCollector = &IID_IApiTracingDataCollector_Value;
pub const IApiTracingDataCollector = extern struct {
pub const VTable = extern struct {
base: IDataCollector.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_LogApiNamesOnly: fn(
self: *const IApiTracingDataCollector,
logapinames: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_LogApiNamesOnly: fn(
self: *const IApiTracingDataCollector,
logapinames: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_LogApisRecursively: fn(
self: *const IApiTracingDataCollector,
logrecursively: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_LogApisRecursively: fn(
self: *const IApiTracingDataCollector,
logrecursively: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ExePath: fn(
self: *const IApiTracingDataCollector,
exepath: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_ExePath: fn(
self: *const IApiTracingDataCollector,
exepath: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_LogFilePath: fn(
self: *const IApiTracingDataCollector,
logfilepath: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_LogFilePath: fn(
self: *const IApiTracingDataCollector,
logfilepath: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_IncludeModules: fn(
self: *const IApiTracingDataCollector,
includemodules: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_IncludeModules: fn(
self: *const IApiTracingDataCollector,
includemodules: ?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_IncludeApis: fn(
self: *const IApiTracingDataCollector,
includeapis: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_IncludeApis: fn(
self: *const IApiTracingDataCollector,
includeapis: ?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ExcludeApis: fn(
self: *const IApiTracingDataCollector,
excludeapis: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_ExcludeApis: fn(
self: *const IApiTracingDataCollector,
excludeapis: ?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDataCollector.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IApiTracingDataCollector_get_LogApiNamesOnly(self: *const T, logapinames: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IApiTracingDataCollector.VTable, self.vtable).get_LogApiNamesOnly(@ptrCast(*const IApiTracingDataCollector, self), logapinames);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IApiTracingDataCollector_put_LogApiNamesOnly(self: *const T, logapinames: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IApiTracingDataCollector.VTable, self.vtable).put_LogApiNamesOnly(@ptrCast(*const IApiTracingDataCollector, self), logapinames);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IApiTracingDataCollector_get_LogApisRecursively(self: *const T, logrecursively: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IApiTracingDataCollector.VTable, self.vtable).get_LogApisRecursively(@ptrCast(*const IApiTracingDataCollector, self), logrecursively);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IApiTracingDataCollector_put_LogApisRecursively(self: *const T, logrecursively: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IApiTracingDataCollector.VTable, self.vtable).put_LogApisRecursively(@ptrCast(*const IApiTracingDataCollector, self), logrecursively);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IApiTracingDataCollector_get_ExePath(self: *const T, exepath: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IApiTracingDataCollector.VTable, self.vtable).get_ExePath(@ptrCast(*const IApiTracingDataCollector, self), exepath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IApiTracingDataCollector_put_ExePath(self: *const T, exepath: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IApiTracingDataCollector.VTable, self.vtable).put_ExePath(@ptrCast(*const IApiTracingDataCollector, self), exepath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IApiTracingDataCollector_get_LogFilePath(self: *const T, logfilepath: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IApiTracingDataCollector.VTable, self.vtable).get_LogFilePath(@ptrCast(*const IApiTracingDataCollector, self), logfilepath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IApiTracingDataCollector_put_LogFilePath(self: *const T, logfilepath: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IApiTracingDataCollector.VTable, self.vtable).put_LogFilePath(@ptrCast(*const IApiTracingDataCollector, self), logfilepath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IApiTracingDataCollector_get_IncludeModules(self: *const T, includemodules: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IApiTracingDataCollector.VTable, self.vtable).get_IncludeModules(@ptrCast(*const IApiTracingDataCollector, self), includemodules);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IApiTracingDataCollector_put_IncludeModules(self: *const T, includemodules: ?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IApiTracingDataCollector.VTable, self.vtable).put_IncludeModules(@ptrCast(*const IApiTracingDataCollector, self), includemodules);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IApiTracingDataCollector_get_IncludeApis(self: *const T, includeapis: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IApiTracingDataCollector.VTable, self.vtable).get_IncludeApis(@ptrCast(*const IApiTracingDataCollector, self), includeapis);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IApiTracingDataCollector_put_IncludeApis(self: *const T, includeapis: ?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IApiTracingDataCollector.VTable, self.vtable).put_IncludeApis(@ptrCast(*const IApiTracingDataCollector, self), includeapis);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IApiTracingDataCollector_get_ExcludeApis(self: *const T, excludeapis: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IApiTracingDataCollector.VTable, self.vtable).get_ExcludeApis(@ptrCast(*const IApiTracingDataCollector, self), excludeapis);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IApiTracingDataCollector_put_ExcludeApis(self: *const T, excludeapis: ?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const IApiTracingDataCollector.VTable, self.vtable).put_ExcludeApis(@ptrCast(*const IApiTracingDataCollector, self), excludeapis);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IDataCollectorCollection_Value = @import("../zig.zig").Guid.initString("03837502-098b-11d8-9414-505054503030");
pub const IID_IDataCollectorCollection = &IID_IDataCollectorCollection_Value;
pub const IDataCollectorCollection = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Count: fn(
self: *const IDataCollectorCollection,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Item: fn(
self: *const IDataCollectorCollection,
index: VARIANT,
collector: ?*?*IDataCollector,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get__NewEnum: fn(
self: *const IDataCollectorCollection,
retVal: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Add: fn(
self: *const IDataCollectorCollection,
collector: ?*IDataCollector,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Remove: fn(
self: *const IDataCollectorCollection,
collector: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clear: fn(
self: *const IDataCollectorCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddRange: fn(
self: *const IDataCollectorCollection,
collectors: ?*IDataCollectorCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateDataCollectorFromXml: fn(
self: *const IDataCollectorCollection,
bstrXml: ?BSTR,
pValidation: ?*?*IValueMap,
pCollector: ?*?*IDataCollector,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateDataCollector: fn(
self: *const IDataCollectorCollection,
Type: DataCollectorType,
Collector: ?*?*IDataCollector,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorCollection_get_Count(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorCollection.VTable, self.vtable).get_Count(@ptrCast(*const IDataCollectorCollection, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorCollection_get_Item(self: *const T, index: VARIANT, collector: ?*?*IDataCollector) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorCollection.VTable, self.vtable).get_Item(@ptrCast(*const IDataCollectorCollection, self), index, collector);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorCollection_get__NewEnum(self: *const T, retVal: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorCollection.VTable, self.vtable).get__NewEnum(@ptrCast(*const IDataCollectorCollection, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorCollection_Add(self: *const T, collector: ?*IDataCollector) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorCollection.VTable, self.vtable).Add(@ptrCast(*const IDataCollectorCollection, self), collector);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorCollection_Remove(self: *const T, collector: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorCollection.VTable, self.vtable).Remove(@ptrCast(*const IDataCollectorCollection, self), collector);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorCollection_Clear(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorCollection.VTable, self.vtable).Clear(@ptrCast(*const IDataCollectorCollection, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorCollection_AddRange(self: *const T, collectors: ?*IDataCollectorCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorCollection.VTable, self.vtable).AddRange(@ptrCast(*const IDataCollectorCollection, self), collectors);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorCollection_CreateDataCollectorFromXml(self: *const T, bstrXml: ?BSTR, pValidation: ?*?*IValueMap, pCollector: ?*?*IDataCollector) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorCollection.VTable, self.vtable).CreateDataCollectorFromXml(@ptrCast(*const IDataCollectorCollection, self), bstrXml, pValidation, pCollector);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorCollection_CreateDataCollector(self: *const T, Type: DataCollectorType, Collector: ?*?*IDataCollector) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorCollection.VTable, self.vtable).CreateDataCollector(@ptrCast(*const IDataCollectorCollection, self), Type, Collector);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IDataCollectorSetCollection_Value = @import("../zig.zig").Guid.initString("03837524-098b-11d8-9414-505054503030");
pub const IID_IDataCollectorSetCollection = &IID_IDataCollectorSetCollection_Value;
pub const IDataCollectorSetCollection = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Count: fn(
self: *const IDataCollectorSetCollection,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Item: fn(
self: *const IDataCollectorSetCollection,
index: VARIANT,
set: ?*?*IDataCollectorSet,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get__NewEnum: fn(
self: *const IDataCollectorSetCollection,
retVal: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Add: fn(
self: *const IDataCollectorSetCollection,
set: ?*IDataCollectorSet,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Remove: fn(
self: *const IDataCollectorSetCollection,
set: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clear: fn(
self: *const IDataCollectorSetCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddRange: fn(
self: *const IDataCollectorSetCollection,
sets: ?*IDataCollectorSetCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDataCollectorSets: fn(
self: *const IDataCollectorSetCollection,
server: ?BSTR,
filter: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSetCollection_get_Count(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSetCollection.VTable, self.vtable).get_Count(@ptrCast(*const IDataCollectorSetCollection, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSetCollection_get_Item(self: *const T, index: VARIANT, set: ?*?*IDataCollectorSet) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSetCollection.VTable, self.vtable).get_Item(@ptrCast(*const IDataCollectorSetCollection, self), index, set);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSetCollection_get__NewEnum(self: *const T, retVal: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSetCollection.VTable, self.vtable).get__NewEnum(@ptrCast(*const IDataCollectorSetCollection, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSetCollection_Add(self: *const T, set: ?*IDataCollectorSet) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSetCollection.VTable, self.vtable).Add(@ptrCast(*const IDataCollectorSetCollection, self), set);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSetCollection_Remove(self: *const T, set: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSetCollection.VTable, self.vtable).Remove(@ptrCast(*const IDataCollectorSetCollection, self), set);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSetCollection_Clear(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSetCollection.VTable, self.vtable).Clear(@ptrCast(*const IDataCollectorSetCollection, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSetCollection_AddRange(self: *const T, sets: ?*IDataCollectorSetCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSetCollection.VTable, self.vtable).AddRange(@ptrCast(*const IDataCollectorSetCollection, self), sets);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IDataCollectorSetCollection_GetDataCollectorSets(self: *const T, server: ?BSTR, filter: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IDataCollectorSetCollection.VTable, self.vtable).GetDataCollectorSets(@ptrCast(*const IDataCollectorSetCollection, self), server, filter);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_ITraceDataProvider_Value = @import("../zig.zig").Guid.initString("03837512-098b-11d8-9414-505054503030");
pub const IID_ITraceDataProvider = &IID_ITraceDataProvider_Value;
pub const ITraceDataProvider = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_DisplayName: fn(
self: *const ITraceDataProvider,
name: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_DisplayName: fn(
self: *const ITraceDataProvider,
name: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Guid: fn(
self: *const ITraceDataProvider,
guid: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Guid: fn(
self: *const ITraceDataProvider,
guid: Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Level: fn(
self: *const ITraceDataProvider,
ppLevel: ?*?*IValueMap,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_KeywordsAny: fn(
self: *const ITraceDataProvider,
ppKeywords: ?*?*IValueMap,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_KeywordsAll: fn(
self: *const ITraceDataProvider,
ppKeywords: ?*?*IValueMap,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Properties: fn(
self: *const ITraceDataProvider,
ppProperties: ?*?*IValueMap,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_FilterEnabled: fn(
self: *const ITraceDataProvider,
FilterEnabled: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_FilterEnabled: fn(
self: *const ITraceDataProvider,
FilterEnabled: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_FilterType: fn(
self: *const ITraceDataProvider,
pulType: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_FilterType: fn(
self: *const ITraceDataProvider,
ulType: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_FilterData: fn(
self: *const ITraceDataProvider,
ppData: ?*?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_FilterData: fn(
self: *const ITraceDataProvider,
pData: ?*SAFEARRAY,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Query: fn(
self: *const ITraceDataProvider,
bstrName: ?BSTR,
bstrServer: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Resolve: fn(
self: *const ITraceDataProvider,
pFrom: ?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetSecurity: fn(
self: *const ITraceDataProvider,
Sddl: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSecurity: fn(
self: *const ITraceDataProvider,
SecurityInfo: u32,
Sddl: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetRegisteredProcesses: fn(
self: *const ITraceDataProvider,
Processes: ?*?*IValueMap,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProvider_get_DisplayName(self: *const T, name: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).get_DisplayName(@ptrCast(*const ITraceDataProvider, self), name);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProvider_put_DisplayName(self: *const T, name: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).put_DisplayName(@ptrCast(*const ITraceDataProvider, self), name);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProvider_get_Guid(self: *const T, guid: ?*Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).get_Guid(@ptrCast(*const ITraceDataProvider, self), guid);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProvider_put_Guid(self: *const T, guid: Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).put_Guid(@ptrCast(*const ITraceDataProvider, self), guid);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProvider_get_Level(self: *const T, ppLevel: ?*?*IValueMap) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).get_Level(@ptrCast(*const ITraceDataProvider, self), ppLevel);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProvider_get_KeywordsAny(self: *const T, ppKeywords: ?*?*IValueMap) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).get_KeywordsAny(@ptrCast(*const ITraceDataProvider, self), ppKeywords);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProvider_get_KeywordsAll(self: *const T, ppKeywords: ?*?*IValueMap) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).get_KeywordsAll(@ptrCast(*const ITraceDataProvider, self), ppKeywords);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProvider_get_Properties(self: *const T, ppProperties: ?*?*IValueMap) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).get_Properties(@ptrCast(*const ITraceDataProvider, self), ppProperties);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProvider_get_FilterEnabled(self: *const T, FilterEnabled: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).get_FilterEnabled(@ptrCast(*const ITraceDataProvider, self), FilterEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProvider_put_FilterEnabled(self: *const T, FilterEnabled: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).put_FilterEnabled(@ptrCast(*const ITraceDataProvider, self), FilterEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProvider_get_FilterType(self: *const T, pulType: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).get_FilterType(@ptrCast(*const ITraceDataProvider, self), pulType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProvider_put_FilterType(self: *const T, ulType: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).put_FilterType(@ptrCast(*const ITraceDataProvider, self), ulType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProvider_get_FilterData(self: *const T, ppData: ?*?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).get_FilterData(@ptrCast(*const ITraceDataProvider, self), ppData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProvider_put_FilterData(self: *const T, pData: ?*SAFEARRAY) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).put_FilterData(@ptrCast(*const ITraceDataProvider, self), pData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProvider_Query(self: *const T, bstrName: ?BSTR, bstrServer: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).Query(@ptrCast(*const ITraceDataProvider, self), bstrName, bstrServer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProvider_Resolve(self: *const T, pFrom: ?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).Resolve(@ptrCast(*const ITraceDataProvider, self), pFrom);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProvider_SetSecurity(self: *const T, Sddl: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).SetSecurity(@ptrCast(*const ITraceDataProvider, self), Sddl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProvider_GetSecurity(self: *const T, SecurityInfo: u32, Sddl: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).GetSecurity(@ptrCast(*const ITraceDataProvider, self), SecurityInfo, Sddl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProvider_GetRegisteredProcesses(self: *const T, Processes: ?*?*IValueMap) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProvider.VTable, self.vtable).GetRegisteredProcesses(@ptrCast(*const ITraceDataProvider, self), Processes);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_ITraceDataProviderCollection_Value = @import("../zig.zig").Guid.initString("03837510-098b-11d8-9414-505054503030");
pub const IID_ITraceDataProviderCollection = &IID_ITraceDataProviderCollection_Value;
pub const ITraceDataProviderCollection = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Count: fn(
self: *const ITraceDataProviderCollection,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Item: fn(
self: *const ITraceDataProviderCollection,
index: VARIANT,
ppProvider: ?*?*ITraceDataProvider,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get__NewEnum: fn(
self: *const ITraceDataProviderCollection,
retVal: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Add: fn(
self: *const ITraceDataProviderCollection,
pProvider: ?*ITraceDataProvider,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Remove: fn(
self: *const ITraceDataProviderCollection,
vProvider: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clear: fn(
self: *const ITraceDataProviderCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddRange: fn(
self: *const ITraceDataProviderCollection,
providers: ?*ITraceDataProviderCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateTraceDataProvider: fn(
self: *const ITraceDataProviderCollection,
Provider: ?*?*ITraceDataProvider,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTraceDataProviders: fn(
self: *const ITraceDataProviderCollection,
server: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTraceDataProvidersByProcess: fn(
self: *const ITraceDataProviderCollection,
Server: ?BSTR,
Pid: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProviderCollection_get_Count(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProviderCollection.VTable, self.vtable).get_Count(@ptrCast(*const ITraceDataProviderCollection, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProviderCollection_get_Item(self: *const T, index: VARIANT, ppProvider: ?*?*ITraceDataProvider) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProviderCollection.VTable, self.vtable).get_Item(@ptrCast(*const ITraceDataProviderCollection, self), index, ppProvider);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProviderCollection_get__NewEnum(self: *const T, retVal: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProviderCollection.VTable, self.vtable).get__NewEnum(@ptrCast(*const ITraceDataProviderCollection, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProviderCollection_Add(self: *const T, pProvider: ?*ITraceDataProvider) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProviderCollection.VTable, self.vtable).Add(@ptrCast(*const ITraceDataProviderCollection, self), pProvider);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProviderCollection_Remove(self: *const T, vProvider: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProviderCollection.VTable, self.vtable).Remove(@ptrCast(*const ITraceDataProviderCollection, self), vProvider);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProviderCollection_Clear(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProviderCollection.VTable, self.vtable).Clear(@ptrCast(*const ITraceDataProviderCollection, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProviderCollection_AddRange(self: *const T, providers: ?*ITraceDataProviderCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProviderCollection.VTable, self.vtable).AddRange(@ptrCast(*const ITraceDataProviderCollection, self), providers);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProviderCollection_CreateTraceDataProvider(self: *const T, Provider: ?*?*ITraceDataProvider) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProviderCollection.VTable, self.vtable).CreateTraceDataProvider(@ptrCast(*const ITraceDataProviderCollection, self), Provider);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProviderCollection_GetTraceDataProviders(self: *const T, server: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProviderCollection.VTable, self.vtable).GetTraceDataProviders(@ptrCast(*const ITraceDataProviderCollection, self), server);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITraceDataProviderCollection_GetTraceDataProvidersByProcess(self: *const T, Server: ?BSTR, Pid: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITraceDataProviderCollection.VTable, self.vtable).GetTraceDataProvidersByProcess(@ptrCast(*const ITraceDataProviderCollection, self), Server, Pid);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_ISchedule_Value = @import("../zig.zig").Guid.initString("0383753a-098b-11d8-9414-505054503030");
pub const IID_ISchedule = &IID_ISchedule_Value;
pub const ISchedule = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StartDate: fn(
self: *const ISchedule,
start: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_StartDate: fn(
self: *const ISchedule,
start: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_EndDate: fn(
self: *const ISchedule,
end: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_EndDate: fn(
self: *const ISchedule,
end: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_StartTime: fn(
self: *const ISchedule,
start: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_StartTime: fn(
self: *const ISchedule,
start: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Days: fn(
self: *const ISchedule,
days: ?*WeekDays,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Days: fn(
self: *const ISchedule,
days: WeekDays,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchedule_get_StartDate(self: *const T, start: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchedule.VTable, self.vtable).get_StartDate(@ptrCast(*const ISchedule, self), start);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchedule_put_StartDate(self: *const T, start: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchedule.VTable, self.vtable).put_StartDate(@ptrCast(*const ISchedule, self), start);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchedule_get_EndDate(self: *const T, end: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchedule.VTable, self.vtable).get_EndDate(@ptrCast(*const ISchedule, self), end);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchedule_put_EndDate(self: *const T, end: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchedule.VTable, self.vtable).put_EndDate(@ptrCast(*const ISchedule, self), end);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchedule_get_StartTime(self: *const T, start: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchedule.VTable, self.vtable).get_StartTime(@ptrCast(*const ISchedule, self), start);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchedule_put_StartTime(self: *const T, start: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchedule.VTable, self.vtable).put_StartTime(@ptrCast(*const ISchedule, self), start);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchedule_get_Days(self: *const T, days: ?*WeekDays) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchedule.VTable, self.vtable).get_Days(@ptrCast(*const ISchedule, self), days);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISchedule_put_Days(self: *const T, days: WeekDays) callconv(.Inline) HRESULT {
return @ptrCast(*const ISchedule.VTable, self.vtable).put_Days(@ptrCast(*const ISchedule, self), days);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IScheduleCollection_Value = @import("../zig.zig").Guid.initString("0383753d-098b-11d8-9414-505054503030");
pub const IID_IScheduleCollection = &IID_IScheduleCollection_Value;
pub const IScheduleCollection = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Count: fn(
self: *const IScheduleCollection,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Item: fn(
self: *const IScheduleCollection,
index: VARIANT,
ppSchedule: ?*?*ISchedule,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get__NewEnum: fn(
self: *const IScheduleCollection,
ienum: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Add: fn(
self: *const IScheduleCollection,
pSchedule: ?*ISchedule,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Remove: fn(
self: *const IScheduleCollection,
vSchedule: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clear: fn(
self: *const IScheduleCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddRange: fn(
self: *const IScheduleCollection,
pSchedules: ?*IScheduleCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateSchedule: fn(
self: *const IScheduleCollection,
Schedule: ?*?*ISchedule,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IScheduleCollection_get_Count(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IScheduleCollection.VTable, self.vtable).get_Count(@ptrCast(*const IScheduleCollection, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IScheduleCollection_get_Item(self: *const T, index: VARIANT, ppSchedule: ?*?*ISchedule) callconv(.Inline) HRESULT {
return @ptrCast(*const IScheduleCollection.VTable, self.vtable).get_Item(@ptrCast(*const IScheduleCollection, self), index, ppSchedule);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IScheduleCollection_get__NewEnum(self: *const T, ienum: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IScheduleCollection.VTable, self.vtable).get__NewEnum(@ptrCast(*const IScheduleCollection, self), ienum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IScheduleCollection_Add(self: *const T, pSchedule: ?*ISchedule) callconv(.Inline) HRESULT {
return @ptrCast(*const IScheduleCollection.VTable, self.vtable).Add(@ptrCast(*const IScheduleCollection, self), pSchedule);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IScheduleCollection_Remove(self: *const T, vSchedule: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IScheduleCollection.VTable, self.vtable).Remove(@ptrCast(*const IScheduleCollection, self), vSchedule);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IScheduleCollection_Clear(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IScheduleCollection.VTable, self.vtable).Clear(@ptrCast(*const IScheduleCollection, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IScheduleCollection_AddRange(self: *const T, pSchedules: ?*IScheduleCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IScheduleCollection.VTable, self.vtable).AddRange(@ptrCast(*const IScheduleCollection, self), pSchedules);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IScheduleCollection_CreateSchedule(self: *const T, Schedule: ?*?*ISchedule) callconv(.Inline) HRESULT {
return @ptrCast(*const IScheduleCollection.VTable, self.vtable).CreateSchedule(@ptrCast(*const IScheduleCollection, self), Schedule);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IValueMapItem_Value = @import("../zig.zig").Guid.initString("03837533-098b-11d8-9414-505054503030");
pub const IID_IValueMapItem = &IID_IValueMapItem_Value;
pub const IValueMapItem = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Description: fn(
self: *const IValueMapItem,
description: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Description: fn(
self: *const IValueMapItem,
description: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Enabled: fn(
self: *const IValueMapItem,
enabled: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Enabled: fn(
self: *const IValueMapItem,
enabled: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Key: fn(
self: *const IValueMapItem,
key: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Key: fn(
self: *const IValueMapItem,
key: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Value: fn(
self: *const IValueMapItem,
Value: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Value: fn(
self: *const IValueMapItem,
Value: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ValueMapType: fn(
self: *const IValueMapItem,
type: ?*ValueMapType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_ValueMapType: fn(
self: *const IValueMapItem,
type: ValueMapType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IValueMapItem_get_Description(self: *const T, description: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IValueMapItem.VTable, self.vtable).get_Description(@ptrCast(*const IValueMapItem, self), description);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IValueMapItem_put_Description(self: *const T, description: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IValueMapItem.VTable, self.vtable).put_Description(@ptrCast(*const IValueMapItem, self), description);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IValueMapItem_get_Enabled(self: *const T, enabled: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IValueMapItem.VTable, self.vtable).get_Enabled(@ptrCast(*const IValueMapItem, self), enabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IValueMapItem_put_Enabled(self: *const T, enabled: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IValueMapItem.VTable, self.vtable).put_Enabled(@ptrCast(*const IValueMapItem, self), enabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IValueMapItem_get_Key(self: *const T, key: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IValueMapItem.VTable, self.vtable).get_Key(@ptrCast(*const IValueMapItem, self), key);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IValueMapItem_put_Key(self: *const T, key: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IValueMapItem.VTable, self.vtable).put_Key(@ptrCast(*const IValueMapItem, self), key);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IValueMapItem_get_Value(self: *const T, Value: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IValueMapItem.VTable, self.vtable).get_Value(@ptrCast(*const IValueMapItem, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IValueMapItem_put_Value(self: *const T, Value: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IValueMapItem.VTable, self.vtable).put_Value(@ptrCast(*const IValueMapItem, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IValueMapItem_get_ValueMapType(self: *const T, type_: ?*ValueMapType) callconv(.Inline) HRESULT {
return @ptrCast(*const IValueMapItem.VTable, self.vtable).get_ValueMapType(@ptrCast(*const IValueMapItem, self), type_);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IValueMapItem_put_ValueMapType(self: *const T, type_: ValueMapType) callconv(.Inline) HRESULT {
return @ptrCast(*const IValueMapItem.VTable, self.vtable).put_ValueMapType(@ptrCast(*const IValueMapItem, self), type_);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IValueMap_Value = @import("../zig.zig").Guid.initString("03837534-098b-11d8-9414-505054503030");
pub const IID_IValueMap = &IID_IValueMap_Value;
pub const IValueMap = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Count: fn(
self: *const IValueMap,
retVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Item: fn(
self: *const IValueMap,
index: VARIANT,
value: ?*?*IValueMapItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get__NewEnum: fn(
self: *const IValueMap,
retVal: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Description: fn(
self: *const IValueMap,
description: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Description: fn(
self: *const IValueMap,
description: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Value: fn(
self: *const IValueMap,
Value: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Value: fn(
self: *const IValueMap,
Value: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ValueMapType: fn(
self: *const IValueMap,
type: ?*ValueMapType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_ValueMapType: fn(
self: *const IValueMap,
type: ValueMapType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Add: fn(
self: *const IValueMap,
value: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Remove: fn(
self: *const IValueMap,
value: VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clear: fn(
self: *const IValueMap,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddRange: fn(
self: *const IValueMap,
map: ?*IValueMap,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateValueMapItem: fn(
self: *const IValueMap,
Item: ?*?*IValueMapItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IValueMap_get_Count(self: *const T, retVal: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IValueMap.VTable, self.vtable).get_Count(@ptrCast(*const IValueMap, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IValueMap_get_Item(self: *const T, index: VARIANT, value: ?*?*IValueMapItem) callconv(.Inline) HRESULT {
return @ptrCast(*const IValueMap.VTable, self.vtable).get_Item(@ptrCast(*const IValueMap, self), index, value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IValueMap_get__NewEnum(self: *const T, retVal: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IValueMap.VTable, self.vtable).get__NewEnum(@ptrCast(*const IValueMap, self), retVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IValueMap_get_Description(self: *const T, description: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IValueMap.VTable, self.vtable).get_Description(@ptrCast(*const IValueMap, self), description);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IValueMap_put_Description(self: *const T, description: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IValueMap.VTable, self.vtable).put_Description(@ptrCast(*const IValueMap, self), description);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IValueMap_get_Value(self: *const T, Value: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IValueMap.VTable, self.vtable).get_Value(@ptrCast(*const IValueMap, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IValueMap_put_Value(self: *const T, Value: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IValueMap.VTable, self.vtable).put_Value(@ptrCast(*const IValueMap, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IValueMap_get_ValueMapType(self: *const T, type_: ?*ValueMapType) callconv(.Inline) HRESULT {
return @ptrCast(*const IValueMap.VTable, self.vtable).get_ValueMapType(@ptrCast(*const IValueMap, self), type_);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IValueMap_put_ValueMapType(self: *const T, type_: ValueMapType) callconv(.Inline) HRESULT {
return @ptrCast(*const IValueMap.VTable, self.vtable).put_ValueMapType(@ptrCast(*const IValueMap, self), type_);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IValueMap_Add(self: *const T, value: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IValueMap.VTable, self.vtable).Add(@ptrCast(*const IValueMap, self), value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IValueMap_Remove(self: *const T, value: VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IValueMap.VTable, self.vtable).Remove(@ptrCast(*const IValueMap, self), value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IValueMap_Clear(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IValueMap.VTable, self.vtable).Clear(@ptrCast(*const IValueMap, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IValueMap_AddRange(self: *const T, map: ?*IValueMap) callconv(.Inline) HRESULT {
return @ptrCast(*const IValueMap.VTable, self.vtable).AddRange(@ptrCast(*const IValueMap, self), map);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IValueMap_CreateValueMapItem(self: *const T, Item: ?*?*IValueMapItem) callconv(.Inline) HRESULT {
return @ptrCast(*const IValueMap.VTable, self.vtable).CreateValueMapItem(@ptrCast(*const IValueMap, self), Item);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const PERF_OBJECT_TYPE = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
TotalByteLength: u32,
DefinitionLength: u32,
HeaderLength: u32,
ObjectNameTitleIndex: u32,
ObjectNameTitle: u32,
ObjectHelpTitleIndex: u32,
ObjectHelpTitle: u32,
DetailLevel: u32,
NumCounters: u32,
DefaultCounter: i32,
NumInstances: i32,
CodePage: u32,
PerfTime: LARGE_INTEGER,
PerfFreq: LARGE_INTEGER,
},
.X86 => extern struct {
TotalByteLength: u32,
DefinitionLength: u32,
HeaderLength: u32,
ObjectNameTitleIndex: u32,
ObjectNameTitle: ?PWSTR,
ObjectHelpTitleIndex: u32,
ObjectHelpTitle: ?PWSTR,
DetailLevel: u32,
NumCounters: u32,
DefaultCounter: i32,
NumInstances: i32,
CodePage: u32,
PerfTime: LARGE_INTEGER,
PerfFreq: LARGE_INTEGER,
},
};
pub const PERF_COUNTER_DEFINITION = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
ByteLength: u32,
CounterNameTitleIndex: u32,
CounterNameTitle: u32,
CounterHelpTitleIndex: u32,
CounterHelpTitle: u32,
DefaultScale: i32,
DetailLevel: u32,
CounterType: u32,
CounterSize: u32,
CounterOffset: u32,
},
.X86 => extern struct {
ByteLength: u32,
CounterNameTitleIndex: u32,
CounterNameTitle: ?PWSTR,
CounterHelpTitleIndex: u32,
CounterHelpTitle: ?PWSTR,
DefaultScale: i32,
DetailLevel: u32,
CounterType: u32,
CounterSize: u32,
CounterOffset: u32,
},
};
//--------------------------------------------------------------------------------
// Section: Functions (135)
//--------------------------------------------------------------------------------
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn QueryPerformanceCounter(
lpPerformanceCount: ?*LARGE_INTEGER,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn QueryPerformanceFrequency(
lpFrequency: ?*LARGE_INTEGER,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "loadperf" fn InstallPerfDllW(
szComputerName: ?[*:0]const u16,
lpIniFile: ?[*:0]const u16,
dwFlags: usize,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "loadperf" fn InstallPerfDllA(
szComputerName: ?[*:0]const u8,
lpIniFile: ?[*:0]const u8,
dwFlags: usize,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "loadperf" fn LoadPerfCounterTextStringsA(
lpCommandLine: ?PSTR,
bQuietModeArg: BOOL,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "loadperf" fn LoadPerfCounterTextStringsW(
lpCommandLine: ?PWSTR,
bQuietModeArg: BOOL,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "loadperf" fn UnloadPerfCounterTextStringsW(
lpCommandLine: ?PWSTR,
bQuietModeArg: BOOL,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "loadperf" fn UnloadPerfCounterTextStringsA(
lpCommandLine: ?PSTR,
bQuietModeArg: BOOL,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "loadperf" fn UpdatePerfNameFilesA(
szNewCtrFilePath: ?[*:0]const u8,
szNewHlpFilePath: ?[*:0]const u8,
szLanguageID: ?PSTR,
dwFlags: usize,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "loadperf" fn UpdatePerfNameFilesW(
szNewCtrFilePath: ?[*:0]const u16,
szNewHlpFilePath: ?[*:0]const u16,
szLanguageID: ?PWSTR,
dwFlags: usize,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "loadperf" fn SetServiceAsTrustedA(
szReserved: ?[*:0]const u8,
szServiceName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "loadperf" fn SetServiceAsTrustedW(
szReserved: ?[*:0]const u16,
szServiceName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "loadperf" fn BackupPerfRegistryToFileW(
szFileName: ?[*:0]const u16,
szCommentString: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "loadperf" fn RestorePerfRegistryFromFileW(
szFileName: ?[*:0]const u16,
szLangId: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "ADVAPI32" fn PerfStartProvider(
ProviderGuid: ?*Guid,
ControlCallback: ?PERFLIBREQUEST,
phProvider: ?*PerfProviderHandle,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "ADVAPI32" fn PerfStartProviderEx(
ProviderGuid: ?*Guid,
ProviderContext: ?*PERF_PROVIDER_CONTEXT,
Provider: ?*PerfProviderHandle,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "ADVAPI32" fn PerfStopProvider(
ProviderHandle: PerfProviderHandle,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "ADVAPI32" fn PerfSetCounterSetInfo(
ProviderHandle: ?HANDLE,
// TODO: what to do with BytesParamIndex 2?
Template: ?*PERF_COUNTERSET_INFO,
TemplateSize: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "ADVAPI32" fn PerfCreateInstance(
ProviderHandle: PerfProviderHandle,
CounterSetGuid: ?*const Guid,
Name: ?[*:0]const u16,
Id: u32,
) callconv(@import("std").os.windows.WINAPI) ?*PERF_COUNTERSET_INSTANCE;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "ADVAPI32" fn PerfDeleteInstance(
Provider: PerfProviderHandle,
InstanceBlock: ?*PERF_COUNTERSET_INSTANCE,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "ADVAPI32" fn PerfQueryInstance(
ProviderHandle: ?HANDLE,
CounterSetGuid: ?*const Guid,
Name: ?[*:0]const u16,
Id: u32,
) callconv(@import("std").os.windows.WINAPI) ?*PERF_COUNTERSET_INSTANCE;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "ADVAPI32" fn PerfSetCounterRefValue(
Provider: ?HANDLE,
Instance: ?*PERF_COUNTERSET_INSTANCE,
CounterId: u32,
Address: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "ADVAPI32" fn PerfSetULongCounterValue(
Provider: ?HANDLE,
Instance: ?*PERF_COUNTERSET_INSTANCE,
CounterId: u32,
Value: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "ADVAPI32" fn PerfSetULongLongCounterValue(
Provider: ?HANDLE,
Instance: ?*PERF_COUNTERSET_INSTANCE,
CounterId: u32,
Value: u64,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "ADVAPI32" fn PerfIncrementULongCounterValue(
Provider: ?HANDLE,
Instance: ?*PERF_COUNTERSET_INSTANCE,
CounterId: u32,
Value: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "ADVAPI32" fn PerfIncrementULongLongCounterValue(
Provider: ?HANDLE,
Instance: ?*PERF_COUNTERSET_INSTANCE,
CounterId: u32,
Value: u64,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "ADVAPI32" fn PerfDecrementULongCounterValue(
Provider: ?HANDLE,
Instance: ?*PERF_COUNTERSET_INSTANCE,
CounterId: u32,
Value: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "ADVAPI32" fn PerfDecrementULongLongCounterValue(
Provider: ?HANDLE,
Instance: ?*PERF_COUNTERSET_INSTANCE,
CounterId: u32,
Value: u64,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows10.0.14393'
pub extern "ADVAPI32" fn PerfEnumerateCounterSet(
szMachine: ?[*:0]const u16,
pCounterSetIds: ?[*]Guid,
cCounterSetIds: u32,
pcCounterSetIdsActual: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows10.0.14393'
pub extern "ADVAPI32" fn PerfEnumerateCounterSetInstances(
szMachine: ?[*:0]const u16,
pCounterSetId: ?*const Guid,
// TODO: what to do with BytesParamIndex 3?
pInstances: ?*PERF_INSTANCE_HEADER,
cbInstances: u32,
pcbInstancesActual: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows10.0.14393'
pub extern "ADVAPI32" fn PerfQueryCounterSetRegistrationInfo(
szMachine: ?[*:0]const u16,
pCounterSetId: ?*const Guid,
requestCode: PerfRegInfoType,
requestLangId: u32,
// TODO: what to do with BytesParamIndex 5?
pbRegInfo: ?*u8,
cbRegInfo: u32,
pcbRegInfoActual: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows10.0.14393'
pub extern "ADVAPI32" fn PerfOpenQueryHandle(
szMachine: ?[*:0]const u16,
phQuery: ?*PerfQueryHandle,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows10.0.14393'
pub extern "ADVAPI32" fn PerfCloseQueryHandle(
hQuery: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows10.0.14393'
pub extern "ADVAPI32" fn PerfQueryCounterInfo(
hQuery: PerfQueryHandle,
// TODO: what to do with BytesParamIndex 2?
pCounters: ?*PERF_COUNTER_IDENTIFIER,
cbCounters: u32,
pcbCountersActual: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows10.0.14393'
pub extern "ADVAPI32" fn PerfQueryCounterData(
hQuery: PerfQueryHandle,
// TODO: what to do with BytesParamIndex 2?
pCounterBlock: ?*PERF_DATA_HEADER,
cbCounterBlock: u32,
pcbCounterBlockActual: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows10.0.14393'
pub extern "ADVAPI32" fn PerfAddCounters(
hQuery: PerfQueryHandle,
// TODO: what to do with BytesParamIndex 2?
pCounters: ?*PERF_COUNTER_IDENTIFIER,
cbCounters: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows10.0.14393'
pub extern "ADVAPI32" fn PerfDeleteCounters(
hQuery: PerfQueryHandle,
// TODO: what to do with BytesParamIndex 2?
pCounters: ?*PERF_COUNTER_IDENTIFIER,
cbCounters: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhGetDllVersion(
lpdwVersion: ?*PDH_DLL_VERSION,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhOpenQueryW(
szDataSource: ?[*:0]const u16,
dwUserData: usize,
phQuery: ?*isize,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhOpenQueryA(
szDataSource: ?[*:0]const u8,
dwUserData: usize,
phQuery: ?*isize,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhAddCounterW(
hQuery: isize,
szFullCounterPath: ?[*:0]const u16,
dwUserData: usize,
phCounter: ?*isize,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhAddCounterA(
hQuery: isize,
szFullCounterPath: ?[*:0]const u8,
dwUserData: usize,
phCounter: ?*isize,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "pdh" fn PdhAddEnglishCounterW(
hQuery: isize,
szFullCounterPath: ?[*:0]const u16,
dwUserData: usize,
phCounter: ?*isize,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "pdh" fn PdhAddEnglishCounterA(
hQuery: isize,
szFullCounterPath: ?[*:0]const u8,
dwUserData: usize,
phCounter: ?*isize,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "pdh" fn PdhCollectQueryDataWithTime(
hQuery: isize,
pllTimeStamp: ?*i64,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "pdh" fn PdhValidatePathExW(
hDataSource: isize,
szFullPathBuffer: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "pdh" fn PdhValidatePathExA(
hDataSource: isize,
szFullPathBuffer: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhRemoveCounter(
hCounter: isize,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhCollectQueryData(
hQuery: isize,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhCloseQuery(
hQuery: isize,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhGetFormattedCounterValue(
hCounter: isize,
dwFormat: PDH_FMT,
lpdwType: ?*u32,
pValue: ?*PDH_FMT_COUNTERVALUE,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhGetFormattedCounterArrayA(
hCounter: isize,
dwFormat: PDH_FMT,
lpdwBufferSize: ?*u32,
lpdwItemCount: ?*u32,
ItemBuffer: ?*PDH_FMT_COUNTERVALUE_ITEM_A,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhGetFormattedCounterArrayW(
hCounter: isize,
dwFormat: PDH_FMT,
lpdwBufferSize: ?*u32,
lpdwItemCount: ?*u32,
ItemBuffer: ?*PDH_FMT_COUNTERVALUE_ITEM_W,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhGetRawCounterValue(
hCounter: isize,
lpdwType: ?*u32,
pValue: ?*PDH_RAW_COUNTER,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhGetRawCounterArrayA(
hCounter: isize,
lpdwBufferSize: ?*u32,
lpdwItemCount: ?*u32,
ItemBuffer: ?*PDH_RAW_COUNTER_ITEM_A,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhGetRawCounterArrayW(
hCounter: isize,
lpdwBufferSize: ?*u32,
lpdwItemCount: ?*u32,
ItemBuffer: ?*PDH_RAW_COUNTER_ITEM_W,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhCalculateCounterFromRawValue(
hCounter: isize,
dwFormat: PDH_FMT,
rawValue1: ?*PDH_RAW_COUNTER,
rawValue2: ?*PDH_RAW_COUNTER,
fmtValue: ?*PDH_FMT_COUNTERVALUE,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhComputeCounterStatistics(
hCounter: isize,
dwFormat: PDH_FMT,
dwFirstEntry: u32,
dwNumEntries: u32,
lpRawValueArray: ?*PDH_RAW_COUNTER,
data: ?*PDH_STATISTICS,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhGetCounterInfoW(
hCounter: isize,
bRetrieveExplainText: BOOLEAN,
pdwBufferSize: ?*u32,
lpBuffer: ?*PDH_COUNTER_INFO_W,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhGetCounterInfoA(
hCounter: isize,
bRetrieveExplainText: BOOLEAN,
pdwBufferSize: ?*u32,
lpBuffer: ?*PDH_COUNTER_INFO_A,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhSetCounterScaleFactor(
hCounter: isize,
lFactor: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhConnectMachineW(
szMachineName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhConnectMachineA(
szMachineName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhEnumMachinesW(
szDataSource: ?[*:0]const u16,
mszMachineList: ?[*]u16,
pcchBufferSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhEnumMachinesA(
szDataSource: ?[*:0]const u8,
mszMachineList: ?[*]u8,
pcchBufferSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhEnumObjectsW(
szDataSource: ?[*:0]const u16,
szMachineName: ?[*:0]const u16,
mszObjectList: ?[*]u16,
pcchBufferSize: ?*u32,
dwDetailLevel: PERF_DETAIL,
bRefresh: BOOL,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhEnumObjectsA(
szDataSource: ?[*:0]const u8,
szMachineName: ?[*:0]const u8,
mszObjectList: ?[*]u8,
pcchBufferSize: ?*u32,
dwDetailLevel: PERF_DETAIL,
bRefresh: BOOL,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhEnumObjectItemsW(
szDataSource: ?[*:0]const u16,
szMachineName: ?[*:0]const u16,
szObjectName: ?[*:0]const u16,
mszCounterList: ?[*]u16,
pcchCounterListLength: ?*u32,
mszInstanceList: ?[*]u16,
pcchInstanceListLength: ?*u32,
dwDetailLevel: PERF_DETAIL,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhEnumObjectItemsA(
szDataSource: ?[*:0]const u8,
szMachineName: ?[*:0]const u8,
szObjectName: ?[*:0]const u8,
mszCounterList: ?[*]u8,
pcchCounterListLength: ?*u32,
mszInstanceList: ?[*]u8,
pcchInstanceListLength: ?*u32,
dwDetailLevel: PERF_DETAIL,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhMakeCounterPathW(
pCounterPathElements: ?*PDH_COUNTER_PATH_ELEMENTS_W,
szFullPathBuffer: ?PWSTR,
pcchBufferSize: ?*u32,
dwFlags: PDH_PATH_FLAGS,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhMakeCounterPathA(
pCounterPathElements: ?*PDH_COUNTER_PATH_ELEMENTS_A,
szFullPathBuffer: ?PSTR,
pcchBufferSize: ?*u32,
dwFlags: PDH_PATH_FLAGS,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhParseCounterPathW(
szFullPathBuffer: ?[*:0]const u16,
pCounterPathElements: ?*PDH_COUNTER_PATH_ELEMENTS_W,
pdwBufferSize: ?*u32,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhParseCounterPathA(
szFullPathBuffer: ?[*:0]const u8,
pCounterPathElements: ?*PDH_COUNTER_PATH_ELEMENTS_A,
pdwBufferSize: ?*u32,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhParseInstanceNameW(
szInstanceString: ?[*:0]const u16,
szInstanceName: ?PWSTR,
pcchInstanceNameLength: ?*u32,
szParentName: ?PWSTR,
pcchParentNameLength: ?*u32,
lpIndex: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhParseInstanceNameA(
szInstanceString: ?[*:0]const u8,
szInstanceName: ?PSTR,
pcchInstanceNameLength: ?*u32,
szParentName: ?PSTR,
pcchParentNameLength: ?*u32,
lpIndex: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhValidatePathW(
szFullPathBuffer: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhValidatePathA(
szFullPathBuffer: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhGetDefaultPerfObjectW(
szDataSource: ?[*:0]const u16,
szMachineName: ?[*:0]const u16,
szDefaultObjectName: ?PWSTR,
pcchBufferSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhGetDefaultPerfObjectA(
szDataSource: ?[*:0]const u8,
szMachineName: ?[*:0]const u8,
szDefaultObjectName: ?PSTR,
pcchBufferSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhGetDefaultPerfCounterW(
szDataSource: ?[*:0]const u16,
szMachineName: ?[*:0]const u16,
szObjectName: ?[*:0]const u16,
szDefaultCounterName: ?PWSTR,
pcchBufferSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhGetDefaultPerfCounterA(
szDataSource: ?[*:0]const u8,
szMachineName: ?[*:0]const u8,
szObjectName: ?[*:0]const u8,
szDefaultCounterName: ?PSTR,
pcchBufferSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhBrowseCountersW(
pBrowseDlgData: ?*PDH_BROWSE_DLG_CONFIG_W,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhBrowseCountersA(
pBrowseDlgData: ?*PDH_BROWSE_DLG_CONFIG_A,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhExpandCounterPathW(
szWildCardPath: ?[*:0]const u16,
mszExpandedPathList: ?[*]u16,
pcchPathListLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhExpandCounterPathA(
szWildCardPath: ?[*:0]const u8,
mszExpandedPathList: ?[*]u8,
pcchPathListLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhLookupPerfNameByIndexW(
szMachineName: ?[*:0]const u16,
dwNameIndex: u32,
szNameBuffer: ?PWSTR,
pcchNameBufferSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhLookupPerfNameByIndexA(
szMachineName: ?[*:0]const u8,
dwNameIndex: u32,
szNameBuffer: ?PSTR,
pcchNameBufferSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhLookupPerfIndexByNameW(
szMachineName: ?[*:0]const u16,
szNameBuffer: ?[*:0]const u16,
pdwIndex: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhLookupPerfIndexByNameA(
szMachineName: ?[*:0]const u8,
szNameBuffer: ?[*:0]const u8,
pdwIndex: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhExpandWildCardPathA(
szDataSource: ?[*:0]const u8,
szWildCardPath: ?[*:0]const u8,
mszExpandedPathList: ?[*]u8,
pcchPathListLength: ?*u32,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhExpandWildCardPathW(
szDataSource: ?[*:0]const u16,
szWildCardPath: ?[*:0]const u16,
mszExpandedPathList: ?[*]u16,
pcchPathListLength: ?*u32,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhOpenLogW(
szLogFileName: ?[*:0]const u16,
dwAccessFlags: PDH_LOG,
lpdwLogType: ?*PDH_LOG_TYPE,
hQuery: isize,
dwMaxSize: u32,
szUserCaption: ?[*:0]const u16,
phLog: ?*isize,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhOpenLogA(
szLogFileName: ?[*:0]const u8,
dwAccessFlags: PDH_LOG,
lpdwLogType: ?*PDH_LOG_TYPE,
hQuery: isize,
dwMaxSize: u32,
szUserCaption: ?[*:0]const u8,
phLog: ?*isize,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhUpdateLogW(
hLog: isize,
szUserString: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhUpdateLogA(
hLog: isize,
szUserString: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhUpdateLogFileCatalog(
hLog: isize,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhGetLogFileSize(
hLog: isize,
llSize: ?*i64,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhCloseLog(
hLog: isize,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhSelectDataSourceW(
hWndOwner: ?HWND,
dwFlags: PDH_SELECT_DATA_SOURCE_FLAGS,
szDataSource: ?PWSTR,
pcchBufferLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhSelectDataSourceA(
hWndOwner: ?HWND,
dwFlags: PDH_SELECT_DATA_SOURCE_FLAGS,
szDataSource: ?PSTR,
pcchBufferLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhIsRealTimeQuery(
hQuery: isize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhSetQueryTimeRange(
hQuery: isize,
pInfo: ?*PDH_TIME_INFO,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhGetDataSourceTimeRangeW(
szDataSource: ?[*:0]const u16,
pdwNumEntries: ?*u32,
pInfo: ?*PDH_TIME_INFO,
pdwBufferSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhGetDataSourceTimeRangeA(
szDataSource: ?[*:0]const u8,
pdwNumEntries: ?*u32,
pInfo: ?*PDH_TIME_INFO,
pdwBufferSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhCollectQueryDataEx(
hQuery: isize,
dwIntervalTime: u32,
hNewDataEvent: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhFormatFromRawValue(
dwCounterType: u32,
dwFormat: PDH_FMT,
pTimeBase: ?*i64,
pRawValue1: ?*PDH_RAW_COUNTER,
pRawValue2: ?*PDH_RAW_COUNTER,
pFmtValue: ?*PDH_FMT_COUNTERVALUE,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhGetCounterTimeBase(
hCounter: isize,
pTimeBase: ?*i64,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhReadRawLogRecord(
hLog: isize,
ftRecord: FILETIME,
pRawLogRecord: ?*PDH_RAW_LOG_RECORD,
pdwBufferLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhSetDefaultRealTimeDataSource(
dwDataSourceId: REAL_TIME_DATA_SOURCE_ID_FLAGS,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhBindInputDataSourceW(
phDataSource: ?*isize,
LogFileNameList: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhBindInputDataSourceA(
phDataSource: ?*isize,
LogFileNameList: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhOpenQueryH(
hDataSource: isize,
dwUserData: usize,
phQuery: ?*isize,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhEnumMachinesHW(
hDataSource: isize,
mszMachineList: ?[*]u16,
pcchBufferSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhEnumMachinesHA(
hDataSource: isize,
mszMachineList: ?[*]u8,
pcchBufferSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhEnumObjectsHW(
hDataSource: isize,
szMachineName: ?[*:0]const u16,
mszObjectList: ?[*]u16,
pcchBufferSize: ?*u32,
dwDetailLevel: PERF_DETAIL,
bRefresh: BOOL,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhEnumObjectsHA(
hDataSource: isize,
szMachineName: ?[*:0]const u8,
mszObjectList: ?[*]u8,
pcchBufferSize: ?*u32,
dwDetailLevel: PERF_DETAIL,
bRefresh: BOOL,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhEnumObjectItemsHW(
hDataSource: isize,
szMachineName: ?[*:0]const u16,
szObjectName: ?[*:0]const u16,
mszCounterList: ?[*]u16,
pcchCounterListLength: ?*u32,
mszInstanceList: ?[*]u16,
pcchInstanceListLength: ?*u32,
dwDetailLevel: PERF_DETAIL,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhEnumObjectItemsHA(
hDataSource: isize,
szMachineName: ?[*:0]const u8,
szObjectName: ?[*:0]const u8,
mszCounterList: ?[*]u8,
pcchCounterListLength: ?*u32,
mszInstanceList: ?[*]u8,
pcchInstanceListLength: ?*u32,
dwDetailLevel: PERF_DETAIL,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhExpandWildCardPathHW(
hDataSource: isize,
szWildCardPath: ?[*:0]const u16,
mszExpandedPathList: ?[*]u16,
pcchPathListLength: ?*u32,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhExpandWildCardPathHA(
hDataSource: isize,
szWildCardPath: ?[*:0]const u8,
mszExpandedPathList: ?[*]u8,
pcchPathListLength: ?*u32,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhGetDataSourceTimeRangeH(
hDataSource: isize,
pdwNumEntries: ?*u32,
pInfo: ?*PDH_TIME_INFO,
pdwBufferSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhGetDefaultPerfObjectHW(
hDataSource: isize,
szMachineName: ?[*:0]const u16,
szDefaultObjectName: ?PWSTR,
pcchBufferSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhGetDefaultPerfObjectHA(
hDataSource: isize,
szMachineName: ?[*:0]const u8,
szDefaultObjectName: ?PSTR,
pcchBufferSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhGetDefaultPerfCounterHW(
hDataSource: isize,
szMachineName: ?[*:0]const u16,
szObjectName: ?[*:0]const u16,
szDefaultCounterName: ?PWSTR,
pcchBufferSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhGetDefaultPerfCounterHA(
hDataSource: isize,
szMachineName: ?[*:0]const u8,
szObjectName: ?[*:0]const u8,
szDefaultCounterName: ?PSTR,
pcchBufferSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhBrowseCountersHW(
pBrowseDlgData: ?*PDH_BROWSE_DLG_CONFIG_HW,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhBrowseCountersHA(
pBrowseDlgData: ?*PDH_BROWSE_DLG_CONFIG_HA,
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "pdh" fn PdhVerifySQLDBW(
szDataSource: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "pdh" fn PdhVerifySQLDBA(
szDataSource: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "pdh" fn PdhCreateSQLTablesW(
szDataSource: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "pdh" fn PdhCreateSQLTablesA(
szDataSource: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhEnumLogSetNamesW(
szDataSource: ?[*:0]const u16,
mszDataSetNameList: ?[*]u16,
pcchBufferLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "pdh" fn PdhEnumLogSetNamesA(
szDataSource: ?[*:0]const u8,
mszDataSetNameList: ?[*]u8,
pcchBufferLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "pdh" fn PdhGetLogSetGUID(
hLog: isize,
pGuid: ?*Guid,
pRunId: ?*i32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "pdh" fn PdhSetLogSetRunID(
hLog: isize,
RunId: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (50)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
pub const PDH_RAW_COUNTER_ITEM_ = thismodule.PDH_RAW_COUNTER_ITEM_A;
pub const PDH_FMT_COUNTERVALUE_ITEM_ = thismodule.PDH_FMT_COUNTERVALUE_ITEM_A;
pub const PDH_COUNTER_PATH_ELEMENTS_ = thismodule.PDH_COUNTER_PATH_ELEMENTS_A;
pub const PDH_DATA_ITEM_PATH_ELEMENTS_ = thismodule.PDH_DATA_ITEM_PATH_ELEMENTS_A;
pub const PDH_COUNTER_INFO_ = thismodule.PDH_COUNTER_INFO_A;
pub const PDH_LOG_SERVICE_QUERY_INFO_ = thismodule.PDH_LOG_SERVICE_QUERY_INFO_A;
pub const PDH_BROWSE_DLG_CONFIG_H = thismodule.PDH_BROWSE_DLG_CONFIG_HA;
pub const PDH_BROWSE_DLG_CONFIG_ = thismodule.PDH_BROWSE_DLG_CONFIG_A;
pub const InstallPerfDll = thismodule.InstallPerfDllA;
pub const LoadPerfCounterTextStrings = thismodule.LoadPerfCounterTextStringsA;
pub const UnloadPerfCounterTextStrings = thismodule.UnloadPerfCounterTextStringsA;
pub const UpdatePerfNameFiles = thismodule.UpdatePerfNameFilesA;
pub const SetServiceAsTrusted = thismodule.SetServiceAsTrustedA;
pub const PdhOpenQuery = thismodule.PdhOpenQueryA;
pub const PdhAddCounter = thismodule.PdhAddCounterA;
pub const PdhAddEnglishCounter = thismodule.PdhAddEnglishCounterA;
pub const PdhValidatePathEx = thismodule.PdhValidatePathExA;
pub const PdhGetFormattedCounterArray = thismodule.PdhGetFormattedCounterArrayA;
pub const PdhGetRawCounterArray = thismodule.PdhGetRawCounterArrayA;
pub const PdhGetCounterInfo = thismodule.PdhGetCounterInfoA;
pub const PdhConnectMachine = thismodule.PdhConnectMachineA;
pub const PdhEnumMachines = thismodule.PdhEnumMachinesA;
pub const PdhEnumObjects = thismodule.PdhEnumObjectsA;
pub const PdhEnumObjectItems = thismodule.PdhEnumObjectItemsA;
pub const PdhMakeCounterPath = thismodule.PdhMakeCounterPathA;
pub const PdhParseCounterPath = thismodule.PdhParseCounterPathA;
pub const PdhParseInstanceName = thismodule.PdhParseInstanceNameA;
pub const PdhValidatePath = thismodule.PdhValidatePathA;
pub const PdhGetDefaultPerfObject = thismodule.PdhGetDefaultPerfObjectA;
pub const PdhGetDefaultPerfCounter = thismodule.PdhGetDefaultPerfCounterA;
pub const PdhBrowseCounters = thismodule.PdhBrowseCountersA;
pub const PdhExpandCounterPath = thismodule.PdhExpandCounterPathA;
pub const PdhLookupPerfNameByIndex = thismodule.PdhLookupPerfNameByIndexA;
pub const PdhLookupPerfIndexByName = thismodule.PdhLookupPerfIndexByNameA;
pub const PdhExpandWildCardPath = thismodule.PdhExpandWildCardPathA;
pub const PdhOpenLog = thismodule.PdhOpenLogA;
pub const PdhUpdateLog = thismodule.PdhUpdateLogA;
pub const PdhSelectDataSource = thismodule.PdhSelectDataSourceA;
pub const PdhGetDataSourceTimeRange = thismodule.PdhGetDataSourceTimeRangeA;
pub const PdhBindInputDataSource = thismodule.PdhBindInputDataSourceA;
pub const PdhEnumMachinesH = thismodule.PdhEnumMachinesHA;
pub const PdhEnumObjectsH = thismodule.PdhEnumObjectsHA;
pub const PdhEnumObjectItemsH = thismodule.PdhEnumObjectItemsHA;
pub const PdhExpandWildCardPathH = thismodule.PdhExpandWildCardPathHA;
pub const PdhGetDefaultPerfObjectH = thismodule.PdhGetDefaultPerfObjectHA;
pub const PdhGetDefaultPerfCounterH = thismodule.PdhGetDefaultPerfCounterHA;
pub const PdhBrowseCountersH = thismodule.PdhBrowseCountersHA;
pub const PdhVerifySQLDB = thismodule.PdhVerifySQLDBA;
pub const PdhCreateSQLTables = thismodule.PdhCreateSQLTablesA;
pub const PdhEnumLogSetNames = thismodule.PdhEnumLogSetNamesA;
},
.wide => struct {
pub const PDH_RAW_COUNTER_ITEM_ = thismodule.PDH_RAW_COUNTER_ITEM_W;
pub const PDH_FMT_COUNTERVALUE_ITEM_ = thismodule.PDH_FMT_COUNTERVALUE_ITEM_W;
pub const PDH_COUNTER_PATH_ELEMENTS_ = thismodule.PDH_COUNTER_PATH_ELEMENTS_W;
pub const PDH_DATA_ITEM_PATH_ELEMENTS_ = thismodule.PDH_DATA_ITEM_PATH_ELEMENTS_W;
pub const PDH_COUNTER_INFO_ = thismodule.PDH_COUNTER_INFO_W;
pub const PDH_LOG_SERVICE_QUERY_INFO_ = thismodule.PDH_LOG_SERVICE_QUERY_INFO_W;
pub const PDH_BROWSE_DLG_CONFIG_H = thismodule.PDH_BROWSE_DLG_CONFIG_HW;
pub const PDH_BROWSE_DLG_CONFIG_ = thismodule.PDH_BROWSE_DLG_CONFIG_W;
pub const InstallPerfDll = thismodule.InstallPerfDllW;
pub const LoadPerfCounterTextStrings = thismodule.LoadPerfCounterTextStringsW;
pub const UnloadPerfCounterTextStrings = thismodule.UnloadPerfCounterTextStringsW;
pub const UpdatePerfNameFiles = thismodule.UpdatePerfNameFilesW;
pub const SetServiceAsTrusted = thismodule.SetServiceAsTrustedW;
pub const PdhOpenQuery = thismodule.PdhOpenQueryW;
pub const PdhAddCounter = thismodule.PdhAddCounterW;
pub const PdhAddEnglishCounter = thismodule.PdhAddEnglishCounterW;
pub const PdhValidatePathEx = thismodule.PdhValidatePathExW;
pub const PdhGetFormattedCounterArray = thismodule.PdhGetFormattedCounterArrayW;
pub const PdhGetRawCounterArray = thismodule.PdhGetRawCounterArrayW;
pub const PdhGetCounterInfo = thismodule.PdhGetCounterInfoW;
pub const PdhConnectMachine = thismodule.PdhConnectMachineW;
pub const PdhEnumMachines = thismodule.PdhEnumMachinesW;
pub const PdhEnumObjects = thismodule.PdhEnumObjectsW;
pub const PdhEnumObjectItems = thismodule.PdhEnumObjectItemsW;
pub const PdhMakeCounterPath = thismodule.PdhMakeCounterPathW;
pub const PdhParseCounterPath = thismodule.PdhParseCounterPathW;
pub const PdhParseInstanceName = thismodule.PdhParseInstanceNameW;
pub const PdhValidatePath = thismodule.PdhValidatePathW;
pub const PdhGetDefaultPerfObject = thismodule.PdhGetDefaultPerfObjectW;
pub const PdhGetDefaultPerfCounter = thismodule.PdhGetDefaultPerfCounterW;
pub const PdhBrowseCounters = thismodule.PdhBrowseCountersW;
pub const PdhExpandCounterPath = thismodule.PdhExpandCounterPathW;
pub const PdhLookupPerfNameByIndex = thismodule.PdhLookupPerfNameByIndexW;
pub const PdhLookupPerfIndexByName = thismodule.PdhLookupPerfIndexByNameW;
pub const PdhExpandWildCardPath = thismodule.PdhExpandWildCardPathW;
pub const PdhOpenLog = thismodule.PdhOpenLogW;
pub const PdhUpdateLog = thismodule.PdhUpdateLogW;
pub const PdhSelectDataSource = thismodule.PdhSelectDataSourceW;
pub const PdhGetDataSourceTimeRange = thismodule.PdhGetDataSourceTimeRangeW;
pub const PdhBindInputDataSource = thismodule.PdhBindInputDataSourceW;
pub const PdhEnumMachinesH = thismodule.PdhEnumMachinesHW;
pub const PdhEnumObjectsH = thismodule.PdhEnumObjectsHW;
pub const PdhEnumObjectItemsH = thismodule.PdhEnumObjectItemsHW;
pub const PdhExpandWildCardPathH = thismodule.PdhExpandWildCardPathHW;
pub const PdhGetDefaultPerfObjectH = thismodule.PdhGetDefaultPerfObjectHW;
pub const PdhGetDefaultPerfCounterH = thismodule.PdhGetDefaultPerfCounterHW;
pub const PdhBrowseCountersH = thismodule.PdhBrowseCountersHW;
pub const PdhVerifySQLDB = thismodule.PdhVerifySQLDBW;
pub const PdhCreateSQLTables = thismodule.PdhCreateSQLTablesW;
pub const PdhEnumLogSetNames = thismodule.PdhEnumLogSetNamesW;
},
.unspecified => if (@import("builtin").is_test) struct {
pub const PDH_RAW_COUNTER_ITEM_ = *opaque{};
pub const PDH_FMT_COUNTERVALUE_ITEM_ = *opaque{};
pub const PDH_COUNTER_PATH_ELEMENTS_ = *opaque{};
pub const PDH_DATA_ITEM_PATH_ELEMENTS_ = *opaque{};
pub const PDH_COUNTER_INFO_ = *opaque{};
pub const PDH_LOG_SERVICE_QUERY_INFO_ = *opaque{};
pub const PDH_BROWSE_DLG_CONFIG_H = *opaque{};
pub const PDH_BROWSE_DLG_CONFIG_ = *opaque{};
pub const InstallPerfDll = *opaque{};
pub const LoadPerfCounterTextStrings = *opaque{};
pub const UnloadPerfCounterTextStrings = *opaque{};
pub const UpdatePerfNameFiles = *opaque{};
pub const SetServiceAsTrusted = *opaque{};
pub const PdhOpenQuery = *opaque{};
pub const PdhAddCounter = *opaque{};
pub const PdhAddEnglishCounter = *opaque{};
pub const PdhValidatePathEx = *opaque{};
pub const PdhGetFormattedCounterArray = *opaque{};
pub const PdhGetRawCounterArray = *opaque{};
pub const PdhGetCounterInfo = *opaque{};
pub const PdhConnectMachine = *opaque{};
pub const PdhEnumMachines = *opaque{};
pub const PdhEnumObjects = *opaque{};
pub const PdhEnumObjectItems = *opaque{};
pub const PdhMakeCounterPath = *opaque{};
pub const PdhParseCounterPath = *opaque{};
pub const PdhParseInstanceName = *opaque{};
pub const PdhValidatePath = *opaque{};
pub const PdhGetDefaultPerfObject = *opaque{};
pub const PdhGetDefaultPerfCounter = *opaque{};
pub const PdhBrowseCounters = *opaque{};
pub const PdhExpandCounterPath = *opaque{};
pub const PdhLookupPerfNameByIndex = *opaque{};
pub const PdhLookupPerfIndexByName = *opaque{};
pub const PdhExpandWildCardPath = *opaque{};
pub const PdhOpenLog = *opaque{};
pub const PdhUpdateLog = *opaque{};
pub const PdhSelectDataSource = *opaque{};
pub const PdhGetDataSourceTimeRange = *opaque{};
pub const PdhBindInputDataSource = *opaque{};
pub const PdhEnumMachinesH = *opaque{};
pub const PdhEnumObjectsH = *opaque{};
pub const PdhEnumObjectItemsH = *opaque{};
pub const PdhExpandWildCardPathH = *opaque{};
pub const PdhGetDefaultPerfObjectH = *opaque{};
pub const PdhGetDefaultPerfCounterH = *opaque{};
pub const PdhBrowseCountersH = *opaque{};
pub const PdhVerifySQLDB = *opaque{};
pub const PdhCreateSQLTables = *opaque{};
pub const PdhEnumLogSetNames = *opaque{};
} else struct {
pub const PDH_RAW_COUNTER_ITEM_ = @compileError("'PDH_RAW_COUNTER_ITEM_' requires that UNICODE be set to true or false in the root module");
pub const PDH_FMT_COUNTERVALUE_ITEM_ = @compileError("'PDH_FMT_COUNTERVALUE_ITEM_' requires that UNICODE be set to true or false in the root module");
pub const PDH_COUNTER_PATH_ELEMENTS_ = @compileError("'PDH_COUNTER_PATH_ELEMENTS_' requires that UNICODE be set to true or false in the root module");
pub const PDH_DATA_ITEM_PATH_ELEMENTS_ = @compileError("'PDH_DATA_ITEM_PATH_ELEMENTS_' requires that UNICODE be set to true or false in the root module");
pub const PDH_COUNTER_INFO_ = @compileError("'PDH_COUNTER_INFO_' requires that UNICODE be set to true or false in the root module");
pub const PDH_LOG_SERVICE_QUERY_INFO_ = @compileError("'PDH_LOG_SERVICE_QUERY_INFO_' requires that UNICODE be set to true or false in the root module");
pub const PDH_BROWSE_DLG_CONFIG_H = @compileError("'PDH_BROWSE_DLG_CONFIG_H' requires that UNICODE be set to true or false in the root module");
pub const PDH_BROWSE_DLG_CONFIG_ = @compileError("'PDH_BROWSE_DLG_CONFIG_' requires that UNICODE be set to true or false in the root module");
pub const InstallPerfDll = @compileError("'InstallPerfDll' requires that UNICODE be set to true or false in the root module");
pub const LoadPerfCounterTextStrings = @compileError("'LoadPerfCounterTextStrings' requires that UNICODE be set to true or false in the root module");
pub const UnloadPerfCounterTextStrings = @compileError("'UnloadPerfCounterTextStrings' requires that UNICODE be set to true or false in the root module");
pub const UpdatePerfNameFiles = @compileError("'UpdatePerfNameFiles' requires that UNICODE be set to true or false in the root module");
pub const SetServiceAsTrusted = @compileError("'SetServiceAsTrusted' requires that UNICODE be set to true or false in the root module");
pub const PdhOpenQuery = @compileError("'PdhOpenQuery' requires that UNICODE be set to true or false in the root module");
pub const PdhAddCounter = @compileError("'PdhAddCounter' requires that UNICODE be set to true or false in the root module");
pub const PdhAddEnglishCounter = @compileError("'PdhAddEnglishCounter' requires that UNICODE be set to true or false in the root module");
pub const PdhValidatePathEx = @compileError("'PdhValidatePathEx' requires that UNICODE be set to true or false in the root module");
pub const PdhGetFormattedCounterArray = @compileError("'PdhGetFormattedCounterArray' requires that UNICODE be set to true or false in the root module");
pub const PdhGetRawCounterArray = @compileError("'PdhGetRawCounterArray' requires that UNICODE be set to true or false in the root module");
pub const PdhGetCounterInfo = @compileError("'PdhGetCounterInfo' requires that UNICODE be set to true or false in the root module");
pub const PdhConnectMachine = @compileError("'PdhConnectMachine' requires that UNICODE be set to true or false in the root module");
pub const PdhEnumMachines = @compileError("'PdhEnumMachines' requires that UNICODE be set to true or false in the root module");
pub const PdhEnumObjects = @compileError("'PdhEnumObjects' requires that UNICODE be set to true or false in the root module");
pub const PdhEnumObjectItems = @compileError("'PdhEnumObjectItems' requires that UNICODE be set to true or false in the root module");
pub const PdhMakeCounterPath = @compileError("'PdhMakeCounterPath' requires that UNICODE be set to true or false in the root module");
pub const PdhParseCounterPath = @compileError("'PdhParseCounterPath' requires that UNICODE be set to true or false in the root module");
pub const PdhParseInstanceName = @compileError("'PdhParseInstanceName' requires that UNICODE be set to true or false in the root module");
pub const PdhValidatePath = @compileError("'PdhValidatePath' requires that UNICODE be set to true or false in the root module");
pub const PdhGetDefaultPerfObject = @compileError("'PdhGetDefaultPerfObject' requires that UNICODE be set to true or false in the root module");
pub const PdhGetDefaultPerfCounter = @compileError("'PdhGetDefaultPerfCounter' requires that UNICODE be set to true or false in the root module");
pub const PdhBrowseCounters = @compileError("'PdhBrowseCounters' requires that UNICODE be set to true or false in the root module");
pub const PdhExpandCounterPath = @compileError("'PdhExpandCounterPath' requires that UNICODE be set to true or false in the root module");
pub const PdhLookupPerfNameByIndex = @compileError("'PdhLookupPerfNameByIndex' requires that UNICODE be set to true or false in the root module");
pub const PdhLookupPerfIndexByName = @compileError("'PdhLookupPerfIndexByName' requires that UNICODE be set to true or false in the root module");
pub const PdhExpandWildCardPath = @compileError("'PdhExpandWildCardPath' requires that UNICODE be set to true or false in the root module");
pub const PdhOpenLog = @compileError("'PdhOpenLog' requires that UNICODE be set to true or false in the root module");
pub const PdhUpdateLog = @compileError("'PdhUpdateLog' requires that UNICODE be set to true or false in the root module");
pub const PdhSelectDataSource = @compileError("'PdhSelectDataSource' requires that UNICODE be set to true or false in the root module");
pub const PdhGetDataSourceTimeRange = @compileError("'PdhGetDataSourceTimeRange' requires that UNICODE be set to true or false in the root module");
pub const PdhBindInputDataSource = @compileError("'PdhBindInputDataSource' requires that UNICODE be set to true or false in the root module");
pub const PdhEnumMachinesH = @compileError("'PdhEnumMachinesH' requires that UNICODE be set to true or false in the root module");
pub const PdhEnumObjectsH = @compileError("'PdhEnumObjectsH' requires that UNICODE be set to true or false in the root module");
pub const PdhEnumObjectItemsH = @compileError("'PdhEnumObjectItemsH' requires that UNICODE be set to true or false in the root module");
pub const PdhExpandWildCardPathH = @compileError("'PdhExpandWildCardPathH' requires that UNICODE be set to true or false in the root module");
pub const PdhGetDefaultPerfObjectH = @compileError("'PdhGetDefaultPerfObjectH' requires that UNICODE be set to true or false in the root module");
pub const PdhGetDefaultPerfCounterH = @compileError("'PdhGetDefaultPerfCounterH' requires that UNICODE be set to true or false in the root module");
pub const PdhBrowseCountersH = @compileError("'PdhBrowseCountersH' requires that UNICODE be set to true or false in the root module");
pub const PdhVerifySQLDB = @compileError("'PdhVerifySQLDB' requires that UNICODE be set to true or false in the root module");
pub const PdhCreateSQLTables = @compileError("'PdhCreateSQLTables' requires that UNICODE be set to true or false in the root module");
pub const PdhEnumLogSetNames = @compileError("'PdhEnumLogSetNames' requires that UNICODE be set to true or false in the root module");
},
};
//--------------------------------------------------------------------------------
// Section: Imports (16)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const BOOL = @import("../foundation.zig").BOOL;
const BOOLEAN = @import("../foundation.zig").BOOLEAN;
const BSTR = @import("../foundation.zig").BSTR;
const FILETIME = @import("../foundation.zig").FILETIME;
const HANDLE = @import("../foundation.zig").HANDLE;
const HRESULT = @import("../foundation.zig").HRESULT;
const HWND = @import("../foundation.zig").HWND;
const IDispatch = @import("../system/ole_automation.zig").IDispatch;
const IUnknown = @import("../system/com.zig").IUnknown;
const LARGE_INTEGER = @import("../system/system_services.zig").LARGE_INTEGER;
const PSTR = @import("../foundation.zig").PSTR;
const PWSTR = @import("../foundation.zig").PWSTR;
const SAFEARRAY = @import("../system/ole_automation.zig").SAFEARRAY;
const SYSTEMTIME = @import("../foundation.zig").SYSTEMTIME;
const VARIANT = @import("../system/ole_automation.zig").VARIANT;
test {
// The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476
if (@hasDecl(@This(), "PERFLIBREQUEST")) { _ = PERFLIBREQUEST; }
if (@hasDecl(@This(), "PERF_MEM_ALLOC")) { _ = PERF_MEM_ALLOC; }
if (@hasDecl(@This(), "PERF_MEM_FREE")) { _ = PERF_MEM_FREE; }
if (@hasDecl(@This(), "PM_OPEN_PROC")) { _ = PM_OPEN_PROC; }
if (@hasDecl(@This(), "PM_COLLECT_PROC")) { _ = PM_COLLECT_PROC; }
if (@hasDecl(@This(), "PM_CLOSE_PROC")) { _ = PM_CLOSE_PROC; }
if (@hasDecl(@This(), "PM_QUERY_PROC")) { _ = PM_QUERY_PROC; }
if (@hasDecl(@This(), "CounterPathCallBack")) { _ = CounterPathCallBack; }
if (@hasDecl(@This(), "PLA_CABEXTRACT_CALLBACK")) { _ = PLA_CABEXTRACT_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;
}
}
}
//--------------------------------------------------------------------------------
// Section: SubModules (1)
//--------------------------------------------------------------------------------
pub const hardware_counter_profiling = @import("performance/hardware_counter_profiling.zig"); | deps/zigwin32/win32/system/performance.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 zigstr = @import("zigstr");
test "Zigstr README tests" {
var allocator = std.testing.allocator;
var str = try zigstr.fromBytes(std.testing.allocator, "Héllo");
defer str.deinit();
// Byte count.
try expectEqual(@as(usize, 6), str.byteCount());
// Code point iteration.
var cp_iter = str.codePointIter();
var want = [_]u21{ 'H', 0x00E9, 'l', 'l', 'o' };
var i: usize = 0;
while (cp_iter.next()) |cp| : (i += 1) {
try expectEqual(want[i], cp.scalar);
}
// Code point count.
try expectEqual(@as(usize, 5), try str.codePointCount());
// Collect all code points at once.
const code_points = try str.codePoints(allocator);
defer allocator.free(code_points);
for (code_points) |cp, j| {
try expectEqual(want[j], cp);
}
// Grapheme cluster iteration.
var giter = try str.graphemeIter();
const gc_want = [_][]const u8{ "H", "é", "l", "l", "o" };
i = 0;
while (giter.next()) |gc| : (i += 1) {
try expect(gc.eql(gc_want[i]));
}
// Collect all grapheme clusters at once.
try expectEqual(@as(usize, 5), try str.graphemeCount());
const gcs = try str.graphemes(allocator);
defer allocator.free(gcs);
for (gcs) |gc, j| {
try expect(gc.eql(gc_want[j]));
}
// Grapheme count.
try expectEqual(@as(usize, 5), try str.graphemeCount());
// Indexing (with negative indexes too.)
try expectEqual(try str.byteAt(0), 72); // H
try expectEqual(try str.byteAt(-2), 108); // l
try expectEqual(try str.codePointAt(0), 'H');
try expectEqual(try str.codePointAt(-2), 'l');
try expect((try str.graphemeAt(0)).eql("H"));
try expect((try str.graphemeAt(-4)).eql("é"));
// Copy
var str2 = try str.copy(allocator);
defer str2.deinit();
try expect(str.eql(str2.bytes.items));
try expect(str2.eql("Héllo"));
try expect(str.sameAs(str2));
// Empty and obtain owned slice of bytes.
const bytes2 = try str2.toOwnedSlice();
defer allocator.free(bytes2);
try expect(str2.eql(""));
try expectEqualStrings(bytes2, "Héllo");
// Re-initialize a Zigstr.
try str.reset("foo");
// Equality
try expect(str.eql("foo")); // exact
try expect(!str.eql("fooo")); // lengths
try expect(!str.eql("foó")); // combining marks
try expect(!str.eql("Foo")); // letter case
// Trimming.
try str.reset(" Hello");
try str.trimLeft(" ");
try expect(str.eql("Hello"));
try str.reset("Hello ");
try str.trimRight(" ");
try expect(str.eql("Hello"));
try str.reset(" Hello ");
try str.trim(" ");
try expect(str.eql("Hello"));
// indexOf / contains / lastIndexOf
try str.reset("H\u{65}\u{301}llo"); // Héllo
try expectEqual(try str.indexOf("l"), 2);
try expectEqual(try str.indexOf("z"), null);
try expect(try str.contains("l"));
try expect(!try str.contains("z"));
try expectEqual(try str.lastIndexOf("l"), 3);
try expectEqual(try str.lastIndexOf("z"), null);
// count
try expectEqual(str.count("l"), 2);
try expectEqual(str.count("ll"), 1);
try expectEqual(str.count("z"), 0);
// Tokenization
try str.reset(" Hello World ");
// Token iteration.
var tok_iter = str.tokenIter(" ");
try expectEqualStrings("Hello", tok_iter.next().?);
try expectEqualStrings("World", tok_iter.next().?);
try expect(tok_iter.next() == null);
// Collect all tokens at once.
var ts = try str.tokenize(" ", allocator);
defer allocator.free(ts);
try expectEqual(@as(usize, 2), ts.len);
try expectEqualStrings("Hello", ts[0]);
try expectEqualStrings("World", ts[1]);
// Split
var split_iter = str.splitIter(" ");
try expectEqualStrings("", split_iter.next().?);
try expectEqualStrings("Hello", split_iter.next().?);
try expectEqualStrings("World", split_iter.next().?);
try expectEqualStrings("", split_iter.next().?);
try expect(split_iter.next() == null);
// Collect all sub-strings at once.
var ss = try str.split(" ", allocator);
defer allocator.free(ss);
try expectEqual(@as(usize, 4), ss.len);
try expectEqualStrings("", ss[0]);
try expectEqualStrings("Hello", ss[1]);
try expectEqualStrings("World", ss[2]);
try expectEqualStrings("", ss[3]);
// Convenience methods for splitting on newline '\n'.
try str.reset("Hello\nWorld");
var iter = str.lineIter(); // line iterator
try expectEqualStrings(iter.next().?, "Hello");
try expectEqualStrings(iter.next().?, "World");
var lines_array = try str.lines(allocator); // array of lines without ending \n.
defer allocator.free(lines_array);
try expectEqualStrings(lines_array[0], "Hello");
try expectEqualStrings(lines_array[1], "World");
// startsWith / endsWith
try str.reset("Hello World");
try expect(str.startsWith("Hell"));
try expect(!str.startsWith("Zig"));
try expect(str.endsWith("World"));
try expect(!str.endsWith("Zig"));
// Concatenation
try str.reset("Hello");
try str.concat(" World");
try expect(str.eql("Hello World"));
var others = [_][]const u8{ " is", " the", " tradition!" };
try str.concatAll(&others);
try expect(str.eql("Hello World is the tradition!"));
// replace
try str.reset("Hello");
var replacements = try str.replace("l", "z");
try expectEqual(@as(usize, 2), replacements);
try expect(str.eql("Hezzo"));
replacements = try str.replace("z", "");
try expectEqual(@as(usize, 2), replacements);
try expect(str.eql("Heo"));
// Append a code point or many.
try str.reset("Hell");
try str.append('o');
try expectEqual(@as(usize, 5), str.bytes.items.len);
try expect(str.eql("Hello"));
try str.appendAll(&[_]u21{ ' ', 'W', 'o', 'r', 'l', 'd' });
try expect(str.eql("Hello World"));
// Test for empty string.
try expect(!str.isEmpty());
// Test for whitespace only (blank) strings.
try str.reset(" \t ");
try expect(try str.isBlank());
try expect(!str.isEmpty());
// Remove grapheme clusters (characters) from strings.
try str.reset("Hello World");
try str.dropLeft(6);
try expect(str.eql("World"));
try str.reset("Hello World");
try str.dropRight(6);
try expect(str.eql("Hello"));
// Insert at a grapheme index.
try str.insert("Hi", 0);
try expect(str.eql("HiHello"));
// Remove a sub-string.
try str.remove("Hi");
try expect(str.eql("Hello"));
try str.remove("Hello");
try expect(str.eql(""));
// Repeat a string's content.
try str.reset("*");
try str.repeat(10);
try expect(str.eql("**********"));
try str.repeat(1);
try expect(str.eql("**********"));
try str.repeat(0);
try expect(str.eql(""));
// Reverse a string. Note correct handling of Unicode code point ordering.
try str.reset("Héllo 😊");
try str.reverse();
try expect(str.eql("😊 olléH"));
// You can also construct a Zigstr from coce points.
const cp_array = [_]u21{ 0x68, 0x65, 0x6C, 0x6C, 0x6F }; // "hello"
str.deinit();
str = try zigstr.fromCodePoints(allocator, &cp_array);
try expect(str.eql("hello"));
try expectEqual(str.codePointCount(), 5);
// Also create a Zigstr from a slice of strings.
str.deinit();
str = try zigstr.fromJoined(std.testing.allocator, &[_][]const u8{ "Hello", "World" }, " ");
try expect(str.eql("Hello World"));
// Chomp line breaks.
try str.reset("Hello\n");
try str.chomp();
try expectEqual(@as(usize, 5), str.bytes.items.len);
try expect(str.eql("Hello"));
try str.reset("Hello\r");
try str.chomp();
try expectEqual(@as(usize, 5), str.bytes.items.len);
try expect(str.eql("Hello"));
try str.reset("Hello\r\n");
try str.chomp();
try expectEqual(@as(usize, 5), str.bytes.items.len);
try expect(str.eql("Hello"));
// byteSlice, codePointSlice, graphemeSlice, substr
try str.reset("H\u{0065}\u{0301}llo"); // Héllo
const bytes = try str.byteSlice(1, 4);
try expectEqualSlices(u8, bytes, "\u{0065}\u{0301}");
const cps = try str.codePointSlice(allocator, 1, 3);
defer allocator.free(cps);
try expectEqualSlices(u21, cps, &[_]u21{ '\u{0065}', '\u{0301}' });
const gs = try str.graphemeSlice(allocator, 1, 2);
defer allocator.free(gs);
try expect(gs[0].eql("\u{0065}\u{0301}"));
// Substrings
var sub = try str.substr(1, 2);
try expectEqualStrings("\u{0065}\u{0301}", sub);
try expectEqualStrings(bytes, sub);
// Letter case detection.
try str.reset("hello! 123");
try expect(try str.isLower());
try expect(!try str.isUpper());
try str.reset("HELLO! 123");
try expect(try str.isUpper());
try expect(!try str.isLower());
// Letter case conversion.
try str.reset("Héllo World! 123\n");
try str.toLower();
try expect(str.eql("héllo world! 123\n"));
try str.toUpper();
try expect(str.eql("HÉLLO WORLD! 123\n"));
try str.reset("tHe (mOviE) 2112\n");
try str.toTitle();
try expect(str.eql("The (Movie) 2112\n"));
// Parsing content.
try str.reset("123");
try expectEqual(try str.parseInt(u8, 10), 123);
try str.reset("123.456");
try expectEqual(try str.parseFloat(f32), 123.456);
try str.reset("true");
try expect(try str.parseBool());
// Truthy == True, T, Yes, Y, On in any letter case.
// Not Truthy == False, F, No, N, Off in any letter case.
try expect(try str.parseTruthy());
try str.reset("TRUE");
try expect(try str.parseTruthy());
try str.reset("T");
try expect(try str.parseTruthy());
try str.reset("No");
try expect(!try str.parseTruthy());
try str.reset("off");
try expect(!try str.parseTruthy());
// Zigstr implements the std.fmt.format interface.
std.debug.print("Zigstr: {}\n", .{str});
} | src/main.zig |
const std = @import("std");
const mem = std.mem;
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const ast = std.c.ast;
const Node = ast.Node;
const Type = ast.Type;
const Tree = ast.Tree;
const TokenIndex = ast.TokenIndex;
const Token = std.c.Token;
const TokenIterator = ast.Tree.TokenList.Iterator;
pub const Error = error{ParseError} || Allocator.Error;
pub const Options = struct {
// /// Keep simple macros unexpanded and add the definitions to the ast
// retain_macros: bool = false,
/// Warning or error
warn_as_err: union(enum) {
/// All warnings are warnings
None,
/// Some warnings are errors
Some: []@TagType(ast.Error),
/// All warnings are errors
All,
} = .All,
};
/// Result should be freed with tree.deinit() when there are
/// no more references to any of the tokens or nodes.
pub fn parse(allocator: *Allocator, source: []const u8, options: Options) !*Tree {
const tree = blk: {
// This block looks unnecessary, but is a "foot-shield" to prevent the SegmentedLists
// from being initialized with a pointer to this `arena`, which is created on
// the stack. Following code should instead refer to `&tree.arena_allocator`, a
// pointer to data which lives safely on the heap and will outlive `parse`.
var arena = std.heap.ArenaAllocator.init(allocator);
errdefer arena.deinit();
const tree = try arena.allocator.create(ast.Tree);
tree.* = .{
.root_node = undefined,
.arena_allocator = arena,
.tokens = undefined,
.sources = undefined,
};
break :blk tree;
};
errdefer tree.deinit();
const arena = &tree.arena_allocator.allocator;
tree.tokens = ast.Tree.TokenList.init(arena);
tree.sources = ast.Tree.SourceList.init(arena);
var tokenizer = std.zig.Tokenizer.init(source);
while (true) {
const tree_token = try tree.tokens.addOne();
tree_token.* = tokenizer.next();
if (tree_token.id == .Eof) break;
}
// TODO preprocess here
var it = tree.tokens.iterator(0);
while (true) {
const tok = it.peek().?.id;
switch (id) {
.LineComment,
.MultiLineComment,
=> {
_ = it.next();
},
else => break,
}
}
var parse_arena = std.heap.ArenaAllocator.init(allocator);
defer parse_arena.deinit();
var parser = Parser{
.scopes = Parser.SymbolList.init(allocator),
.arena = &parse_arena.allocator,
.it = &it,
.tree = tree,
.options = options,
};
defer parser.symbols.deinit();
tree.root_node = try parser.root();
return tree;
}
const Parser = struct {
arena: *Allocator,
it: *TokenIterator,
tree: *Tree,
arena: *Allocator,
scopes: ScopeList,
options: Options,
const ScopeList = std.SegmentedLists(Scope);
const SymbolList = std.SegmentedLists(Symbol);
const Scope = struct {
kind: ScopeKind,
syms: SymbolList,
};
const Symbol = struct {
name: []const u8,
ty: *Type,
};
const ScopeKind = enum {
Block,
Loop,
Root,
Switch,
};
fn pushScope(parser: *Parser, kind: ScopeKind) !void {
const new = try parser.scopes.addOne();
new.* = .{
.kind = kind,
.syms = SymbolList.init(parser.arena),
};
}
fn popScope(parser: *Parser, len: usize) void {
_ = parser.scopes.pop();
}
fn getSymbol(parser: *Parser, tok: TokenIndex) ?*Symbol {
const name = parser.tree.tokenSlice(tok);
var scope_it = parser.scopes.iterator(parser.scopes.len);
while (scope_it.prev()) |scope| {
var sym_it = scope.syms.iterator(scope.syms.len);
while (sym_it.prev()) |sym| {
if (mem.eql(u8, sym.name, name)) {
return sym;
}
}
}
return null;
}
fn declareSymbol(parser: *Parser, type_spec: Node.TypeSpec, dr: *Node.Declarator) Error!void {
return; // TODO
}
/// Root <- ExternalDeclaration* eof
fn root(parser: *Parser) Allocator.Error!*Node.Root {
try parser.pushScope(.Root);
defer parser.popScope();
const node = try parser.arena.create(Node.Root);
node.* = .{
.decls = Node.Root.DeclList.init(parser.arena),
.eof = undefined,
};
while (parser.externalDeclarations() catch |e| switch (e) {
error.OutOfMemory => return error.OutOfMemory,
error.ParseError => return node,
}) |decl| {
try node.decls.push(decl);
}
node.eof = parser.eatToken(.Eof) orelse return node;
return node;
}
/// ExternalDeclaration
/// <- DeclSpec Declarator OldStyleDecl* CompoundStmt
/// / Declaration
/// OldStyleDecl <- DeclSpec Declarator (COMMA Declarator)* SEMICOLON
fn externalDeclarations(parser: *Parser) !?*Node {
return parser.declarationExtra(false);
}
/// Declaration
/// <- DeclSpec DeclInit SEMICOLON
/// / StaticAssert
/// DeclInit <- Declarator (EQUAL Initializer)? (COMMA Declarator (EQUAL Initializer)?)*
fn declaration(parser: *Parser) !?*Node {
return parser.declarationExtra(true);
}
fn declarationExtra(parser: *Parser, local: bool) !?*Node {
if (try parser.staticAssert()) |decl| return decl;
const begin = parser.it.index + 1;
var ds = Node.DeclSpec{};
const got_ds = try parser.declSpec(&ds);
if (local and !got_ds) {
// not a declaration
return null;
}
switch (ds.storage_class) {
.Auto, .Register => |tok| return parser.err(.{
.InvalidStorageClass = .{ .token = tok },
}),
.Typedef => {
const node = try parser.arena.create(Node.Typedef);
node.* = .{
.decl_spec = ds,
.declarators = Node.Typedef.DeclaratorList.init(parser.arena),
.semicolon = undefined,
};
while (true) {
const dr = @fieldParentPtr(Node.Declarator, "base", (try parser.declarator(.Must)) orelse return parser.err(.{
.ExpectedDeclarator = .{ .token = parser.it.index },
}));
try parser.declareSymbol(ds.type_spec, dr);
try node.declarators.push(&dr.base);
if (parser.eatToken(.Comma)) |_| {} else break;
}
return &node.base;
},
else => {},
}
var first_dr = try parser.declarator(.Must);
if (first_dr != null and declaratorIsFunction(first_dr.?)) {
// TODO typedeffed fn proto-only
const dr = @fieldParentPtr(Node.Declarator, "base", first_dr.?);
try parser.declareSymbol(ds.type_spec, dr);
var old_decls = Node.FnDecl.OldDeclList.init(parser.arena);
const body = if (parser.eatToken(.Semicolon)) |_|
null
else blk: {
if (local) {
// TODO nested function warning
}
// TODO first_dr.is_old
// while (true) {
// var old_ds = Node.DeclSpec{};
// if (!(try parser.declSpec(&old_ds))) {
// // not old decl
// break;
// }
// var old_dr = (try parser.declarator(.Must));
// // if (old_dr == null)
// // try parser.err(.{
// // .NoParamName = .{ .token = parser.it.index },
// // });
// // try old_decls.push(decl);
// }
const body_node = (try parser.compoundStmt()) orelse return parser.err(.{
.ExpectedFnBody = .{ .token = parser.it.index },
});
break :blk @fieldParentPtr(Node.CompoundStmt, "base", body_node);
};
const node = try parser.arena.create(Node.FnDecl);
node.* = .{
.decl_spec = ds,
.declarator = dr,
.old_decls = old_decls,
.body = body,
};
return &node.base;
} else {
switch (ds.fn_spec) {
.Inline, .Noreturn => |tok| return parser.err(.{
.FnSpecOnNonFn = .{ .token = tok },
}),
else => {},
}
// TODO threadlocal without static or extern on local variable
const node = try parser.arena.create(Node.VarDecl);
node.* = .{
.decl_spec = ds,
.initializers = Node.VarDecl.Initializers.init(parser.arena),
.semicolon = undefined,
};
if (first_dr == null) {
node.semicolon = try parser.expectToken(.Semicolon);
const ok = switch (ds.type_spec.spec) {
.Enum => |e| e.name != null,
.Record => |r| r.name != null,
else => false,
};
const q = ds.type_spec.qual;
if (!ok)
try parser.warn(.{
.NothingDeclared = .{ .token = begin },
})
else if (q.@"const" orelse q.atomic orelse q.@"volatile" orelse q.restrict) |tok|
try parser.warn(.{
.QualifierIgnored = .{ .token = tok },
});
return &node.base;
}
var dr = @fieldParentPtr(Node.Declarator, "base", first_dr.?);
while (true) {
try parser.declareSymbol(ds.type_spec, dr);
if (parser.eatToken(.Equal)) |tok| {
try node.initializers.push((try parser.initializer(dr)) orelse return parser.err(.{
.ExpectedInitializer = .{ .token = parser.it.index },
}));
} else
try node.initializers.push(&dr.base);
if (parser.eatToken(.Comma) != null) break;
dr = @fieldParentPtr(Node.Declarator, "base", (try parser.declarator(.Must)) orelse return parser.err(.{
.ExpectedDeclarator = .{ .token = parser.it.index },
}));
}
node.semicolon = try parser.expectToken(.Semicolon);
return &node.base;
}
}
fn declaratorIsFunction(node: *Node) bool {
if (node.id != .Declarator) return false;
assert(node.id == .Declarator);
const dr = @fieldParentPtr(Node.Declarator, "base", node);
if (dr.suffix != .Fn) return false;
switch (dr.prefix) {
.None, .Identifer => return true,
.Complex => |inner| {
var inner_node = inner.inner;
while (true) {
if (inner_node.id != .Declarator) return false;
assert(inner_node.id == .Declarator);
const inner_dr = @fieldParentPtr(Node.Declarator, "base", inner_node);
if (inner_dr.pointer != null) return false;
switch (inner_dr.prefix) {
.None, .Identifer => return true,
.Complex => |c| inner_node = c.inner,
}
}
},
}
}
/// StaticAssert <- Keyword_static_assert LPAREN ConstExpr COMMA STRINGLITERAL RPAREN SEMICOLON
fn staticAssert(parser: *Parser) !?*Node {
const tok = parser.eatToken(.Keyword_static_assert) orelse return null;
_ = try parser.expectToken(.LParen);
const const_expr = (try parser.constExpr()) orelse parser.err(.{
.ExpectedExpr = .{ .token = parser.it.index },
});
_ = try parser.expectToken(.Comma);
const str = try parser.expectToken(.StringLiteral);
_ = try parser.expectToken(.RParen);
const node = try parser.arena.create(Node.StaticAssert);
node.* = .{
.assert = tok,
.expr = const_expr,
.semicolon = try parser.expectToken(.Semicolon),
};
return &node.base;
}
/// DeclSpec <- (StorageClassSpec / TypeSpec / FnSpec / AlignSpec)*
/// returns true if any tokens were consumed
fn declSpec(parser: *Parser, ds: *Node.DeclSpec) !bool {
var got = false;
while ((try parser.storageClassSpec(ds)) or (try parser.typeSpec(&ds.type_spec)) or (try parser.fnSpec(ds)) or (try parser.alignSpec(ds))) {
got = true;
}
return got;
}
/// StorageClassSpec
/// <- Keyword_typedef / Keyword_extern / Keyword_static / Keyword_thread_local / Keyword_auto / Keyword_register
fn storageClassSpec(parser: *Parser, ds: *Node.DeclSpec) !bool {
blk: {
if (parser.eatToken(.Keyword_typedef)) |tok| {
if (ds.storage_class != .None or ds.thread_local != null)
break :blk;
ds.storage_class = .{ .Typedef = tok };
} else if (parser.eatToken(.Keyword_extern)) |tok| {
if (ds.storage_class != .None)
break :blk;
ds.storage_class = .{ .Extern = tok };
} else if (parser.eatToken(.Keyword_static)) |tok| {
if (ds.storage_class != .None)
break :blk;
ds.storage_class = .{ .Static = tok };
} else if (parser.eatToken(.Keyword_thread_local)) |tok| {
switch (ds.storage_class) {
.None, .Extern, .Static => {},
else => break :blk,
}
ds.thread_local = tok;
} else if (parser.eatToken(.Keyword_auto)) |tok| {
if (ds.storage_class != .None or ds.thread_local != null)
break :blk;
ds.storage_class = .{ .Auto = tok };
} else if (parser.eatToken(.Keyword_register)) |tok| {
if (ds.storage_class != .None or ds.thread_local != null)
break :blk;
ds.storage_class = .{ .Register = tok };
} else return false;
return true;
}
try parser.warn(.{
.DuplicateSpecifier = .{ .token = parser.it.index },
});
return true;
}
/// TypeSpec
/// <- Keyword_void / Keyword_char / Keyword_short / Keyword_int / Keyword_long / Keyword_float / Keyword_double
/// / Keyword_signed / Keyword_unsigned / Keyword_bool / Keyword_complex / Keyword_imaginary /
/// / Keyword_atomic LPAREN TypeName RPAREN
/// / EnumSpec
/// / RecordSpec
/// / IDENTIFIER // typedef name
/// / TypeQual
fn typeSpec(parser: *Parser, type_spec: *Node.TypeSpec) !bool {
blk: {
if (parser.eatToken(.Keyword_void)) |tok| {
if (type_spec.spec != .None)
break :blk;
type_spec.spec = .{ .Void = tok };
} else if (parser.eatToken(.Keyword_char)) |tok| {
switch (type_spec.spec) {
.None => {
type_spec.spec = .{
.Char = .{
.char = tok,
},
};
},
.Int => |int| {
if (int.int != null)
break :blk;
type_spec.spec = .{
.Char = .{
.char = tok,
.sign = int.sign,
},
};
},
else => break :blk,
}
} else if (parser.eatToken(.Keyword_short)) |tok| {
switch (type_spec.spec) {
.None => {
type_spec.spec = .{
.Short = .{
.short = tok,
},
};
},
.Int => |int| {
if (int.int != null)
break :blk;
type_spec.spec = .{
.Short = .{
.short = tok,
.sign = int.sign,
},
};
},
else => break :blk,
}
} else if (parser.eatToken(.Keyword_long)) |tok| {
switch (type_spec.spec) {
.None => {
type_spec.spec = .{
.Long = .{
.long = tok,
},
};
},
.Int => |int| {
type_spec.spec = .{
.Long = .{
.long = tok,
.sign = int.sign,
.int = int.int,
},
};
},
.Long => |*long| {
if (long.longlong != null)
break :blk;
long.longlong = tok;
},
.Double => |*double| {
if (double.long != null)
break :blk;
double.long = tok;
},
else => break :blk,
}
} else if (parser.eatToken(.Keyword_int)) |tok| {
switch (type_spec.spec) {
.None => {
type_spec.spec = .{
.Int = .{
.int = tok,
},
};
},
.Short => |*short| {
if (short.int != null)
break :blk;
short.int = tok;
},
.Int => |*int| {
if (int.int != null)
break :blk;
int.int = tok;
},
.Long => |*long| {
if (long.int != null)
break :blk;
long.int = tok;
},
else => break :blk,
}
} else if (parser.eatToken(.Keyword_signed) orelse parser.eatToken(.Keyword_unsigned)) |tok| {
switch (type_spec.spec) {
.None => {
type_spec.spec = .{
.Int = .{
.sign = tok,
},
};
},
.Char => |*char| {
if (char.sign != null)
break :blk;
char.sign = tok;
},
.Short => |*short| {
if (short.sign != null)
break :blk;
short.sign = tok;
},
.Int => |*int| {
if (int.sign != null)
break :blk;
int.sign = tok;
},
.Long => |*long| {
if (long.sign != null)
break :blk;
long.sign = tok;
},
else => break :blk,
}
} else if (parser.eatToken(.Keyword_float)) |tok| {
if (type_spec.spec != .None)
break :blk;
type_spec.spec = .{
.Float = .{
.float = tok,
},
};
} else if (parser.eatToken(.Keyword_double)) |tok| {
if (type_spec.spec != .None)
break :blk;
type_spec.spec = .{
.Double = .{
.double = tok,
},
};
} else if (parser.eatToken(.Keyword_complex)) |tok| {
switch (type_spec.spec) {
.None => {
type_spec.spec = .{
.Double = .{
.complex = tok,
.double = null,
},
};
},
.Float => |*float| {
if (float.complex != null)
break :blk;
float.complex = tok;
},
.Double => |*double| {
if (double.complex != null)
break :blk;
double.complex = tok;
},
else => break :blk,
}
} else if (parser.eatToken(.Keyword_bool)) |tok| {
if (type_spec.spec != .None)
break :blk;
type_spec.spec = .{ .Bool = tok };
} else if (parser.eatToken(.Keyword_atomic)) |tok| {
// might be _Atomic qualifier
if (parser.eatToken(.LParen)) |_| {
if (type_spec.spec != .None)
break :blk;
const name = (try parser.typeName()) orelse return parser.err(.{
.ExpectedTypeName = .{ .token = parser.it.index },
});
type_spec.spec.Atomic = .{
.atomic = tok,
.typename = name,
.rparen = try parser.expectToken(.RParen),
};
} else {
parser.putBackToken(tok);
}
} else if (parser.eatToken(.Keyword_enum)) |tok| {
if (type_spec.spec != .None)
break :blk;
type_spec.spec.Enum = try parser.enumSpec(tok);
} else if (parser.eatToken(.Keyword_union) orelse parser.eatToken(.Keyword_struct)) |tok| {
if (type_spec.spec != .None)
break :blk;
type_spec.spec.Record = try parser.recordSpec(tok);
} else if (parser.eatToken(.Identifier)) |tok| {
const ty = parser.getSymbol(tok) orelse {
parser.putBackToken(tok);
return false;
};
switch (ty.id) {
.Enum => |e| blk: {
if (e.name) |some|
if (!parser.tree.tokenEql(some, tok))
break :blk;
return parser.err(.{
.MustUseKwToRefer = .{ .kw = e.tok, .name = tok },
});
},
.Record => |r| blk: {
if (r.name) |some|
if (!parser.tree.tokenEql(some, tok))
break :blk;
return parser.err(.{
.MustUseKwToRefer = .{
.kw = r.tok,
.name = tok,
},
});
},
.Typedef => {
type_spec.spec = .{
.Typedef = .{
.sym = tok,
.sym_type = ty,
},
};
return true;
},
else => {},
}
parser.putBackToken(tok);
return false;
}
return parser.typeQual(&type_spec.qual);
}
return parser.err(.{
.InvalidTypeSpecifier = .{
.token = parser.it.index,
.type_spec = type_spec,
},
});
}
/// TypeQual <- Keyword_const / Keyword_restrict / Keyword_volatile / Keyword_atomic
fn typeQual(parser: *Parser, qual: *Node.TypeQual) !bool {
blk: {
if (parser.eatToken(.Keyword_const)) |tok| {
if (qual.@"const" != null)
break :blk;
qual.@"const" = tok;
} else if (parser.eatToken(.Keyword_restrict)) |tok| {
if (qual.atomic != null)
break :blk;
qual.atomic = tok;
} else if (parser.eatToken(.Keyword_volatile)) |tok| {
if (qual.@"volatile" != null)
break :blk;
qual.@"volatile" = tok;
} else if (parser.eatToken(.Keyword_atomic)) |tok| {
if (qual.atomic != null)
break :blk;
qual.atomic = tok;
} else return false;
return true;
}
try parser.warn(.{
.DuplicateQualifier = .{ .token = parser.it.index },
});
return true;
}
/// FnSpec <- Keyword_inline / Keyword_noreturn
fn fnSpec(parser: *Parser, ds: *Node.DeclSpec) !bool {
blk: {
if (parser.eatToken(.Keyword_inline)) |tok| {
if (ds.fn_spec != .None)
break :blk;
ds.fn_spec = .{ .Inline = tok };
} else if (parser.eatToken(.Keyword_noreturn)) |tok| {
if (ds.fn_spec != .None)
break :blk;
ds.fn_spec = .{ .Noreturn = tok };
} else return false;
return true;
}
try parser.warn(.{
.DuplicateSpecifier = .{ .token = parser.it.index },
});
return true;
}
/// AlignSpec <- Keyword_alignas LPAREN (TypeName / ConstExpr) RPAREN
fn alignSpec(parser: *Parser, ds: *Node.DeclSpec) !bool {
if (parser.eatToken(.Keyword_alignas)) |tok| {
_ = try parser.expectToken(.LParen);
const node = (try parser.typeName()) orelse (try parser.constExpr()) orelse parser.err(.{
.ExpectedExpr = .{ .token = parser.it.index },
});
if (ds.align_spec != null) {
try parser.warn(.{
.DuplicateSpecifier = .{ .token = parser.it.index },
});
}
ds.align_spec = .{
.alignas = tok,
.expr = node,
.rparen = try parser.expectToken(.RParen),
};
return true;
}
return false;
}
/// EnumSpec <- Keyword_enum IDENTIFIER? (LBRACE EnumField RBRACE)?
fn enumSpec(parser: *Parser, tok: TokenIndex) !*Node.EnumType {
const node = try parser.arena.create(Node.EnumType);
const name = parser.eatToken(.Identifier);
node.* = .{
.tok = tok,
.name = name,
.body = null,
};
const ty = try parser.arena.create(Type);
ty.* = .{
.id = .{
.Enum = node,
},
};
if (name) |some|
try parser.symbols.append(.{
.name = parser.tree.tokenSlice(some),
.ty = ty,
});
if (parser.eatToken(.LBrace)) |lbrace| {
var fields = Node.EnumType.FieldList.init(parser.arena);
try fields.push((try parser.enumField()) orelse return parser.err(.{
.ExpectedEnumField = .{ .token = parser.it.index },
}));
while (parser.eatToken(.Comma)) |_| {
try fields.push((try parser.enumField()) orelse break);
}
node.body = .{
.lbrace = lbrace,
.fields = fields,
.rbrace = try parser.expectToken(.RBrace),
};
}
return node;
}
/// EnumField <- IDENTIFIER (EQUAL ConstExpr)? (COMMA EnumField) COMMA?
fn enumField(parser: *Parser) !?*Node {
const name = parser.eatToken(.Identifier) orelse return null;
const node = try parser.arena.create(Node.EnumField);
node.* = .{
.name = name,
.value = null,
};
if (parser.eatToken(.Equal)) |eq| {
node.value = (try parser.constExpr()) orelse parser.err(.{
.ExpectedExpr = .{ .token = parser.it.index },
});
}
return &node.base;
}
/// RecordSpec <- (Keyword_struct / Keyword_union) IDENTIFIER? (LBRACE RecordField+ RBRACE)?
fn recordSpec(parser: *Parser, tok: TokenIndex) !*Node.RecordType {
const node = try parser.arena.create(Node.RecordType);
const name = parser.eatToken(.Identifier);
const is_struct = parser.tree.tokenSlice(tok)[0] == 's';
node.* = .{
.tok = tok,
.kind = if (is_struct) .Struct else .Union,
.name = name,
.body = null,
};
const ty = try parser.arena.create(Type);
ty.* = .{
.id = .{
.Record = node,
},
};
if (name) |some|
try parser.symbols.append(.{
.name = parser.tree.tokenSlice(some),
.ty = ty,
});
if (parser.eatToken(.LBrace)) |lbrace| {
try parser.pushScope(.Block);
defer parser.popScope();
var fields = Node.RecordType.FieldList.init(parser.arena);
while (true) {
if (parser.eatToken(.RBrace)) |rbrace| {
node.body = .{
.lbrace = lbrace,
.fields = fields,
.rbrace = rbrace,
};
break;
}
try fields.push(try parser.recordField());
}
}
return node;
}
/// RecordField
/// <- TypeSpec* (RecordDeclarator (COMMA RecordDeclarator))? SEMICOLON
/// \ StaticAssert
fn recordField(parser: *Parser) Error!*Node {
if (try parser.staticAssert()) |decl| return decl;
var got = false;
var type_spec = Node.TypeSpec{};
while (try parser.typeSpec(&type_spec)) got = true;
if (!got)
return parser.err(.{
.ExpectedType = .{ .token = parser.it.index },
});
const node = try parser.arena.create(Node.RecordField);
node.* = .{
.type_spec = type_spec,
.declarators = Node.RecordField.DeclaratorList.init(parser.arena),
.semicolon = undefined,
};
while (true) {
const rdr = try parser.recordDeclarator();
try parser.declareSymbol(type_spec, rdr.declarator);
try node.declarators.push(&rdr.base);
if (parser.eatToken(.Comma)) |_| {} else break;
}
node.semicolon = try parser.expectToken(.Semicolon);
return &node.base;
}
/// TypeName <- TypeSpec* AbstractDeclarator?
fn typeName(parser: *Parser) Error!?*Node {
@panic("TODO");
}
/// RecordDeclarator <- Declarator? (COLON ConstExpr)?
fn recordDeclarator(parser: *Parser) Error!*Node.RecordDeclarator {
@panic("TODO");
}
/// Pointer <- ASTERISK TypeQual* Pointer?
fn pointer(parser: *Parser) Error!?*Node.Pointer {
const asterisk = parser.eatToken(.Asterisk) orelse return null;
const node = try parser.arena.create(Node.Pointer);
node.* = .{
.asterisk = asterisk,
.qual = .{},
.pointer = null,
};
while (try parser.typeQual(&node.qual)) {}
node.pointer = try parser.pointer();
return node;
}
const Named = enum {
Must,
Allowed,
Forbidden,
};
/// Declarator <- Pointer? DeclaratorSuffix
/// DeclaratorPrefix
/// <- IDENTIFIER // if named != .Forbidden
/// / LPAREN Declarator RPAREN
/// / (none) // if named != .Must
/// DeclaratorSuffix
/// <- DeclaratorPrefix (LBRACKET ArrayDeclarator? RBRACKET)*
/// / DeclaratorPrefix LPAREN (ParamDecl (COMMA ParamDecl)* (COMMA ELLIPSIS)?)? RPAREN
fn declarator(parser: *Parser, named: Named) Error!?*Node {
const ptr = try parser.pointer();
var node: *Node.Declarator = undefined;
var inner_fn = false;
// TODO sizof(int (int))
// prefix
if (parser.eatToken(.LParen)) |lparen| {
const inner = (try parser.declarator(named)) orelse return parser.err(.{
.ExpectedDeclarator = .{ .token = lparen + 1 },
});
inner_fn = declaratorIsFunction(inner);
node = try parser.arena.create(Node.Declarator);
node.* = .{
.pointer = ptr,
.prefix = .{
.Complex = .{
.lparen = lparen,
.inner = inner,
.rparen = try parser.expectToken(.RParen),
},
},
.suffix = .None,
};
} else if (named != .Forbidden) {
if (parser.eatToken(.Identifier)) |tok| {
node = try parser.arena.create(Node.Declarator);
node.* = .{
.pointer = ptr,
.prefix = .{ .Identifer = tok },
.suffix = .None,
};
} else if (named == .Must) {
return parser.err(.{
.ExpectedToken = .{ .token = parser.it.index, .expected_id = .Identifier },
});
} else {
if (ptr) |some|
return &some.base;
return null;
}
} else {
node = try parser.arena.create(Node.Declarator);
node.* = .{
.pointer = ptr,
.prefix = .None,
.suffix = .None,
};
}
// suffix
if (parser.eatToken(.LParen)) |lparen| {
if (inner_fn)
return parser.err(.{
.InvalidDeclarator = .{ .token = lparen },
});
node.suffix = .{
.Fn = .{
.lparen = lparen,
.params = Node.Declarator.Params.init(parser.arena),
.rparen = undefined,
},
};
try parser.paramDecl(node);
node.suffix.Fn.rparen = try parser.expectToken(.RParen);
} else if (parser.eatToken(.LBracket)) |tok| {
if (inner_fn)
return parser.err(.{
.InvalidDeclarator = .{ .token = tok },
});
node.suffix = .{ .Array = Node.Declarator.Arrays.init(parser.arena) };
var lbrace = tok;
while (true) {
try node.suffix.Array.push(try parser.arrayDeclarator(lbrace));
if (parser.eatToken(.LBracket)) |t| lbrace = t else break;
}
}
if (parser.eatToken(.LParen) orelse parser.eatToken(.LBracket)) |tok|
return parser.err(.{
.InvalidDeclarator = .{ .token = tok },
});
return &node.base;
}
/// ArrayDeclarator
/// <- ASTERISK
/// / Keyword_static TypeQual* AssignmentExpr
/// / TypeQual+ (ASTERISK / Keyword_static AssignmentExpr)
/// / TypeQual+ AssignmentExpr?
/// / AssignmentExpr
fn arrayDeclarator(parser: *Parser, lbracket: TokenIndex) !*Node.Array {
const arr = try parser.arena.create(Node.Array);
arr.* = .{
.lbracket = lbracket,
.inner = .Inferred,
.rbracket = undefined,
};
if (parser.eatToken(.Asterisk)) |tok| {
arr.inner = .{ .Unspecified = tok };
} else {
// TODO
}
arr.rbracket = try parser.expectToken(.RBracket);
return arr;
}
/// Params <- ParamDecl (COMMA ParamDecl)* (COMMA ELLIPSIS)?
/// ParamDecl <- DeclSpec (Declarator / AbstractDeclarator)
fn paramDecl(parser: *Parser, dr: *Node.Declarator) !void {
var old_style = false;
while (true) {
var ds = Node.DeclSpec{};
if (try parser.declSpec(&ds)) {
//TODO
// TODO try parser.declareSymbol(ds.type_spec, dr);
} else if (parser.eatToken(.Identifier)) |tok| {
old_style = true;
} else if (parser.eatToken(.Ellipsis)) |tok| {
// TODO
}
}
}
/// Expr <- AssignmentExpr (COMMA Expr)*
fn expr(parser: *Parser) Error!?*Expr {
@panic("TODO");
}
/// AssignmentExpr
/// <- ConditionalExpr // TODO recursive?
/// / UnaryExpr (EQUAL / ASTERISKEQUAL / SLASHEQUAL / PERCENTEQUAL / PLUSEQUAL / MINUSEQUA /
/// / ANGLEBRACKETANGLEBRACKETLEFTEQUAL / ANGLEBRACKETANGLEBRACKETRIGHTEQUAL /
/// / AMPERSANDEQUAL / CARETEQUAL / PIPEEQUAL) AssignmentExpr
fn assignmentExpr(parser: *Parser) !?*Expr {
@panic("TODO");
}
/// ConstExpr <- ConditionalExpr
fn constExpr(parser: *Parser) Error!?*Expr {
const start = parser.it.index;
const expression = try parser.conditionalExpr();
if (expression != null and expression.?.value == .None)
return parser.err(.{
.ConsExpr = start,
});
return expression;
}
/// ConditionalExpr <- LogicalOrExpr (QUESTIONMARK Expr COLON ConditionalExpr)?
fn conditionalExpr(parser: *Parser) Error!?*Expr {
@panic("TODO");
}
/// LogicalOrExpr <- LogicalAndExpr (PIPEPIPE LogicalOrExpr)*
fn logicalOrExpr(parser: *Parser) !*Node {
const lhs = (try parser.logicalAndExpr()) orelse return null;
}
/// LogicalAndExpr <- BinOrExpr (AMPERSANDAMPERSAND LogicalAndExpr)*
fn logicalAndExpr(parser: *Parser) !*Node {
@panic("TODO");
}
/// BinOrExpr <- BinXorExpr (PIPE BinOrExpr)*
fn binOrExpr(parser: *Parser) !*Node {
@panic("TODO");
}
/// BinXorExpr <- BinAndExpr (CARET BinXorExpr)*
fn binXorExpr(parser: *Parser) !*Node {
@panic("TODO");
}
/// BinAndExpr <- EqualityExpr (AMPERSAND BinAndExpr)*
fn binAndExpr(parser: *Parser) !*Node {
@panic("TODO");
}
/// EqualityExpr <- ComparisionExpr ((EQUALEQUAL / BANGEQUAL) EqualityExpr)*
fn equalityExpr(parser: *Parser) !*Node {
@panic("TODO");
}
/// ComparisionExpr <- ShiftExpr (ANGLEBRACKETLEFT / ANGLEBRACKETLEFTEQUAL /ANGLEBRACKETRIGHT / ANGLEBRACKETRIGHTEQUAL) ComparisionExpr)*
fn comparisionExpr(parser: *Parser) !*Node {
@panic("TODO");
}
/// ShiftExpr <- AdditiveExpr (ANGLEBRACKETANGLEBRACKETLEFT / ANGLEBRACKETANGLEBRACKETRIGHT) ShiftExpr)*
fn shiftExpr(parser: *Parser) !*Node {
@panic("TODO");
}
/// AdditiveExpr <- MultiplicativeExpr (PLUS / MINUS) AdditiveExpr)*
fn additiveExpr(parser: *Parser) !*Node {
@panic("TODO");
}
/// MultiplicativeExpr <- UnaryExpr (ASTERISK / SLASH / PERCENT) MultiplicativeExpr)*
fn multiplicativeExpr(parser: *Parser) !*Node {
@panic("TODO");
}
/// UnaryExpr
/// <- LPAREN TypeName RPAREN UnaryExpr
/// / Keyword_sizeof LAPERN TypeName RPAREN
/// / Keyword_sizeof UnaryExpr
/// / Keyword_alignof LAPERN TypeName RPAREN
/// / (AMPERSAND / ASTERISK / PLUS / PLUSPLUS / MINUS / MINUSMINUS / TILDE / BANG) UnaryExpr
/// / PrimaryExpr PostFixExpr*
fn unaryExpr(parser: *Parser) !*Node {
@panic("TODO");
}
/// PrimaryExpr
/// <- IDENTIFIER
/// / INTEGERLITERAL / FLOATLITERAL / STRINGLITERAL / CHARLITERAL
/// / LPAREN Expr RPAREN
/// / Keyword_generic LPAREN AssignmentExpr (COMMA Generic)+ RPAREN
fn primaryExpr(parser: *Parser) !*Node {
@panic("TODO");
}
/// Generic
/// <- TypeName COLON AssignmentExpr
/// / Keyword_default COLON AssignmentExpr
fn generic(parser: *Parser) !*Node {
@panic("TODO");
}
/// PostFixExpr
/// <- LPAREN TypeName RPAREN LBRACE Initializers RBRACE
/// / LBRACKET Expr RBRACKET
/// / LPAREN (AssignmentExpr (COMMA AssignmentExpr)*)? RPAREN
/// / (PERIOD / ARROW) IDENTIFIER
/// / (PLUSPLUS / MINUSMINUS)
fn postFixExpr(parser: *Parser) !*Node {
@panic("TODO");
}
/// Initializers <- ((Designator+ EQUAL)? Initializer COMMA)* (Designator+ EQUAL)? Initializer COMMA?
fn initializers(parser: *Parser) !*Node {
@panic("TODO");
}
/// Initializer
/// <- LBRACE Initializers RBRACE
/// / AssignmentExpr
fn initializer(parser: *Parser, dr: *Node.Declarator) Error!?*Node {
@panic("TODO");
}
/// Designator
/// <- LBRACKET ConstExpr RBRACKET
/// / PERIOD IDENTIFIER
fn designator(parser: *Parser) !*Node {
@panic("TODO");
}
/// CompoundStmt <- LBRACE (Declaration / Stmt)* RBRACE
fn compoundStmt(parser: *Parser) Error!?*Node {
const lbrace = parser.eatToken(.LBrace) orelse return null;
try parser.pushScope(.Block);
defer parser.popScope();
const body_node = try parser.arena.create(Node.CompoundStmt);
body_node.* = .{
.lbrace = lbrace,
.statements = Node.CompoundStmt.StmtList.init(parser.arena),
.rbrace = undefined,
};
while (true) {
if (parser.eatToken(.RBRACE)) |rbrace| {
body_node.rbrace = rbrace;
break;
}
try body_node.statements.push((try parser.declaration()) orelse (try parser.stmt()));
}
return &body_node.base;
}
/// Stmt
/// <- CompoundStmt
/// / Keyword_if LPAREN Expr RPAREN Stmt (Keyword_ELSE Stmt)?
/// / Keyword_switch LPAREN Expr RPAREN Stmt
/// / Keyword_while LPAREN Expr RPAREN Stmt
/// / Keyword_do statement Keyword_while LPAREN Expr RPAREN SEMICOLON
/// / Keyword_for LPAREN (Declaration / ExprStmt) ExprStmt Expr? RPAREN Stmt
/// / Keyword_default COLON Stmt
/// / Keyword_case ConstExpr COLON Stmt
/// / Keyword_goto IDENTIFIER SEMICOLON
/// / Keyword_continue SEMICOLON
/// / Keyword_break SEMICOLON
/// / Keyword_return Expr? SEMICOLON
/// / IDENTIFIER COLON Stmt
/// / ExprStmt
fn stmt(parser: *Parser) Error!*Node {
if (try parser.compoundStmt()) |node| return node;
if (parser.eatToken(.Keyword_if)) |tok| {
const node = try parser.arena.create(Node.IfStmt);
_ = try parser.expectToken(.LParen);
node.* = .{
.@"if" = tok,
.cond = (try parser.expr()) orelse return parser.err(.{
.ExpectedExpr = .{ .token = parser.it.index },
}),
.body = undefined,
.@"else" = null,
};
_ = try parser.expectToken(.RParen);
node.body = try parser.stmt();
if (parser.eatToken(.Keyword_else)) |else_tok| {
node.@"else" = .{
.tok = else_tok,
.body = try parser.stmt(),
};
}
return &node.base;
}
if (parser.eatToken(.Keyword_while)) |tok| {
try parser.pushScope(.Loop);
defer parser.popScope();
_ = try parser.expectToken(.LParen);
const cond = (try parser.expr()) orelse return parser.err(.{
.ExpectedExpr = .{ .token = parser.it.index },
});
const rparen = try parser.expectToken(.RParen);
const node = try parser.arena.create(Node.WhileStmt);
node.* = .{
.@"while" = tok,
.cond = cond,
.rparen = rparen,
.body = try parser.stmt(),
.semicolon = try parser.expectToken(.Semicolon),
};
return &node.base;
}
if (parser.eatToken(.Keyword_do)) |tok| {
try parser.pushScope(.Loop);
defer parser.popScope();
const body = try parser.stmt();
_ = try parser.expectToken(.LParen);
const cond = (try parser.expr()) orelse return parser.err(.{
.ExpectedExpr = .{ .token = parser.it.index },
});
_ = try parser.expectToken(.RParen);
const node = try parser.arena.create(Node.DoStmt);
node.* = .{
.do = tok,
.body = body,
.cond = cond,
.@"while" = @"while",
.semicolon = try parser.expectToken(.Semicolon),
};
return &node.base;
}
if (parser.eatToken(.Keyword_for)) |tok| {
try parser.pushScope(.Loop);
defer parser.popScope();
_ = try parser.expectToken(.LParen);
const init = if (try parser.declaration()) |decl| blk: {
// TODO disallow storage class other than auto and register
break :blk decl;
} else try parser.exprStmt();
const cond = try parser.expr();
const semicolon = try parser.expectToken(.Semicolon);
const incr = try parser.expr();
const rparen = try parser.expectToken(.RParen);
const node = try parser.arena.create(Node.ForStmt);
node.* = .{
.@"for" = tok,
.init = init,
.cond = cond,
.semicolon = semicolon,
.incr = incr,
.rparen = rparen,
.body = try parser.stmt(),
};
return &node.base;
}
if (parser.eatToken(.Keyword_switch)) |tok| {
try parser.pushScope(.Switch);
defer parser.popScope();
_ = try parser.expectToken(.LParen);
const switch_expr = try parser.exprStmt();
const rparen = try parser.expectToken(.RParen);
const node = try parser.arena.create(Node.SwitchStmt);
node.* = .{
.@"switch" = tok,
.expr = switch_expr,
.rparen = rparen,
.body = try parser.stmt(),
};
return &node.base;
}
if (parser.eatToken(.Keyword_default)) |tok| {
_ = try parser.expectToken(.Colon);
const node = try parser.arena.create(Node.LabeledStmt);
node.* = .{
.kind = .{ .Default = tok },
.stmt = try parser.stmt(),
};
return &node.base;
}
if (parser.eatToken(.Keyword_case)) |tok| {
_ = try parser.expectToken(.Colon);
const node = try parser.arena.create(Node.LabeledStmt);
node.* = .{
.kind = .{ .Case = tok },
.stmt = try parser.stmt(),
};
return &node.base;
}
if (parser.eatToken(.Keyword_goto)) |tok| {
const node = try parser.arena.create(Node.JumpStmt);
node.* = .{
.ltoken = tok,
.kind = .{ .Goto = tok },
.semicolon = try parser.expectToken(.Semicolon),
};
return &node.base;
}
if (parser.eatToken(.Keyword_continue)) |tok| {
const node = try parser.arena.create(Node.JumpStmt);
node.* = .{
.ltoken = tok,
.kind = .Continue,
.semicolon = try parser.expectToken(.Semicolon),
};
return &node.base;
}
if (parser.eatToken(.Keyword_break)) |tok| {
const node = try parser.arena.create(Node.JumpStmt);
node.* = .{
.ltoken = tok,
.kind = .Break,
.semicolon = try parser.expectToken(.Semicolon),
};
return &node.base;
}
if (parser.eatToken(.Keyword_return)) |tok| {
const node = try parser.arena.create(Node.JumpStmt);
node.* = .{
.ltoken = tok,
.kind = .{ .Return = try parser.expr() },
.semicolon = try parser.expectToken(.Semicolon),
};
return &node.base;
}
if (parser.eatToken(.Identifier)) |tok| {
if (parser.eatToken(.Colon)) |_| {
const node = try parser.arena.create(Node.LabeledStmt);
node.* = .{
.kind = .{ .Label = tok },
.stmt = try parser.stmt(),
};
return &node.base;
}
parser.putBackToken(tok);
}
return parser.exprStmt();
}
/// ExprStmt <- Expr? SEMICOLON
fn exprStmt(parser: *Parser) !*Node {
const node = try parser.arena.create(Node.ExprStmt);
node.* = .{
.expr = try parser.expr(),
.semicolon = try parser.expectToken(.Semicolon),
};
return &node.base;
}
fn eatToken(parser: *Parser, id: @TagType(Token.Id)) ?TokenIndex {
while (true) {
switch ((parser.it.next() orelse return null).id) {
.LineComment, .MultiLineComment, .Nl => continue,
else => |next_id| if (next_id == id) {
return parser.it.index;
} else {
_ = parser.it.prev();
return null;
},
}
}
}
fn expectToken(parser: *Parser, id: @TagType(Token.Id)) Error!TokenIndex {
while (true) {
switch ((parser.it.next() orelse return error.ParseError).id) {
.LineComment, .MultiLineComment, .Nl => continue,
else => |next_id| if (next_id != id) {
return parser.err(.{
.ExpectedToken = .{ .token = parser.it.index, .expected_id = id },
});
} else {
return parser.it.index;
},
}
}
}
fn putBackToken(parser: *Parser, putting_back: TokenIndex) void {
while (true) {
const prev_tok = parser.it.next() orelse return;
switch (prev_tok.id) {
.LineComment, .MultiLineComment, .Nl => continue,
else => {
assert(parser.it.list.at(putting_back) == prev_tok);
return;
},
}
}
}
fn err(parser: *Parser, msg: ast.Error) Error {
try parser.tree.msgs.push(.{
.kind = .Error,
.inner = msg,
});
return error.ParseError;
}
fn warn(parser: *Parser, msg: ast.Error) Error!void {
const is_warning = switch (parser.options.warn_as_err) {
.None => true,
.Some => |list| for (list) |item| (if (item == msg) break false) else true,
.All => false,
};
try parser.tree.msgs.push(.{
.kind = if (is_warning) .Warning else .Error,
.inner = msg,
});
if (!is_warning) return error.ParseError;
}
fn note(parser: *Parser, msg: ast.Error) Error!void {
try parser.tree.msgs.push(.{
.kind = .Note,
.inner = msg,
});
}
}; | lib/std/c/parse.zig |
const std = @import("../../std.zig");
const builtin = @import("builtin");
const linux = std.os.linux;
const mem = std.mem;
const elf = std.elf;
const expect = std.testing.expect;
const fs = std.fs;
test "fallocate" {
const path = "test_fallocate";
const file = try fs.cwd().createFile(path, .{ .truncate = true, .mode = 0o666 });
defer file.close();
defer fs.cwd().deleteFile(path) catch {};
expect((try file.stat()).size == 0);
const len: u64 = 65536;
switch (linux.getErrno(linux.fallocate(file.handle, 0, 0, len))) {
0 => {},
linux.ENOSYS => return error.SkipZigTest,
linux.EOPNOTSUPP => return error.SkipZigTest,
else => |errno| std.debug.panic("unhandled errno: {}", .{errno}),
}
expect((try file.stat()).size == len);
}
test "getpid" {
expect(linux.getpid() != 0);
}
test "timer" {
const epoll_fd = linux.epoll_create();
var err: usize = linux.getErrno(epoll_fd);
expect(err == 0);
const timer_fd = linux.timerfd_create(linux.CLOCK_MONOTONIC, 0);
expect(linux.getErrno(timer_fd) == 0);
const time_interval = linux.timespec{
.tv_sec = 0,
.tv_nsec = 2000000,
};
const new_time = linux.itimerspec{
.it_interval = time_interval,
.it_value = time_interval,
};
err = linux.timerfd_settime(@intCast(i32, timer_fd), 0, &new_time, null);
expect(err == 0);
var event = linux.epoll_event{
.events = linux.EPOLLIN | linux.EPOLLOUT | linux.EPOLLET,
.data = linux.epoll_data{ .ptr = 0 },
};
err = linux.epoll_ctl(@intCast(i32, epoll_fd), linux.EPOLL_CTL_ADD, @intCast(i32, timer_fd), &event);
expect(err == 0);
const events_one: linux.epoll_event = undefined;
var events = [_]linux.epoll_event{events_one} ** 8;
// TODO implicit cast from *[N]T to [*]T
err = linux.epoll_wait(@intCast(i32, epoll_fd), @ptrCast([*]linux.epoll_event, &events), 8, -1);
}
test "statx" {
const tmp_file_name = "just_a_temporary_file.txt";
var file = try fs.cwd().createFile(tmp_file_name, .{});
defer {
file.close();
fs.cwd().deleteFile(tmp_file_name) catch {};
}
var statx_buf: linux.Statx = undefined;
switch (linux.getErrno(linux.statx(file.handle, "", linux.AT_EMPTY_PATH, linux.STATX_BASIC_STATS, &statx_buf))) {
0 => {},
// The statx syscall was only introduced in linux 4.11
linux.ENOSYS => return error.SkipZigTest,
else => unreachable,
}
var stat_buf: linux.kernel_stat = undefined;
switch (linux.getErrno(linux.fstatat(file.handle, "", &stat_buf, linux.AT_EMPTY_PATH))) {
0 => {},
else => unreachable,
}
expect(stat_buf.mode == statx_buf.mode);
expect(@bitCast(u32, stat_buf.uid) == statx_buf.uid);
expect(@bitCast(u32, stat_buf.gid) == statx_buf.gid);
expect(@bitCast(u64, @as(i64, stat_buf.size)) == statx_buf.size);
expect(@bitCast(u64, @as(i64, stat_buf.blksize)) == statx_buf.blksize);
expect(@bitCast(u64, @as(i64, stat_buf.blocks)) == statx_buf.blocks);
} | lib/std/os/linux/test.zig |
const Object = @This();
const std = @import("std");
const build_options = @import("build_options");
const assert = std.debug.assert;
const dwarf = std.dwarf;
const fs = std.fs;
const io = std.io;
const log = std.log.scoped(.link);
const macho = std.macho;
const math = std.math;
const mem = std.mem;
const sort = std.sort;
const commands = @import("commands.zig");
const segmentName = commands.segmentName;
const sectionName = commands.sectionName;
const trace = @import("../../tracy.zig").trace;
const Allocator = mem.Allocator;
const Atom = @import("Atom.zig");
const LoadCommand = commands.LoadCommand;
const MachO = @import("../MachO.zig");
file: fs.File,
name: []const u8,
file_offset: ?u32 = null,
header: ?macho.mach_header_64 = null,
load_commands: std.ArrayListUnmanaged(LoadCommand) = .{},
segment_cmd_index: ?u16 = null,
text_section_index: ?u16 = null,
symtab_cmd_index: ?u16 = null,
dysymtab_cmd_index: ?u16 = null,
build_version_cmd_index: ?u16 = null,
data_in_code_cmd_index: ?u16 = null,
// __DWARF segment sections
dwarf_debug_info_index: ?u16 = null,
dwarf_debug_abbrev_index: ?u16 = null,
dwarf_debug_str_index: ?u16 = null,
dwarf_debug_line_index: ?u16 = null,
dwarf_debug_ranges_index: ?u16 = null,
symtab: std.ArrayListUnmanaged(macho.nlist_64) = .{},
strtab: std.ArrayListUnmanaged(u8) = .{},
data_in_code_entries: std.ArrayListUnmanaged(macho.data_in_code_entry) = .{},
// Debug info
debug_info: ?DebugInfo = null,
tu_name: ?[]const u8 = null,
tu_comp_dir: ?[]const u8 = null,
mtime: ?u64 = null,
contained_atoms: std.ArrayListUnmanaged(*Atom) = .{},
start_atoms: std.AutoHashMapUnmanaged(MachO.MatchingSection, *Atom) = .{},
end_atoms: std.AutoHashMapUnmanaged(MachO.MatchingSection, *Atom) = .{},
sections_as_symbols: std.AutoHashMapUnmanaged(u16, u32) = .{},
// TODO symbol mapping and its inverse can probably be simple arrays
// instead of hash maps.
symbol_mapping: std.AutoHashMapUnmanaged(u32, u32) = .{},
reverse_symbol_mapping: std.AutoHashMapUnmanaged(u32, u32) = .{},
analyzed: bool = false,
const DebugInfo = struct {
inner: dwarf.DwarfInfo,
debug_info: []u8,
debug_abbrev: []u8,
debug_str: []u8,
debug_line: []u8,
debug_ranges: []u8,
pub fn parseFromObject(allocator: *Allocator, object: *const Object) !?DebugInfo {
var debug_info = blk: {
const index = object.dwarf_debug_info_index orelse return null;
break :blk try object.readSection(allocator, index);
};
var debug_abbrev = blk: {
const index = object.dwarf_debug_abbrev_index orelse return null;
break :blk try object.readSection(allocator, index);
};
var debug_str = blk: {
const index = object.dwarf_debug_str_index orelse return null;
break :blk try object.readSection(allocator, index);
};
var debug_line = blk: {
const index = object.dwarf_debug_line_index orelse return null;
break :blk try object.readSection(allocator, index);
};
var debug_ranges = blk: {
if (object.dwarf_debug_ranges_index) |ind| {
break :blk try object.readSection(allocator, ind);
}
break :blk try allocator.alloc(u8, 0);
};
var inner: dwarf.DwarfInfo = .{
.endian = .Little,
.debug_info = debug_info,
.debug_abbrev = debug_abbrev,
.debug_str = debug_str,
.debug_line = debug_line,
.debug_ranges = debug_ranges,
};
try dwarf.openDwarfDebugInfo(&inner, allocator);
return DebugInfo{
.inner = inner,
.debug_info = debug_info,
.debug_abbrev = debug_abbrev,
.debug_str = debug_str,
.debug_line = debug_line,
.debug_ranges = debug_ranges,
};
}
pub fn deinit(self: *DebugInfo, allocator: *Allocator) void {
allocator.free(self.debug_info);
allocator.free(self.debug_abbrev);
allocator.free(self.debug_str);
allocator.free(self.debug_line);
allocator.free(self.debug_ranges);
self.inner.abbrev_table_list.deinit();
self.inner.compile_unit_list.deinit();
self.inner.func_list.deinit();
}
};
pub fn deinit(self: *Object, allocator: *Allocator) void {
for (self.load_commands.items) |*lc| {
lc.deinit(allocator);
}
self.load_commands.deinit(allocator);
self.data_in_code_entries.deinit(allocator);
self.symtab.deinit(allocator);
self.strtab.deinit(allocator);
self.sections_as_symbols.deinit(allocator);
self.symbol_mapping.deinit(allocator);
self.reverse_symbol_mapping.deinit(allocator);
allocator.free(self.name);
self.contained_atoms.deinit(allocator);
self.start_atoms.deinit(allocator);
self.end_atoms.deinit(allocator);
if (self.debug_info) |*db| {
db.deinit(allocator);
}
if (self.tu_name) |n| {
allocator.free(n);
}
if (self.tu_comp_dir) |n| {
allocator.free(n);
}
}
pub fn free(self: *Object, allocator: *Allocator, macho_file: *MachO) void {
log.debug("freeObject {*}", .{self});
var it = self.end_atoms.iterator();
while (it.next()) |entry| {
const match = entry.key_ptr.*;
const first_atom = self.start_atoms.get(match).?;
const last_atom = entry.value_ptr.*;
var atom = first_atom;
while (true) {
if (atom.local_sym_index != 0) {
macho_file.locals_free_list.append(allocator, atom.local_sym_index) catch {};
const local = &macho_file.locals.items[atom.local_sym_index];
local.* = .{
.n_strx = 0,
.n_type = 0,
.n_sect = 0,
.n_desc = 0,
.n_value = 0,
};
atom.local_sym_index = 0;
}
if (atom == last_atom) {
break;
}
if (atom.next) |next| {
atom = next;
} else break;
}
}
self.freeAtoms(macho_file);
}
fn freeAtoms(self: *Object, macho_file: *MachO) void {
var it = self.end_atoms.iterator();
while (it.next()) |entry| {
const match = entry.key_ptr.*;
var first_atom: *Atom = self.start_atoms.get(match).?;
var last_atom: *Atom = entry.value_ptr.*;
if (macho_file.atoms.getPtr(match)) |atom_ptr| {
if (atom_ptr.* == last_atom) {
if (first_atom.prev) |prev| {
// TODO shrink the section size here
atom_ptr.* = prev;
} else {
_ = macho_file.atoms.fetchRemove(match);
}
}
}
if (first_atom.prev) |prev| {
prev.next = last_atom.next;
} else {
first_atom.prev = null;
}
if (last_atom.next) |next| {
next.prev = last_atom.prev;
} else {
last_atom.next = null;
}
}
}
pub fn parse(self: *Object, allocator: *Allocator, target: std.Target) !void {
const reader = self.file.reader();
if (self.file_offset) |offset| {
try reader.context.seekTo(offset);
}
const header = try reader.readStruct(macho.mach_header_64);
if (header.filetype != macho.MH_OBJECT) {
log.debug("invalid filetype: expected 0x{x}, found 0x{x}", .{
macho.MH_OBJECT,
header.filetype,
});
return error.NotObject;
}
const this_arch: std.Target.Cpu.Arch = switch (header.cputype) {
macho.CPU_TYPE_ARM64 => .aarch64,
macho.CPU_TYPE_X86_64 => .x86_64,
else => |value| {
log.err("unsupported cpu architecture 0x{x}", .{value});
return error.UnsupportedCpuArchitecture;
},
};
if (this_arch != target.cpu.arch) {
log.err("mismatched cpu architecture: expected {s}, found {s}", .{ target.cpu.arch, this_arch });
return error.MismatchedCpuArchitecture;
}
self.header = header;
try self.readLoadCommands(allocator, reader);
try self.parseSymtab(allocator);
try self.parseDataInCode(allocator);
try self.parseDebugInfo(allocator);
}
pub fn readLoadCommands(self: *Object, allocator: *Allocator, reader: anytype) !void {
const header = self.header orelse unreachable; // Unreachable here signifies a fatal unexplored condition.
const offset = self.file_offset orelse 0;
try self.load_commands.ensureTotalCapacity(allocator, header.ncmds);
var i: u16 = 0;
while (i < header.ncmds) : (i += 1) {
var cmd = try LoadCommand.read(allocator, reader);
switch (cmd.cmd()) {
macho.LC_SEGMENT_64 => {
self.segment_cmd_index = i;
var seg = cmd.Segment;
for (seg.sections.items) |*sect, j| {
const index = @intCast(u16, j);
const segname = segmentName(sect.*);
const sectname = sectionName(sect.*);
if (mem.eql(u8, segname, "__DWARF")) {
if (mem.eql(u8, sectname, "__debug_info")) {
self.dwarf_debug_info_index = index;
} else if (mem.eql(u8, sectname, "__debug_abbrev")) {
self.dwarf_debug_abbrev_index = index;
} else if (mem.eql(u8, sectname, "__debug_str")) {
self.dwarf_debug_str_index = index;
} else if (mem.eql(u8, sectname, "__debug_line")) {
self.dwarf_debug_line_index = index;
} else if (mem.eql(u8, sectname, "__debug_ranges")) {
self.dwarf_debug_ranges_index = index;
}
} else if (mem.eql(u8, segname, "__TEXT")) {
if (mem.eql(u8, sectname, "__text")) {
self.text_section_index = index;
}
}
sect.offset += offset;
if (sect.reloff > 0) {
sect.reloff += offset;
}
}
seg.inner.fileoff += offset;
},
macho.LC_SYMTAB => {
self.symtab_cmd_index = i;
cmd.Symtab.symoff += offset;
cmd.Symtab.stroff += offset;
},
macho.LC_DYSYMTAB => {
self.dysymtab_cmd_index = i;
},
macho.LC_BUILD_VERSION => {
self.build_version_cmd_index = i;
},
macho.LC_DATA_IN_CODE => {
self.data_in_code_cmd_index = i;
cmd.LinkeditData.dataoff += offset;
},
else => {
log.debug("Unknown load command detected: 0x{x}.", .{cmd.cmd()});
},
}
self.load_commands.appendAssumeCapacity(cmd);
}
}
const NlistWithIndex = struct {
nlist: macho.nlist_64,
index: u32,
fn lessThan(_: void, lhs: NlistWithIndex, rhs: NlistWithIndex) bool {
// We sort by type: defined < undefined, and
// afterwards by address in each group. Normally, dysymtab should
// be enough to guarantee the sort, but turns out not every compiler
// is kind enough to specify the symbols in the correct order.
if (MachO.symbolIsSect(lhs.nlist)) {
if (MachO.symbolIsSect(rhs.nlist)) {
// Same group, sort by address.
return lhs.nlist.n_value < rhs.nlist.n_value;
} else {
return true;
}
} else {
return false;
}
}
fn filterInSection(symbols: []NlistWithIndex, sect: macho.section_64) []NlistWithIndex {
const Predicate = struct {
addr: u64,
pub fn predicate(self: @This(), symbol: NlistWithIndex) bool {
return symbol.nlist.n_value >= self.addr;
}
};
const start = MachO.findFirst(NlistWithIndex, symbols, 0, Predicate{ .addr = sect.addr });
const end = MachO.findFirst(NlistWithIndex, symbols, start, Predicate{ .addr = sect.addr + sect.size });
return symbols[start..end];
}
};
fn filterDice(dices: []macho.data_in_code_entry, start_addr: u64, end_addr: u64) []macho.data_in_code_entry {
const Predicate = struct {
addr: u64,
pub fn predicate(self: @This(), dice: macho.data_in_code_entry) bool {
return dice.offset >= self.addr;
}
};
const start = MachO.findFirst(macho.data_in_code_entry, dices, 0, Predicate{ .addr = start_addr });
const end = MachO.findFirst(macho.data_in_code_entry, dices, start, Predicate{ .addr = end_addr });
return dices[start..end];
}
pub fn parseIntoAtoms(self: *Object, allocator: *Allocator, macho_file: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
const seg = self.load_commands.items[self.segment_cmd_index.?].Segment;
log.debug("analysing {s}", .{self.name});
// You would expect that the symbol table is at least pre-sorted based on symbol's type:
// local < extern defined < undefined. Unfortunately, this is not guaranteed! For instance,
// the GO compiler does not necessarily respect that therefore we sort immediately by type
// and address within.
var sorted_all_nlists = std.ArrayList(NlistWithIndex).init(allocator);
defer sorted_all_nlists.deinit();
try sorted_all_nlists.ensureTotalCapacity(self.symtab.items.len);
for (self.symtab.items) |nlist, index| {
sorted_all_nlists.appendAssumeCapacity(.{
.nlist = nlist,
.index = @intCast(u32, index),
});
}
sort.sort(NlistWithIndex, sorted_all_nlists.items, {}, NlistWithIndex.lessThan);
// Well, shit, sometimes compilers skip the dysymtab load command altogether, meaning we
// have to infer the start of undef section in the symtab ourselves.
const iundefsym = if (self.dysymtab_cmd_index) |cmd_index| blk: {
const dysymtab = self.load_commands.items[cmd_index].Dysymtab;
break :blk dysymtab.iundefsym;
} else blk: {
var iundefsym: usize = sorted_all_nlists.items.len;
while (iundefsym > 0) : (iundefsym -= 1) {
const nlist = sorted_all_nlists.items[iundefsym];
if (MachO.symbolIsSect(nlist.nlist)) break;
}
break :blk iundefsym;
};
// We only care about defined symbols, so filter every other out.
const sorted_nlists = sorted_all_nlists.items[0..iundefsym];
for (seg.sections.items) |sect, id| {
const sect_id = @intCast(u8, id);
log.debug("putting section '{s},{s}' as an Atom", .{
segmentName(sect),
sectionName(sect),
});
// Get matching segment/section in the final artifact.
const match = (try macho_file.getMatchingSection(sect)) orelse {
log.debug("unhandled section", .{});
continue;
};
// Read section's code
var code = try allocator.alloc(u8, @intCast(usize, sect.size));
defer allocator.free(code);
_ = try self.file.preadAll(code, sect.offset);
// Read section's list of relocations
var raw_relocs = try allocator.alloc(u8, sect.nreloc * @sizeOf(macho.relocation_info));
defer allocator.free(raw_relocs);
_ = try self.file.preadAll(raw_relocs, sect.reloff);
const relocs = mem.bytesAsSlice(macho.relocation_info, raw_relocs);
// Symbols within this section only.
const filtered_nlists = NlistWithIndex.filterInSection(sorted_nlists, sect);
macho_file.has_dices = macho_file.has_dices or blk: {
if (self.text_section_index) |index| {
if (index != id) break :blk false;
if (self.data_in_code_entries.items.len == 0) break :blk false;
break :blk true;
}
break :blk false;
};
macho_file.has_stabs = macho_file.has_stabs or self.debug_info != null;
// Since there is no symbol to refer to this atom, we create
// a temp one, unless we already did that when working out the relocations
// of other atoms.
const atom_local_sym_index = self.sections_as_symbols.get(sect_id) orelse blk: {
const atom_local_sym_index = @intCast(u32, macho_file.locals.items.len);
try macho_file.locals.append(allocator, .{
.n_strx = 0,
.n_type = macho.N_SECT,
.n_sect = @intCast(u8, macho_file.section_ordinals.getIndex(match).? + 1),
.n_desc = 0,
.n_value = 0,
});
try self.sections_as_symbols.putNoClobber(allocator, sect_id, atom_local_sym_index);
break :blk atom_local_sym_index;
};
const atom = try macho_file.createEmptyAtom(atom_local_sym_index, sect.size, sect.@"align");
const is_zerofill = blk: {
const section_type = commands.sectionType(sect);
break :blk section_type == macho.S_ZEROFILL or section_type == macho.S_THREAD_LOCAL_ZEROFILL;
};
if (!is_zerofill) {
mem.copy(u8, atom.code.items, code);
}
try atom.parseRelocs(relocs, .{
.base_addr = sect.addr,
.allocator = allocator,
.object = self,
.macho_file = macho_file,
});
if (macho_file.has_dices) {
const dices = filterDice(self.data_in_code_entries.items, sect.addr, sect.addr + sect.size);
try atom.dices.ensureTotalCapacity(allocator, dices.len);
for (dices) |dice| {
atom.dices.appendAssumeCapacity(.{
.offset = dice.offset - try math.cast(u32, sect.addr),
.length = dice.length,
.kind = dice.kind,
});
}
}
// Since this is atom gets a helper local temporary symbol that didn't exist
// in the object file which encompasses the entire section, we need traverse
// the filtered symbols and note which symbol is contained within so that
// we can properly allocate addresses down the line.
// While we're at it, we need to update segment,section mapping of each symbol too.
try atom.contained.ensureTotalCapacity(allocator, filtered_nlists.len);
for (filtered_nlists) |nlist_with_index| {
const nlist = nlist_with_index.nlist;
const local_sym_index = self.symbol_mapping.get(nlist_with_index.index) orelse unreachable;
const local = &macho_file.locals.items[local_sym_index];
local.n_sect = @intCast(u8, macho_file.section_ordinals.getIndex(match).? + 1);
const stab: ?Atom.Stab = if (self.debug_info) |di| blk: {
// TODO there has to be a better to handle this.
for (di.inner.func_list.items) |func| {
if (func.pc_range) |range| {
if (nlist.n_value >= range.start and nlist.n_value < range.end) {
break :blk Atom.Stab{
.function = range.end - range.start,
};
}
}
}
// TODO
// if (zld.globals.contains(zld.getString(sym.strx))) break :blk .global;
break :blk .static;
} else null;
atom.contained.appendAssumeCapacity(.{
.local_sym_index = local_sym_index,
.offset = nlist.n_value - sect.addr,
.stab = stab,
});
}
if (!self.start_atoms.contains(match)) {
try self.start_atoms.putNoClobber(allocator, match, atom);
}
if (self.end_atoms.getPtr(match)) |last| {
last.*.next = atom;
atom.prev = last.*;
last.* = atom;
} else {
try self.end_atoms.putNoClobber(allocator, match, atom);
}
try self.contained_atoms.append(allocator, atom);
}
}
fn parseSymtab(self: *Object, allocator: *Allocator) !void {
const index = self.symtab_cmd_index orelse return;
const symtab_cmd = self.load_commands.items[index].Symtab;
var symtab = try allocator.alloc(u8, @sizeOf(macho.nlist_64) * symtab_cmd.nsyms);
defer allocator.free(symtab);
_ = try self.file.preadAll(symtab, symtab_cmd.symoff);
const slice = @alignCast(@alignOf(macho.nlist_64), mem.bytesAsSlice(macho.nlist_64, symtab));
try self.symtab.appendSlice(allocator, slice);
var strtab = try allocator.alloc(u8, symtab_cmd.strsize);
defer allocator.free(strtab);
_ = try self.file.preadAll(strtab, symtab_cmd.stroff);
try self.strtab.appendSlice(allocator, strtab);
}
pub fn parseDebugInfo(self: *Object, allocator: *Allocator) !void {
log.debug("parsing debug info in '{s}'", .{self.name});
var debug_info = blk: {
var di = try DebugInfo.parseFromObject(allocator, self);
break :blk di orelse return;
};
// We assume there is only one CU.
const compile_unit = debug_info.inner.findCompileUnit(0x0) catch |err| switch (err) {
error.MissingDebugInfo => {
// TODO audit cases with missing debug info and audit our dwarf.zig module.
log.debug("invalid or missing debug info in {s}; skipping", .{self.name});
return;
},
else => |e| return e,
};
const name = try compile_unit.die.getAttrString(&debug_info.inner, dwarf.AT.name);
const comp_dir = try compile_unit.die.getAttrString(&debug_info.inner, dwarf.AT.comp_dir);
self.debug_info = debug_info;
self.tu_name = try allocator.dupe(u8, name);
self.tu_comp_dir = try allocator.dupe(u8, comp_dir);
if (self.mtime == null) {
self.mtime = mtime: {
const stat = self.file.stat() catch break :mtime 0;
break :mtime @intCast(u64, @divFloor(stat.mtime, 1_000_000_000));
};
}
}
pub fn parseDataInCode(self: *Object, allocator: *Allocator) !void {
const index = self.data_in_code_cmd_index orelse return;
const data_in_code = self.load_commands.items[index].LinkeditData;
var buffer = try allocator.alloc(u8, data_in_code.datasize);
defer allocator.free(buffer);
_ = try self.file.preadAll(buffer, data_in_code.dataoff);
var stream = io.fixedBufferStream(buffer);
var reader = stream.reader();
while (true) {
const dice = reader.readStruct(macho.data_in_code_entry) catch |err| switch (err) {
error.EndOfStream => break,
else => |e| return e,
};
try self.data_in_code_entries.append(allocator, dice);
}
}
fn readSection(self: Object, allocator: *Allocator, index: u16) ![]u8 {
const seg = self.load_commands.items[self.segment_cmd_index.?].Segment;
const sect = seg.sections.items[index];
var buffer = try allocator.alloc(u8, @intCast(usize, sect.size));
_ = try self.file.preadAll(buffer, sect.offset);
return buffer;
}
pub fn getString(self: Object, off: u32) []const u8 {
assert(off < self.strtab.items.len);
return mem.spanZ(@ptrCast([*:0]const u8, self.strtab.items.ptr + off));
} | src/link/MachO/Object.zig |
const std = @import("std");
const mem = std.mem;
const Allocator = mem.Allocator;
const testing = std.testing;
const builtin = @import("builtin");
const assert = std.debug.assert;
/// An entity ID uniquely identifies an entity globally within an Entities set.
pub const EntityID = u64;
/// Represents the storage for a single type of component within a single type of entity.
///
/// Database equivalent: a column within a table.
pub fn ComponentStorage(comptime Component: type) type {
return struct {
/// A reference to the total number of entities with the same type as is being stored here.
total_rows: *usize,
/// The actual component data. This starts as empty, and then based on the first call to
/// .set() or .setDense() is initialized as dense storage (an array) or sparse storage (a
/// hashmap.)
///
/// Sparse storage may turn to dense storage if someone later calls .set(), see that method
/// for details.
data: std.ArrayListUnmanaged(Component) = .{},
const Self = @This();
pub fn deinit(storage: *Self, allocator: Allocator) void {
storage.data.deinit(allocator);
}
// If the storage of this component is sparse, it is turned dense as calling this method
// indicates that the caller expects to set this component for most entities rather than
// sparsely.
pub fn set(storage: *Self, allocator: Allocator, row_index: u32, component: Component) !void {
if (storage.data.items.len <= row_index) try storage.data.appendNTimes(allocator, undefined, storage.data.items.len + 1 - row_index);
storage.data.items[row_index] = component;
}
/// Removes the given row index.
pub fn remove(storage: *Self, row_index: u32) void {
if (storage.data.items.len > row_index) {
_ = storage.data.swapRemove(row_index);
}
}
/// Gets the component value for the given entity ID.
pub inline fn get(storage: Self, row_index: u32) Component {
return storage.data.items[row_index];
}
pub inline fn copy(dst: *Self, allocator: Allocator, src_row: u32, dst_row: u32, src: *Self) !void {
try dst.set(allocator, dst_row, src.get(src_row));
}
pub inline fn copySparse(dst: *Self, allocator: Allocator, src_row: u32, dst_row: u32, src: *Self) !void {
// TODO: setSparse!
try dst.set(allocator, dst_row, src.get(src_row));
}
};
}
/// A type-erased representation of ComponentStorage(T) (where T is unknown).
///
/// This is useful as it allows us to store all of the typed ComponentStorage as values in a hashmap
/// despite having different types, and allows us to still deinitialize them without knowing the
/// underlying type.
pub const ErasedComponentStorage = struct {
ptr: *anyopaque,
deinit: fn (erased: *anyopaque, allocator: Allocator) void,
remove: fn (erased: *anyopaque, row: u32) void,
cloneType: fn (erased: ErasedComponentStorage, total_entities: *usize, allocator: Allocator, retval: *ErasedComponentStorage) error{OutOfMemory}!void,
copy: fn (dst_erased: *anyopaque, allocator: Allocator, src_row: u32, dst_row: u32, src_erased: *anyopaque) error{OutOfMemory}!void,
copySparse: fn (dst_erased: *anyopaque, allocator: Allocator, src_row: u32, dst_row: u32, src_erased: *anyopaque) error{OutOfMemory}!void,
pub fn cast(ptr: *anyopaque, comptime Component: type) *ComponentStorage(Component) {
var aligned = @alignCast(@alignOf(*ComponentStorage(Component)), ptr);
return @ptrCast(*ComponentStorage(Component), aligned);
}
};
/// Represents a single archetype, that is, entities which have the same exact set of component
/// types. When a component is added or removed from an entity, it's archetype changes.
///
/// Database equivalent: a table where rows are entities and columns are components (dense storage).
pub const ArchetypeStorage = struct {
allocator: Allocator,
/// The hash of every component name in this archetype, i.e. the name of this archetype.
hash: u64,
/// A mapping of rows in the table to entity IDs.
///
/// Doubles as the counter of total number of rows that have been reserved within this
/// archetype table.
entity_ids: std.ArrayListUnmanaged(EntityID) = .{},
/// A string hashmap of component_name -> type-erased *ComponentStorage(Component)
components: std.StringArrayHashMapUnmanaged(ErasedComponentStorage),
/// Calculates the storage.hash value. This is a hash of all the component names, and can
/// effectively be used to uniquely identify this table within the database.
pub fn calculateHash(storage: *ArchetypeStorage) void {
storage.hash = 0;
var iter = storage.components.iterator();
while (iter.next()) |entry| {
const component_name = entry.key_ptr.*;
storage.hash ^= std.hash_map.hashString(component_name);
}
}
pub fn deinit(storage: *ArchetypeStorage) void {
for (storage.components.values()) |erased| {
erased.deinit(erased.ptr, storage.allocator);
}
storage.entity_ids.deinit(storage.allocator);
storage.components.deinit(storage.allocator);
}
/// New reserves a row for storing an entity within this archetype table.
pub fn new(storage: *ArchetypeStorage, entity: EntityID) !u32 {
// Return a new row index
const new_row_index = storage.entity_ids.items.len;
try storage.entity_ids.append(storage.allocator, entity);
return @intCast(u32, new_row_index);
}
/// Undoes the last call to the new() operation, effectively unreserving the row that was last
/// reserved.
pub fn undoNew(storage: *ArchetypeStorage) void {
_ = storage.entity_ids.pop();
}
/// Sets the value of the named component (column) for the given row in the table. Realizes the
/// deferred allocation of column storage for N entities (storage.counter) if it is not already.
pub fn set(storage: *ArchetypeStorage, row_index: u32, name: []const u8, component: anytype) !void {
var component_storage_erased = storage.components.get(name).?;
var component_storage = ErasedComponentStorage.cast(component_storage_erased.ptr, @TypeOf(component));
try component_storage.set(storage.allocator, row_index, component);
}
/// Removes the specified row. See also the `Entity.delete()` helper.
///
/// This merely marks the row as removed, the same row index will be recycled the next time a
/// new row is requested via `new()`.
pub fn remove(storage: *ArchetypeStorage, row_index: u32) !void {
_ = storage.entity_ids.swapRemove(row_index);
for (storage.components.values()) |component_storage| {
component_storage.remove(component_storage.ptr, row_index);
}
}
/// The number of entities actively stored in this table (not counting entities which are
/// allocated in this table but have been removed)
pub fn count(storage: *ArchetypeStorage) usize {
return storage.entity_ids.items.len;
}
/// Tells if this archetype has every one of the given components.
pub fn hasComponents(storage: *ArchetypeStorage, components: []const []const u8) bool {
for (components) |component_name| {
if (!storage.components.contains(component_name)) return false;
}
return true;
}
};
pub const void_archetype_hash = std.math.maxInt(u64);
/// A database of entities. For example, all player, monster, etc. entities in a game world.
///
/// ```
/// const world = Entities.init(allocator); // all entities in our world.
/// defer world.deinit();
///
/// const player1 = world.new(); // our first "player" entity
/// const player2 = world.new(); // our second "player" entity
/// ```
///
/// Entities are divided into archetypes for optimal, CPU cache efficient storage. For example, all
/// entities with two components `Location` and `Name` are stored in the same table dedicated to
/// densely storing `(Location, Name)` rows in contiguous memory. This not only ensures CPU cache
/// efficiency (leveraging data oriented design) which improves iteration speed over entities for
/// example, but makes queries like "find all entities with a Location component" ridiculously fast
/// because one need only find the tables which have a column for storing Location components and it
/// is then guaranteed every entity in the table has that component (entities do not need to be
/// checked one by one to determine if they have a Location component.)
///
/// Components can be added and removed to entities at runtime as you please:
///
/// ```
/// try player1.set("rotation", Rotation{ .degrees = 90 });
/// try player1.remove("rotation");
/// ```
///
/// When getting a component value, you must know it's type or undefined behavior will occur:
/// TODO: improve this!
///
/// ```
/// if (player1.get("rotation", Rotation)) |rotation| {
/// // player1 had a rotation component!
/// }
/// ```
///
/// When a component is added or removed from an entity, it's archetype is said to change. For
/// example player1 may have had the archetype `(Location, Name)` before, and after adding the
/// rotation component has the archetype `(Location, Name, Rotation)`. It will be automagically
/// "moved" from the table that stores entities with `(Location, Name)` components to the table that
/// stores `(Location, Name, Rotation)` components for you.
///
/// You can have 65,535 archetypes in total, and 4,294,967,295 entities total. Entities which are
/// deleted are merely marked as "unused" and recycled
///
/// Database equivalents:
/// * Entities is a database of tables, where each table represents a single archetype.
/// * ArchetypeStorage is a table, whose rows are entities and columns are components.
/// * EntityID is a mere 32-bit array index, pointing to a 16-bit archetype table index and 32-bit
/// row index, enabling entities to "move" from one archetype table to another seamlessly and
/// making lookup by entity ID a few cheap array indexing operations.
/// * ComponentStorage(T) is a column of data within a table for a single type of component `T`.
pub const Entities = struct {
allocator: Allocator,
/// TODO!
counter: EntityID = 0,
/// A mapping of entity IDs (array indices) to where an entity's component values are actually
/// stored.
entities: std.AutoHashMapUnmanaged(EntityID, Pointer) = .{},
/// A mapping of archetype hash to their storage.
///
/// Database equivalent: table name -> tables representing entities.
archetypes: std.AutoArrayHashMapUnmanaged(u64, ArchetypeStorage) = .{},
/// Points to where an entity is stored, specifically in which archetype table and in which row
/// of that table. That is, the entity's component values are stored at:
///
/// ```
/// Entities.archetypes[ptr.archetype_index].rows[ptr.row_index]
/// ```
///
pub const Pointer = struct {
archetype_index: u16,
row_index: u32,
};
pub const Iterator = struct {
entities: *Entities,
components: []const []const u8,
archetype_index: usize = 0,
row_index: usize = 0,
pub const Entry = struct {
entity: EntityID,
pub fn unlock(e: Entry) void {
_ = e;
}
};
pub fn next(iter: *Iterator) ?Entry {
const entities = iter.entities;
// If the archetype table we're looking at does not contain the components we're
// querying for, keep searching through tables until we find one that does.
var archetype = entities.archetypes.entries.get(iter.archetype_index).value;
while (!archetype.hasComponents(iter.components) or iter.row_index >= archetype.count()) {
iter.archetype_index += 1;
iter.row_index = 0;
if (iter.archetype_index >= entities.archetypes.count()) {
return null;
}
archetype = entities.archetypes.entries.get(iter.archetype_index).value;
}
const row_entity_id = archetype.entity_ids.items[iter.row_index];
iter.row_index += 1;
return Entry{ .entity = row_entity_id };
}
};
pub fn query(entities: *Entities, components: []const []const u8) Iterator {
return Iterator{
.entities = entities,
.components = components,
};
}
pub fn init(allocator: Allocator) !Entities {
var entities = Entities{ .allocator = allocator };
try entities.archetypes.put(allocator, void_archetype_hash, ArchetypeStorage{
.allocator = allocator,
.components = .{},
.hash = void_archetype_hash,
});
return entities;
}
pub fn deinit(entities: *Entities) void {
entities.entities.deinit(entities.allocator);
var iter = entities.archetypes.iterator();
while (iter.next()) |entry| {
entry.value_ptr.deinit();
}
entities.archetypes.deinit(entities.allocator);
}
/// Returns a new entity.
pub fn new(entities: *Entities) !EntityID {
const new_id = entities.counter;
entities.counter += 1;
var void_archetype = entities.archetypes.getPtr(void_archetype_hash).?;
const new_row = try void_archetype.new(new_id);
const void_pointer = Pointer{
.archetype_index = 0, // void archetype is guaranteed to be first index
.row_index = new_row,
};
entities.entities.put(entities.allocator, new_id, void_pointer) catch |err| {
void_archetype.undoNew();
return err;
};
return new_id;
}
/// Removes an entity.
pub fn remove(entities: *Entities, entity: EntityID) !void {
var archetype = entities.archetypeByID(entity);
const ptr = entities.entities.get(entity).?;
// A swap removal will be performed, update the entity stored in the last row of the
// archetype table to point to the row the entity we are removing is currently located.
const last_row_entity_id = archetype.entity_ids.items[archetype.entity_ids.items.len - 1];
try entities.entities.put(entities.allocator, last_row_entity_id, Pointer{
.archetype_index = ptr.archetype_index,
.row_index = ptr.row_index,
});
// Perform a swap removal to remove our entity from the archetype table.
try archetype.remove(ptr.row_index);
_ = entities.entities.remove(entity);
}
/// Returns the archetype storage for the given entity.
pub inline fn archetypeByID(entities: *Entities, entity: EntityID) *ArchetypeStorage {
const ptr = entities.entities.get(entity).?;
return &entities.archetypes.values()[ptr.archetype_index];
}
/// Sets the named component to the specified value for the given entity,
/// moving the entity from it's current archetype table to the new archetype
/// table if required.
pub fn setComponent(entities: *Entities, entity: EntityID, name: []const u8, component: anytype) !void {
var archetype = entities.archetypeByID(entity);
// Determine the old hash for the archetype.
const old_hash = archetype.hash;
// Determine the new hash for the archetype + new component
var have_already = archetype.components.contains(name);
const new_hash = if (have_already) old_hash else old_hash ^ std.hash_map.hashString(name);
// Find the archetype storage for this entity. Could be a new archetype storage table (if a
// new component was added), or the same archetype storage table (if just updating the
// value of a component.)
var archetype_entry = try entities.archetypes.getOrPut(entities.allocator, new_hash);
if (!archetype_entry.found_existing) {
archetype_entry.value_ptr.* = ArchetypeStorage{
.allocator = entities.allocator,
.components = .{},
.hash = 0,
};
var new_archetype = archetype_entry.value_ptr;
// Create storage/columns for all of the existing components on the entity.
var column_iter = archetype.components.iterator();
while (column_iter.next()) |entry| {
var erased: ErasedComponentStorage = undefined;
entry.value_ptr.cloneType(entry.value_ptr.*, &new_archetype.entity_ids.items.len, entities.allocator, &erased) catch |err| {
assert(entities.archetypes.swapRemove(new_hash));
return err;
};
new_archetype.components.put(entities.allocator, entry.key_ptr.*, erased) catch |err| {
assert(entities.archetypes.swapRemove(new_hash));
return err;
};
}
// Create storage/column for the new component.
const erased = entities.initErasedStorage(&new_archetype.entity_ids.items.len, @TypeOf(component)) catch |err| {
assert(entities.archetypes.swapRemove(new_hash));
return err;
};
new_archetype.components.put(entities.allocator, name, erased) catch |err| {
assert(entities.archetypes.swapRemove(new_hash));
return err;
};
new_archetype.calculateHash();
}
// Either new storage (if the entity moved between storage tables due to having a new
// component) or the prior storage (if the entity already had the component and it's value
// is merely being updated.)
var current_archetype_storage = archetype_entry.value_ptr;
if (new_hash == old_hash) {
// Update the value of the existing component of the entity.
const ptr = entities.entities.get(entity).?;
try current_archetype_storage.set(ptr.row_index, name, component);
return;
}
// Copy to all component values for our entity from the old archetype storage
// (archetype) to the new one (current_archetype_storage).
const new_row = try current_archetype_storage.new(entity);
const old_ptr = entities.entities.get(entity).?;
// Update the storage/columns for all of the existing components on the entity.
var column_iter = archetype.components.iterator();
while (column_iter.next()) |entry| {
var old_component_storage = entry.value_ptr;
var new_component_storage = current_archetype_storage.components.get(entry.key_ptr.*).?;
new_component_storage.copy(new_component_storage.ptr, entities.allocator, new_row, old_ptr.row_index, old_component_storage.ptr) catch |err| {
current_archetype_storage.undoNew();
return err;
};
}
current_archetype_storage.entity_ids.items[new_row] = entity;
// Update the storage/column for the new component.
current_archetype_storage.set(new_row, name, component) catch |err| {
current_archetype_storage.undoNew();
return err;
};
var swapped_entity_id = archetype.entity_ids.items[archetype.entity_ids.items.len - 1];
archetype.remove(old_ptr.row_index) catch |err| {
current_archetype_storage.undoNew();
return err;
};
try entities.entities.put(entities.allocator, swapped_entity_id, old_ptr);
try entities.entities.put(entities.allocator, entity, Pointer{
.archetype_index = @intCast(u16, archetype_entry.index),
.row_index = new_row,
});
return;
}
/// gets the named component of the given type (which must be correct, otherwise undefined
/// behavior will occur). Returns null if the component does not exist on the entity.
pub fn getComponent(entities: *Entities, entity: EntityID, name: []const u8, comptime Component: type) ?Component {
var archetype = entities.archetypeByID(entity);
var component_storage_erased = archetype.components.get(name) orelse return null;
const ptr = entities.entities.get(entity).?;
var component_storage = ErasedComponentStorage.cast(component_storage_erased.ptr, Component);
return component_storage.get(ptr.row_index);
}
/// Removes the named component from the entity, or noop if it doesn't have such a component.
pub fn removeComponent(entities: *Entities, entity: EntityID, name: []const u8) !void {
var archetype = entities.archetypeByID(entity);
if (!archetype.components.contains(name)) return;
// Determine the old hash for the archetype.
const old_hash = archetype.hash;
// Determine the new hash for the archetype with the component removed
var new_hash: u64 = 0;
var iter = archetype.components.iterator();
while (iter.next()) |entry| {
const component_name = entry.key_ptr.*;
if (!std.mem.eql(u8, component_name, name)) new_hash ^= std.hash_map.hashString(component_name);
}
assert(new_hash != old_hash);
// Find the archetype storage for this entity. Could be a new archetype storage table (if a
// new component was added), or the same archetype storage table (if just updating the
// value of a component.)
var archetype_entry = try entities.archetypes.getOrPut(entities.allocator, new_hash);
if (!archetype_entry.found_existing) {
archetype_entry.value_ptr.* = ArchetypeStorage{
.allocator = entities.allocator,
.components = .{},
.hash = 0,
};
var new_archetype = archetype_entry.value_ptr;
// Create storage/columns for all of the existing components on the entity.
var column_iter = archetype.components.iterator();
while (column_iter.next()) |entry| {
if (std.mem.eql(u8, entry.key_ptr.*, name)) continue;
var erased: ErasedComponentStorage = undefined;
entry.value_ptr.cloneType(entry.value_ptr.*, &new_archetype.entity_ids.items.len, entities.allocator, &erased) catch |err| {
assert(entities.archetypes.swapRemove(new_hash));
return err;
};
new_archetype.components.put(entities.allocator, entry.key_ptr.*, erased) catch |err| {
assert(entities.archetypes.swapRemove(new_hash));
return err;
};
}
new_archetype.calculateHash();
}
// Either new storage (if the entity moved between storage tables due to having a new
// component) or the prior storage (if the entity already had the component and it's value
// is merely being updated.)
var current_archetype_storage = archetype_entry.value_ptr;
// Copy to all component values for our entity from the old archetype storage
// (archetype) to the new one (current_archetype_storage).
const new_row = try current_archetype_storage.new(entity);
const old_ptr = entities.entities.get(entity).?;
// Update the storage/columns for all of the existing components on the entity.
var column_iter = current_archetype_storage.components.iterator();
while (column_iter.next()) |entry| {
var src_component_storage = archetype.components.get(entry.key_ptr.*).?;
var dst_component_storage = entry.value_ptr;
dst_component_storage.copy(dst_component_storage.ptr, entities.allocator, new_row, old_ptr.row_index, src_component_storage.ptr) catch |err| {
current_archetype_storage.undoNew();
return err;
};
}
current_archetype_storage.entity_ids.items[new_row] = entity;
var swapped_entity_id = archetype.entity_ids.items[archetype.entity_ids.items.len - 1];
archetype.remove(old_ptr.row_index) catch |err| {
current_archetype_storage.undoNew();
return err;
};
try entities.entities.put(entities.allocator, swapped_entity_id, old_ptr);
try entities.entities.put(entities.allocator, entity, Pointer{
.archetype_index = @intCast(u16, archetype_entry.index),
.row_index = new_row,
});
return;
}
// TODO: iteration over all entities
// TODO: iteration over all entities with components (U, V, ...)
// TODO: iteration over all entities with type T
// TODO: iteration over all entities with type T and components (U, V, ...)
// TODO: "indexes" - a few ideas we could express:
//
// * Graph relations index: e.g. parent-child entity relations for a DOM / UI / scene graph.
// * Spatial index: "give me all entities within 5 units distance from (x, y, z)"
// * Generic index: "give me all entities where arbitraryFunction(e) returns true"
//
pub fn initErasedStorage(entities: *const Entities, total_rows: *usize, comptime Component: type) !ErasedComponentStorage {
var new_ptr = try entities.allocator.create(ComponentStorage(Component));
new_ptr.* = ComponentStorage(Component){ .total_rows = total_rows };
return ErasedComponentStorage{
.ptr = new_ptr,
.deinit = (struct {
pub fn deinit(erased: *anyopaque, allocator: Allocator) void {
var ptr = ErasedComponentStorage.cast(erased, Component);
ptr.deinit(allocator);
allocator.destroy(ptr);
}
}).deinit,
.remove = (struct {
pub fn remove(erased: *anyopaque, row: u32) void {
var ptr = ErasedComponentStorage.cast(erased, Component);
ptr.remove(row);
}
}).remove,
.cloneType = (struct {
pub fn cloneType(erased: ErasedComponentStorage, _total_rows: *usize, allocator: Allocator, retval: *ErasedComponentStorage) !void {
var new_clone = try allocator.create(ComponentStorage(Component));
new_clone.* = ComponentStorage(Component){ .total_rows = _total_rows };
var tmp = erased;
tmp.ptr = new_clone;
retval.* = tmp;
}
}).cloneType,
.copy = (struct {
pub fn copy(dst_erased: *anyopaque, allocator: Allocator, src_row: u32, dst_row: u32, src_erased: *anyopaque) !void {
var dst = ErasedComponentStorage.cast(dst_erased, Component);
var src = ErasedComponentStorage.cast(src_erased, Component);
return dst.copy(allocator, src_row, dst_row, src);
}
}).copy,
.copySparse = (struct {
pub fn copySparse(dst_erased: *anyopaque, allocator: Allocator, src_row: u32, dst_row: u32, src_erased: *anyopaque) !void {
var dst = ErasedComponentStorage.cast(dst_erased, Component);
var src = ErasedComponentStorage.cast(src_erased, Component);
return dst.copySparse(allocator, src_row, dst_row, src);
}
}).copySparse,
};
}
// TODO: ability to remove archetype entirely, deleting all entities in it
// TODO: ability to remove archetypes with no entities (garbage collection)
};
test "entity ID size" {
try testing.expectEqual(8, @sizeOf(EntityID));
}
test "example" {
const allocator = testing.allocator;
//-------------------------------------------------------------------------
// Create a world.
var world = try Entities.init(allocator);
defer world.deinit();
//-------------------------------------------------------------------------
// Define component types, any Zig type will do!
// A location component.
const Location = struct {
x: f32 = 0,
y: f32 = 0,
z: f32 = 0,
};
//-------------------------------------------------------------------------
// Create first player entity.
var player1 = try world.new();
try world.setComponent(player1, "name", "jane"); // add Name component
try world.setComponent(player1, "location", Location{}); // add Location component
// Create second player entity.
var player2 = try world.new();
try testing.expect(world.getComponent(player2, "location", Location) == null);
try testing.expect(world.getComponent(player2, "name", []const u8) == null);
//-------------------------------------------------------------------------
// We can add new components at will.
const Rotation = struct { degrees: f32 };
try world.setComponent(player2, "rotation", Rotation{ .degrees = 90 });
try testing.expect(world.getComponent(player1, "rotation", Rotation) == null); // player1 has no rotation
//-------------------------------------------------------------------------
// Remove a component from any entity at will.
// TODO: add a way to "cleanup" truly unused archetypes
try world.removeComponent(player1, "name");
try world.removeComponent(player1, "location");
try world.removeComponent(player1, "location"); // doesn't exist? no problem.
//-------------------------------------------------------------------------
// Introspect things.
//
// Archetype IDs, these are our "table names" - they're just hashes of all the component names
// within the archetype table.
var archetypes = world.archetypes.keys();
try testing.expectEqual(@as(usize, 6), archetypes.len);
try testing.expectEqual(@as(u64, 18446744073709551615), archetypes[0]);
try testing.expectEqual(@as(u64, 6893717443977936573), archetypes[1]);
try testing.expectEqual(@as(u64, 7008573051677164842), archetypes[2]);
try testing.expectEqual(@as(u64, 14420739110802803032), archetypes[3]);
try testing.expectEqual(@as(u64, 13913849663823266920), archetypes[4]);
try testing.expectEqual(@as(u64, 0), archetypes[5]);
// Number of (living) entities stored in an archetype table.
try testing.expectEqual(@as(usize, 0), world.archetypes.get(archetypes[2]).?.count());
// Component names for a given archetype.
var component_names = world.archetypes.get(archetypes[2]).?.components.keys();
try testing.expectEqual(@as(usize, 2), component_names.len);
try testing.expectEqualStrings("name", component_names[0]);
try testing.expectEqualStrings("location", component_names[1]);
// Component names for a given entity
var player2_archetype = world.archetypeByID(player2);
component_names = player2_archetype.components.keys();
try testing.expectEqual(@as(usize, 1), component_names.len);
try testing.expectEqualStrings("rotation", component_names[0]);
// TODO: iterating components an entity has not currently supported.
//-------------------------------------------------------------------------
// Remove an entity whenever you wish. Just be sure not to try and use it later!
try world.remove(player1);
} | ecs/src/entities.zig |
const fmath = @import("index.zig");
pub fn atanh(x: var) -> @typeOf(x) {
const T = @typeOf(x);
switch (T) {
f32 => @inlineCall(atanhf, x),
f64 => @inlineCall(atanhd, x),
else => @compileError("atanh not implemented for " ++ @typeName(T)),
}
}
// atanh(x) = log((1 + x) / (1 - x)) / 2 = log1p(2x / (1 - x)) / 2 ~= x + x^3 / 3 + o(x^5)
fn atanhf(x: f32) -> f32 {
const u = @bitCast(u32, x);
const i = u & 0x7FFFFFFF;
const s = u >> 31;
var y = @bitCast(f32, i); // |x|
if (u < 0x3F800000 - (1 << 23)) {
if (u < 0x3F800000 - (32 << 23)) {
// underflow
if (u < (1 << 23)) {
fmath.forceEval(y * y)
}
}
// |x| < 0.5
else {
y = 0.5 * fmath.log1p(2 * y + 2 * y * y / (1 - y));
}
} else {
// avoid overflow
y = 0.5 * fmath.log1p(2 * (y / (1 - y)));
}
if (s != 0) -y else y
}
fn atanhd(x: f64) -> f64 {
const u = @bitCast(u64, x);
const e = (u >> 52) & 0x7FF;
const s = u >> 63;
var y = @bitCast(f64, u & (@maxValue(u64) >> 1)); // |x|
if (e < 0x3FF - 1) {
if (e < 0x3FF - 32) {
// underflow
if (e == 0) {
fmath.forceEval(f32(y));
}
}
// |x| < 0.5
else {
y = 0.5 * fmath.log1p(2 * y + 2 * y * y / (1 - y));
}
} else {
// avoid overflow
y = 0.5 * fmath.log1p(2 * (y / (1 - y)));
}
if (s != 0) -y else y
}
test "atanh" {
fmath.assert(atanh(f32(0.0)) == atanhf(0.0));
fmath.assert(atanh(f64(0.0)) == atanhd(0.0));
}
test "atanhf" {
const epsilon = 0.000001;
fmath.assert(fmath.approxEq(f32, atanhf(0.0), 0.0, epsilon));
fmath.assert(fmath.approxEq(f32, atanhf(0.2), 0.202733, epsilon));
fmath.assert(fmath.approxEq(f32, atanhf(0.8923), 1.433099, epsilon));
}
test "atanhd" {
const epsilon = 0.000001;
fmath.assert(fmath.approxEq(f64, atanhd(0.0), 0.0, epsilon));
fmath.assert(fmath.approxEq(f64, atanhd(0.2), 0.202733, epsilon));
fmath.assert(fmath.approxEq(f64, atanhd(0.8923), 1.433099, epsilon));
} | src/atanh.zig |
const std = @import("std");
const mem = @import("./mem.zig");
const stdout = std.io.getStdOut().writer();
const stdin = std.io.getStdIn().reader();
const Traps = enum(u16) {
GETC = 0x20, // 0: Read a single character
OUT = 0x21, // Write character to console
PUTS = 0x22, // Write string to console
IN = 0x23, // Print prompt and read
PUTSP = 0x24, //
HALT = 0x25, // Halt execution and print message to console
pub fn val(self: Traps) u16 {
return @enumToInt(self);
}
fn getC() void {
const input_char = stdin.readByte() catch unreachable;
mem.reg[mem.Registers.R0.val()] = @as(u16, input_char);
}
fn out() void {
const output_char = @truncate(u8, mem.reg[mem.Registers.R0.val()]);
stdout.print("{c}", .{ output_char }) catch unreachable;
}
fn puts() void {
const init_str_address = mem.reg[mem.Registers.R0.val()];
var str_len: u16 = 0;
var str_val_long: u16 = mem.memory[init_str_address];
while (str_val_long != 0) {
const str_val_char: u8 = @truncate(u8, str_val_long);
stdout.print("{c}", .{ str_val_char }) catch unreachable;
str_len += 1;
str_val_long = mem.memory[init_str_address + str_len];
}
}
fn in() void {
stdout.print("Enter a character: ", .{}) catch unreachable;
const input_char = stdin.readByte() catch unreachable;
mem.reg[mem.Registers.R0.val()] = @as(u16, input_char);
stdout.print("{c}", .{ input_char }) catch unreachable;
}
fn putsp() void {
std.debug.print("PUTSP trap called\n", .{});
const str_addr = mem.reg[mem.Registers.R0.val()];
var str_len: u16 = 0;
var double_char = mem.memory[str_addr];
while (double_char != 0) {
const first_char_long = double_char & 0xFF;
const first_char = @truncate(u8, first_char_long);
stdout.print("{c}", .{ first_char }) catch unreachable;
const second_char_long = double_char >> 8;
if (second_char_long != 0) {
const second_char = @truncate(u8, second_char_long);
stdout.print("{c}", .{ second_char }) catch unreachable;
}
str_len += 1;
double_char = mem.memory[str_addr + str_len];
}
}
fn halt() void {
stdout.print("HALT", .{}) catch unreachable;
std.os.exit(0);
}
};
pub fn run(vector: u16) void {
switch (vector) {
Traps.GETC.val() => Traps.getC(),
Traps.OUT.val() => Traps.out(),
Traps.PUTS.val() => Traps.puts(),
Traps.IN.val() => Traps.in(),
Traps.PUTSP.val() => Traps.putsp(),
Traps.HALT.val() => Traps.halt(),
else => {
std.debug.print("Did not understand trap vector: {b}\n", .{ vector });
}
}
} | src/traps.zig |
const std = @import("std");
const csv = @import("csv");
pub const Converter = struct {
const BufferedWriter = std.io.BufferedWriter(4096, std.fs.File.Writer);
allocator: *std.mem.Allocator,
csvBuf: []u8,
hdrBuf: []u8,
rowBuf: []u8,
keys: [][]const u8,
out: BufferedWriter,
// Initialize the converter.
pub fn init(allocator: *std.mem.Allocator, writer: anytype, rowBufSize: u32) !Converter {
var s = Converter{
.allocator = allocator,
.out = std.io.bufferedWriter(writer),
.csvBuf = try allocator.alloc(u8, rowBufSize),
.hdrBuf = try allocator.alloc(u8, rowBufSize),
.rowBuf = try allocator.alloc(u8, rowBufSize),
.keys = undefined,
};
return s;
}
pub fn deinit(self: *Converter) void {
if (self.csvBuf) self.allocator.free(self.csvBuf);
if (self.hdrBuf) self.allocator.free(self.hdrBuf);
if (self.rowBuf) self.allocator.free(self.rowBuf);
}
// Convert a CSV file. rowBufSize should be greater than the length (bytes)
// of the biggest row in the CSV file.
pub fn convert(self: *Converter, filePath: []const u8) !u64 {
const file = try std.fs.cwd().openFile(filePath, .{});
defer file.close();
const tk = &try csv.CsvTokenizer(std.fs.File.Reader).init(file.reader(), self.csvBuf, .{});
var fields = std.ArrayList([]const u8).init(std.heap.page_allocator);
var isFirst: bool = true;
var line: u64 = 1;
var f: usize = 0;
while (try tk.next()) |token| {
switch (token) {
.field => |val| {
// Copy the incoming field slice to the row buffer.
const ln: usize = f + val.len;
if (isFirst) {
// Copy all the fields in the first row to a separate buffer
// to be retained throughout the lifetime of the program.
std.mem.copy(u8, self.hdrBuf[f..ln], val);
try fields.append(self.hdrBuf[f..ln]);
} else {
// Row buffer can be discarded after processing each individual row.
std.mem.copy(u8, self.rowBuf[f..ln], val);
try fields.append(self.rowBuf[f..ln]);
}
f = ln;
},
.row_end => {
f = 0;
// Move the first row (header) fields to be reused with every subsequent
// row as JSON keys.
if (isFirst) {
isFirst = false;
self.keys = fields.toOwnedSlice();
continue;
}
try self.writeJSON(fields, line);
try fields.resize(0);
line += 1;
},
}
}
try self.out.flush();
return line;
}
// Writes a list of "value" fields from a row as a JSON dict.
fn writeJSON(self: *Converter, vals: std.ArrayList([]const u8), line: u64) !void {
if (self.keys.len != vals.items.len) {
std.debug.print("Invalid field count on line {d}: {d} (headers) != {d} (fields).\n", .{ line, self.keys.len, vals.items.len });
return;
}
try self.out.writer().writeAll("{");
for (self.keys) |key, n| {
// Write the key.
try self.out.writer().writeAll("\"");
try self.out.writer().writeAll(key);
try self.out.writer().writeAll("\": ");
// Write the value.
if (vals.items[n].len == 0) {
try self.out.writer().writeAll("null");
} else {
try self.writeValue(vals.items[n], true);
}
// If it's not the last key, write a comma.
if (n < self.keys.len - 1) {
try self.out.writer().writeAll(", ");
}
}
try self.out.writer().writeAll("}\n");
}
fn writeValue(self: *Converter, val: []const u8, detectNum: bool) !void {
// If the first char is a digit, then try and iterate through the rest
// of the chars to see if it's a number.
if (detectNum and std.ascii.isDigit(val[0])) {
var hasPeriod: bool = false;
var isNum: bool = true;
for (val) |c| {
// Already found a period.
if (hasPeriod) {
isNum = false;
break;
}
if (c == '.') {
hasPeriod = true;
}
if (!std.ascii.isDigit(c)) {
isNum = false;
break;
}
}
if (isNum) {
try self.out.writer().writeAll(val);
return;
}
}
// It's a string.
try self.out.writer().writeAll("\"");
// Iterate through the string to see if there are any quotes to escape.
// If there aren't, doing a writeAll() is faster than than doing a .write() per character.
if (self.hasQuote(val)) {
for (val) |c| {
// Escape quotes.
if (c == '"') {
_ = try self.out.writer().write("\\");
}
_ = try self.out.writer().write(&[_]u8{c});
}
} else {
try self.out.writer().writeAll(val);
}
try self.out.writer().writeAll("\"");
}
fn hasQuote(self: *Converter, val: []const u8) bool {
// workaround to fix the error
_ = self;
// src/converter.zig:166:17: error: unused function parameter
// fn hasQuote(self: *Converter, val: []const u8) bool {
// ^
// csv2json...The following command exited with error code 1:
for (val) |c| {
if (c == '"') {
return true;
}
}
return false;
}
}; | src/converter.zig |
const std = @import("std");
const stb_image = @import("stb");
const gk = @import("../gamekit.zig");
const imgui = @import("imgui");
const renderkit = @import("renderkit");
const renderer = renderkit.renderer;
const fs = gk.utils.fs;
pub const Texture = struct {
img: renderkit.Image,
width: f32 = 0,
height: f32 = 0,
pub fn init(width: i32, height: i32) Texture {
return initDynamic(width, height, .nearest, .clamp);
}
pub fn initDynamic(width: i32, height: i32, filter: renderkit.TextureFilter, wrap: renderkit.TextureWrap) Texture {
const img = renderer.createImage(.{
.width = width,
.height = height,
.usage = .dynamic,
.min_filter = filter,
.mag_filter = filter,
.wrap_u = wrap,
.wrap_v = wrap,
.content = null,
});
return .{
.img = img,
.width = @intToFloat(f32, width),
.height = @intToFloat(f32, height),
};
}
pub fn initFromFile(allocator: std.mem.Allocator, file: []const u8, filter: renderkit.TextureFilter) !Texture {
const image_contents = try fs.read(allocator, file);
defer allocator.free(image_contents);
var w: c_int = undefined;
var h: c_int = undefined;
var channels: c_int = undefined;
const load_res = stb_image.stbi_load_from_memory(image_contents.ptr, @intCast(c_int, image_contents.len), &w, &h, &channels, 4);
if (load_res == null) return error.ImageLoadFailed;
defer stb_image.stbi_image_free(load_res);
return initWithDataOptions(u8, w, h, load_res[0..@intCast(usize, w * h * channels)], filter, .clamp);
}
pub fn initWithData(comptime T: type, width: i32, height: i32, pixels: []T) Texture {
return initWithDataOptions(T, width, height, pixels, .nearest, .clamp);
}
pub fn initWithDataOptions(comptime T: type, width: i32, height: i32, pixels: []T, filter: renderkit.TextureFilter, wrap: renderkit.TextureWrap) Texture {
const img = renderer.createImage(.{
.width = width,
.height = height,
.min_filter = filter,
.mag_filter = filter,
.wrap_u = wrap,
.wrap_v = wrap,
.content = std.mem.sliceAsBytes(pixels).ptr,
});
return .{
.img = img,
.width = @intToFloat(f32, width),
.height = @intToFloat(f32, height),
};
}
pub fn initCheckerTexture() Texture {
var pixels = [_]u32{
0xFFFFFFFF, 0xFF000000, 0xFFFFFFFF, 0xFF000000,
0xFF000000, 0xFFFFFFFF, 0xFF000000, 0xFFFFFFFF,
0xFFFFFFFF, 0xFF000000, 0xFFFFFFFF, 0xFF000000,
0xFF000000, 0xFFFFFFFF, 0xFF000000, 0xFFFFFFFF,
};
return initWithData(u32, 4, 4, &pixels);
}
pub fn initSingleColor(color: u32) Texture {
var pixels: [16]u32 = undefined;
std.mem.set(u32, &pixels, color);
return initWithData(u32, 4, 4, pixels[0..]);
}
pub fn initOffscreen(width: i32, height: i32, filter: renderkit.TextureFilter, wrap: renderkit.TextureWrap) Texture {
const img = renderer.createImage(.{
.render_target = true,
.width = width,
.height = height,
.min_filter = filter,
.mag_filter = filter,
.wrap_u = wrap,
.wrap_v = wrap,
});
return .{
.img = img,
.width = @intToFloat(f32, width),
.height = @intToFloat(f32, height),
};
}
pub fn initStencil(width: i32, height: i32, filter: renderkit.TextureFilter, wrap: renderkit.TextureWrap) Texture {
const img = renderer.createImage(.{
.render_target = true,
.pixel_format = .stencil,
.width = width,
.height = height,
.min_filter = filter,
.mag_filter = filter,
.wrap_u = wrap,
.wrap_v = wrap,
});
return .{
.img = img,
.width = @intToFloat(f32, width),
.height = @intToFloat(f32, height),
};
}
pub fn deinit(self: *const Texture) void {
renderer.destroyImage(self.img);
}
pub fn setData(self: *Texture, comptime T: type, data: []T) void {
renderer.updateImage(T, self.img, data);
}
pub fn imTextureID(self: Texture) imgui.ImTextureID {
return @intToPtr(*anyopaque, self.img);
}
}; | gamekit/graphics/texture.zig |
const xcb = @import("../xcb.zig");
pub const id = xcb.Extension{ .name = "DAMAGE", .global_id = 0 };
pub const DAMAGE = u32;
pub const ReportLevel = extern enum(c_uint) {
@"RawRectangles" = 0,
@"DeltaRectangles" = 1,
@"BoundingBox" = 2,
@"NonEmpty" = 3,
};
/// Opcode for BadDamage.
pub const BadDamageOpcode = 0;
/// @brief BadDamageError
pub const BadDamageError = struct {
@"response_type": u8,
@"error_code": u8,
@"sequence": u16,
};
/// @brief QueryVersioncookie
pub const QueryVersioncookie = struct {
sequence: c_uint,
};
/// @brief QueryVersionRequest
pub const QueryVersionRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 0,
@"length": u16,
@"client_major_version": u32,
@"client_minor_version": u32,
};
/// @brief QueryVersionReply
pub const QueryVersionReply = struct {
@"response_type": u8,
@"pad0": u8,
@"sequence": u16,
@"length": u32,
@"major_version": u32,
@"minor_version": u32,
@"pad1": [16]u8,
};
/// @brief CreateRequest
pub const CreateRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 1,
@"length": u16,
@"damage": xcb.damage.DAMAGE,
@"drawable": xcb.DRAWABLE,
@"level": u8,
@"pad0": [3]u8,
};
/// @brief DestroyRequest
pub const DestroyRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 2,
@"length": u16,
@"damage": xcb.damage.DAMAGE,
};
/// @brief SubtractRequest
pub const SubtractRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 3,
@"length": u16,
@"damage": xcb.damage.DAMAGE,
@"repair": xcb.xfixes.REGION,
@"parts": xcb.xfixes.REGION,
};
/// @brief AddRequest
pub const AddRequest = struct {
@"major_opcode": u8,
@"minor_opcode": u8 = 4,
@"length": u16,
@"drawable": xcb.DRAWABLE,
@"region": xcb.xfixes.REGION,
};
/// Opcode for Notify.
pub const NotifyOpcode = 0;
/// @brief NotifyEvent
pub const NotifyEvent = struct {
@"response_type": u8,
@"level": u8,
@"sequence": u16,
@"drawable": xcb.DRAWABLE,
@"damage": xcb.damage.DAMAGE,
@"timestamp": xcb.TIMESTAMP,
@"area": xcb.RECTANGLE,
@"geometry": xcb.RECTANGLE,
};
test "" {
@import("std").testing.refAllDecls(@This());
} | src/auto/damage.zig |
const build_ = @import("std").build;
const Builder = build_.Builder;
const LibExeObjStep = build_.LibExeObjStep;
const builtin = @import("builtin");
const testNames = [_][]const u8{
"WindowGraphicsInput",
"ModelFiles",
"RTRenderEngine",
"Mathematics",
"Compress",
"RGB10A2",
"Assets",
"Scene",
};
const testFiles = [_][]const u8{
"WindowGraphicsInput/WindowGraphicsInput.zig",
"ModelFiles/ModelFiles.zig",
"RTRenderEngine/RTRenderEngine.zig",
"Mathematics/Mathematics.zig",
"Compress/Compress.zig",
"RGB10A2/RGB10A2.zig",
"Assets/Assets.zig",
"Scene/Scene.zig",
};
fn addSettings(x: *LibExeObjStep) void {
x.linkSystemLibrary("c");
x.addIncludeDir("deps/glad");
x.addIncludeDir("deps/stb_image");
x.addIncludeDir("deps/glfw/include");
x.addCSourceFile("deps/glad/glad.c", &[_][]const u8{"-I."});
x.addCSourceFile("deps/stb_image/stb_image.c", &[_][]const u8{"-I."});
x.addIncludeDir("deps/zstd/lib");
if (builtin.os.tag == builtin.Os.Tag.windows) {
x.addLibPath("deps/glfw/src/Release");
x.addLibPath("deps\\zstd\\build\\VS2010\\bin\\x64_Release");
x.linkSystemLibrary("libzstd_static");
} else {
x.addLibPath("deps/glfw/src");
x.addLibPath("deps/zstd/lib");
x.linkSystemLibrary("zstd");
x.linkSystemLibrary("rt");
x.linkSystemLibrary("m");
x.linkSystemLibrary("dl");
x.linkSystemLibrary("X11");
}
x.linkSystemLibrary("glfw3");
if (builtin.os.tag == builtin.Os.Tag.windows) {
x.linkSystemLibrary("user32");
x.linkSystemLibrary("gdi32");
x.linkSystemLibrary("shell32");
} else {}
}
pub fn build(b: *Builder) void {
const mode = b.standardReleaseOptions();
const test_step = b.step("test", "Run all tests");
const demo_step = b.step("Demos", "Build Demos");
inline for ([_][]const u8{ "Demo1", "Demo2", "Demo3" }) |demo_name| {
const f = "src/" ++ demo_name ++ ".zig";
const exe = b.addExecutable(demo_name, f);
exe.setBuildMode(mode);
exe.setMainPkgPath("src");
addSettings(exe);
b.installArtifact(exe);
}
// tools
const compress_exe = b.addExecutable("compress-file", "src/Compress/CompressApp.zig");
compress_exe.setBuildMode(mode);
compress_exe.setMainPkgPath("src");
addSettings(compress_exe);
b.installArtifact(compress_exe);
const rgb10a2convert_exe = b.addExecutable("rgb10a2convert", "src/RGB10A2/RGB10A2ConvertApp.zig");
rgb10a2convert_exe.setBuildMode(mode);
rgb10a2convert_exe.setMainPkgPath("src");
addSettings(rgb10a2convert_exe);
b.installArtifact(rgb10a2convert_exe);
// tests
comptime var i: u32 = 0;
inline while (i < testNames.len) : (i += 1) {
const t = b.addTest("src/" ++ testFiles[i]);
t.setBuildMode(mode);
t.setMainPkgPath("src");
addSettings(t);
test_step.dependOn(&t.step);
const step = b.step("test-" ++ testNames[i], "Run all tests for " ++ testFiles[i]);
step.dependOn(&t.step);
}
b.default_step.dependOn(demo_step);
} | build.zig |
const std = @import("std");
const math = std.math;
const testing = std.testing;
const __divtf3 = @import("divtf3.zig").__divtf3;
fn compareResultLD(result: f128, expectedHi: u64, expectedLo: u64) bool {
const rep = @bitCast(u128, result);
const hi = @truncate(u64, rep >> 64);
const lo = @truncate(u64, rep);
if (hi == expectedHi and lo == expectedLo) {
return true;
}
// test other possible NaN representation(signal NaN)
else if (expectedHi == 0x7fff800000000000 and expectedLo == 0) {
if ((hi & 0x7fff000000000000) == 0x7fff000000000000 and
((hi & 0xffffffffffff) > 0 or lo > 0))
{
return true;
}
}
return false;
}
fn test__divtf3(a: f128, b: f128, expectedHi: u64, expectedLo: u64) void {
const x = __divtf3(a, b);
const ret = compareResultLD(x, expectedHi, expectedLo);
testing.expect(ret == true);
}
test "divtf3" {
// qNaN / any = qNaN
test__divtf3(math.qnan_f128, 0x1.23456789abcdefp+5, 0x7fff800000000000, 0);
// NaN / any = NaN
test__divtf3(math.nan_f128, 0x1.23456789abcdefp+5, 0x7fff800000000000, 0);
// inf / any = inf
test__divtf3(math.inf_f128, 0x1.23456789abcdefp+5, 0x7fff000000000000, 0);
test__divtf3(0x1.a23b45362464523375893ab4cdefp+5, 0x1.eedcbaba3a94546558237654321fp-1, 0x4004b0b72924d407, 0x0717e84356c6eba2);
test__divtf3(0x1.a2b34c56d745382f9abf2c3dfeffp-50, 0x1.ed2c3ba15935332532287654321fp-9, 0x3fd5b2af3f828c9b, 0x40e51f64cde8b1f2);
test__divtf3(0x1.2345f6aaaa786555f42432abcdefp+456, 0x1.edacbba9874f765463544dd3621fp+6400, 0x28c62e15dc464466, 0xb5a07586348557ac);
test__divtf3(0x1.2d3456f789ba6322bc665544edefp-234, 0x1.eddcdba39f3c8b7a36564354321fp-4455, 0x507b38442b539266, 0x22ce0f1d024e1252);
test__divtf3(0x1.2345f6b77b7a8953365433abcdefp+234, 0x1.edcba987d6bb3aa467754354321fp-4055, 0x50bf2e02f0798d36, 0x5e6fcb6b60044078);
test__divtf3(6.72420628622418701252535563464350521E-4932, 2.0, 0x0001000000000000, 0);
} | lib/std/special/compiler_rt/divtf3_test.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");
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(gpa);
defer arena.deinit();
const allocator = arena.allocator();
var input = try getInput(allocator);
defer allocator.free(input);
const length = input[0].len;
assert(length != 0);
{ // Part 1
const counts = try allocator.alloc(isize, length);
defer allocator.free(counts);
for (counts) |*digit| digit.* = 0;
for (input) |line| {
if (line.len != length) @panic("Inconsistent length");
for (line) |digit, i| {
switch (digit) {
'1' => counts[i] += 1,
'0' => counts[i] -= 1,
else => @panic("Invalid digit"),
}
}
}
var gamma_string = try allocator.alloc(u8, length);
for (counts) |count, i| {
if (count > 0) {
gamma_string[i] = '1';
} else {
gamma_string[i] = '0';
}
}
const gamma = try parseInt(usize, gamma_string, 2);
const epsilon = gamma ^ (std.math.pow(usize, 2, length) - 1);
const power = gamma * epsilon;
print("Part 1: {d}\n", .{power});
}
{ // Part 2
const o2_generator = try getRating(allocator, input, 1);
const co2_scrubber = try getRating(allocator, input, 0);
print("Part 2: {d}\n", .{o2_generator * co2_scrubber});
}
}
fn getInput(allocator: Allocator) ![]const []const u8 {
var input = std.ArrayList([]const u8).init(allocator);
errdefer input.deinit();
{
var iter = split(u8, data, "\n");
while (iter.next()) |line| {
if (line.len == 0) break;
try input.append(line);
}
}
return input.toOwnedSlice();
}
fn getRating(allocator: Allocator, input: []const []const u8, priority_bit: u1) !usize {
const length = input[0].len;
const keep = try allocator.alloc(bool, input.len);
for (keep) |*b| b.* = true;
defer allocator.free(keep);
var keep_count = input.len;
var i: usize = 0;
while (i < length and keep_count > 1) : (i += 1) {
var count: isize = 0;
for (input) |line, j| {
if (keep[j] == false) continue;
switch (line[i]) {
'1' => count += 1,
'0' => count -= 1,
else => @panic("Invalid digit"),
}
}
var j: usize = 0;
while (j < input.len) : (j += 1) {
if (keep[j] == false) continue;
var required_bit: u8 = undefined;
if (count < 0) {
if (priority_bit == 1) {
required_bit = '0';
} else {
required_bit = '1';
}
} else {
if (priority_bit == 1) {
required_bit = '1';
} else {
required_bit = '0';
}
}
if (input[j][i] != required_bit) {
keep[j] = false;
keep_count -= 1;
}
}
}
for (keep) |b, j| {
if (b) {
return try parseInt(usize, input[j], 2);
}
}
unreachable;
}
// 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 parseInt = std.fmt.parseInt;
const print = std.debug.print;
const tokenize = std.mem.tokenize;
const testing = std.testing;
const input = @embedFile("./input.txt");
const rows = 100;
const cols = 100;
pub fn main() anyerror!void {
print("--- Part One ---\n", .{});
print("Result: {d}\n", .{part1()});
print("--- Part Two ---\n", .{});
print("Result: {d}\n", .{part2()});
}
///
/// --- Part One ---
///
fn part1() !u32 {
var ans: u32 = 0;
var heatmap: [rows][cols]u8 = try parseHeatmap();
for (heatmap) |row, i| {
for (heatmap[i]) |cell, j| {
if (j != 0 and cell >= heatmap[i][j - 1]) continue;
if (j != row.len - 1 and cell >= heatmap[i][j + 1]) continue;
if (i != 0 and cell >= heatmap[i - 1][j]) continue;
if (i != heatmap.len - 1 and cell >= heatmap[i + 1][j]) continue;
ans += cell + 1;
}
}
return ans;
}
test "day09.part1" {
@setEvalBranchQuota(200_000);
try testing.expectEqual(537, comptime try part1());
}
///
/// --- Part Two ---
///
fn part2() !u32 {
var s1: u32 = 0;
var s2: u32 = 0;
var s3: u32 = 0;
var heatmap: [rows][cols]u8 = try parseHeatmap();
for (heatmap) |row, i| {
for (heatmap[i]) |cell, j| {
if (j != 0 and cell >= heatmap[i][j - 1]) continue;
if (j != row.len - 1 and cell >= heatmap[i][j + 1]) continue;
if (i != 0 and cell >= heatmap[i - 1][j]) continue;
if (i != heatmap.len - 1 and cell >= heatmap[i + 1][j]) continue;
var size = fillBasin(&heatmap, .{ i, j });
if (size > s1) {
s3 = s2;
s2 = s1;
s1 = size;
} else if (size > s2) {
s3 = s2;
s2 = size;
} else if (size > s3) {
s3 = size;
}
}
}
return s1 * s2 * s3;
}
test "day09.part2" {
@setEvalBranchQuota(1_000_000);
try testing.expectEqual(1142757, comptime try part2());
}
///
/// parseHeatmap parses the input into a 2D array of u8s
///
fn parseHeatmap() ![rows][cols]u8 {
var heatmap: [rows][cols]u8 = undefined;
var input_iter = tokenize(u8, input, "\n");
var i: usize = 0;
while (input_iter.next()) |row| : (i += 1) {
for (row) |cell, j| {
heatmap[i][j] = cell - '0';
}
}
return heatmap;
}
///
/// fillBasin fills a basin of the start cell in a BFS fashion and returns its size
///
fn fillBasin(heatmap: *[rows][cols]u8, start: anytype) u32 {
var queue: [rows * cols][2]usize = undefined;
var front: u32 = 0;
var back: u32 = 1;
queue[front] = start;
while (front < back) : (front += 1) {
var i = queue[front][0];
var j = queue[front][1];
inline for (.{ .{ 1, 0 }, .{ 0, 1 }, .{ -1, 0 }, .{ 0, -1 } }) |deltas| {
if ((i != 0 or deltas[0] != -1) and (j != 0 or deltas[1] != -1)) {
var x: usize = @intCast(usize, @intCast(i16, i) + deltas[0]);
var y: usize = @intCast(usize, @intCast(i16, j) + deltas[1]);
if (x < rows and y < cols and heatmap[x][y] < 9) {
heatmap[x][y] = 9;
queue[back] = .{ x, y };
back += 1;
}
}
}
}
return back - 1;
} | src/day09/day09.zig |
extern "wapc" fn __guest_request(operation_ptr: [*]u8, payload_ptr: [*]u8) void;
extern "wapc" fn __guest_response(ptr: [*]u8, len: usize) void;
extern "wapc" fn __guest_error(ptr: [*]u8, len: usize) void;
extern "wapc" fn __host_call(binding_ptr: [*]u8, binding_len: usize, namespace_ptr: [*]u8, namespace_len: usize, operation_ptr: [*]u8, operation_len: usize, payload_ptr: [*]u8, payload_len: usize) bool;
extern "wapc" fn __host_response_len() usize;
extern "wapc" fn __host_response(ptr: [*]u8) void;
extern "wapc" fn __host_error_len() usize;
extern "wapc" fn __host_error(ptr: [*]u8) void;
extern fn __console_log(ptr: [*]u8, len: usize) void;
const std = @import("std");
const mem = std.mem;
const heap = std.heap;
pub const Function = struct {
pub const Error = error{HostError,OutOfMemory};
name: []u8,
invoke: fn (
allocator: *mem.Allocator,
payload: []u8,
) Error![]u8,
};
pub fn handleCall(operation_size: usize, payload_size: usize, fns: []Function) bool {
var sbuf: [1000]u8 = undefined;
var allocator = &std.heap.FixedBufferAllocator.init(sbuf[0..]).allocator;
var operation_buf = allocator.alloc(u8, operation_size) catch |err| return false;
var payload_buf = allocator.alloc(u8, payload_size) catch |err| return false;
__guest_request(operation_buf.ptr, payload_buf.ptr);
for (fns) |function| {
if (mem.eql(u8, operation_buf, function.name)) {
const response = function.invoke(allocator, payload_buf) catch |err| return false;
__guest_response(response.ptr, response.len);
return true;
}
}
const functionNotFound = "Could not find function ";
const message = allocator.alloc(u8, functionNotFound.len + operation_buf.len) catch |err| return false;
mem.copy(u8, message, &functionNotFound);
mem.copy(u8, message[functionNotFound.len..], operation_buf);
__guest_error(message.ptr, message.len);
return false;
}
pub fn hostCall(allocator: *mem.Allocator, binding: []u8, namespace: []u8, operation: []u8, payload: []u8) ![]u8 {
const result = __host_call(binding.ptr, binding.len, namespace.ptr, namespace.len, operation.ptr, operation.len, payload.ptr, payload.len);
if (!result) {
const errorLen = __host_error_len();
const errorPrefix = "Host error: ";
const message = allocator.alloc(u8, errorPrefix.len +errorLen) catch |err| return error.HostError;
mem.copy(u8, message, &errorPrefix);
__host_error(message.ptr + errorPrefix.len);
__guest_error(message.ptr, message.len);
return error.HostError;
}
const responseLen = __host_response_len();
const response = try allocator.alloc(u8, responseLen);
__host_response(response.ptr);
return response;
} | wapc.zig |
const std = @import("std");
const json = @import("../json.zig");
// Utils
pub fn EnumStringify(comptime T: type) type {
return struct {
pub fn jsonStringify(value: T, options: json.StringifyOptions, out_stream: anytype) !void {
try json.stringify(@enumToInt(value), options, out_stream);
}
};
}
pub const PacketKind = enum { request, response, notification };
pub fn Paramsify(comptime T: type) type {
return @Type(.{ .Struct = .{
.layout = .Auto,
.fields = &([1]std.builtin.TypeInfo.StructField{
.{
.name = "method",
.field_type = []const u8,
.default_value = std.mem.sliceAsBytes(std.mem.span(@field(T, "method"))),
.is_comptime = true,
.alignment = 0,
},
} ++ (if (@field(T, "kind") == .request) [1]std.builtin.TypeInfo.StructField{
.{
.name = "id",
.field_type = RequestId,
.default_value = null,
.is_comptime = false,
.alignment = 0,
},
} else [0]std.builtin.TypeInfo.StructField{}) ++ [1]std.builtin.TypeInfo.StructField{
.{
.name = "params",
.field_type = T,
.default_value = null,
.is_comptime = false,
.alignment = 0,
},
}),
.decls = &.{},
.is_tuple = false,
} });
}
// LSP types
// https://microsoft.github.io/language-server-protocol/specifications/specification-3-16/
/// Defines an integer number in the range of -2^31 to 2^31 - 1.
pub const integer = i64;
/// Defines an unsigned integer number in the range of 0 to 2^31 - 1.
pub const uinteger = i64;
/// Defines a decimal number. Since decimal numbers are very
/// rare in the language server specification we denote the
/// exact range with every decimal using the mathematics
/// interval notation (e.g. [0, 1] denotes all decimals d with
/// 0 <= d <= 1.
pub const decimal = i64;
/// Many of the interfaces contain fields that correspond to the URI of a document.
/// For clarity, the type of such a field is declared as a DocumentUri.
/// Over the wire, it will still be transferred as a string, but this guarantees
/// that the contents of that string can be parsed as a valid URI.
const DocumentUri = []const u8;
/// There is also a tagging interface for normal non document URIs. It maps to a string as well.
const Uri = []const u8;
/// Position in a text document expressed as zero-based line and zero-based character offset.
/// A position is between two characters like an ‘insert’ cursor in an editor.
/// Special values like for example -1 to denote the end of a line are not supported.
///
/// [Docs](https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#position)
pub const Position = struct {
/// Line position in a document (zero-based).
line: uinteger,
/// Character offset on a line in a document (zero-based). Assuming that
/// the line is represented as a string, the `character` value represents
/// the gap between the `character` and `character + 1`.
///
/// If the character value is greater than the line length it defaults back
/// to the line length.
character: uinteger,
};
/// A range in a text document expressed as (zero-based) start and end positions.
/// A range is comparable to a selection in an editor. Therefore the end position is exclusive.
/// If you want to specify a range that contains a line including the line ending character(s)
/// then use an end position denoting the start of the next line.
///
/// [Docs](https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#range)
pub const Range = struct {
/// The range's start position.
start: Position,
/// The range's end position.
end: Position,
};
/// Represents a location inside a resource, such as a line inside a text file.
///
/// [Docs](https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#location)
pub const Location = struct {
uri: DocumentUri,
range: Range,
};
/// Represents a link between a source and a target location.
///
/// [Docs](https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#locationLink)
pub const LocationLink = struct {
/// Span of the origin of this link.
///
/// Used as the underlined span for mouse interaction. Defaults to the word
/// range at the mouse position.
originSelectionRange: Range,
/// The target resource identifier of this link.
targetUri: DocumentUri,
/// The full target range of this link. If the target for example is a symbol
/// then target range is the range enclosing this symbol not including
/// leading/trailing whitespace but everything else like comments. This
/// information is typically used to highlight the range in the editor.
targetRange: Range,
/// The range that should be selected and revealed when this link is being
/// followed, e.g the name of a function. Must be contained by the the
/// `targetRange`. See also `DocumentSymbol#range`
targetSelectionRange: Range,
};
pub const DiagnosticSeverity = enum(i64) {
err = 1,
warn = 2,
info = 3,
log = 4,
pub fn jsonStringify(value: DiagnosticSeverity, options: json.StringifyOptions, out_stream: anytype) !void {
try json.stringify(@enumToInt(value), options, out_stream);
}
};
pub const DiagnosticCode = union(enum) {
integer: integer,
string: []const u8,
};
/// The diagnostic tags.
///
/// Ssince 3.15.0
pub const DiagnosticTag = enum(i64) {
/// Unused or unnecessary code.
///
/// Clients are allowed to render diagnostics with this tag faded out
/// instead of having an error squiggle.
unnecessary = 1,
/// Deprecated or obsolete code.
///
/// Clients are allowed to rendered diagnostics with this tag strike through.
deprecated = 2,
};
/// Structure to capture a description for an error code.
///
/// Since 3.16.0
pub const CodeDescription = struct {
/// An URI to open with more information about the diagnostic error.
href: Uri,
};
/// Represents a related message and source code location for a diagnostic.
/// This should be used to point to code locations that cause or are related to
/// a diagnostics, e.g when duplicating a symbol in a scope.
pub const DiagnosticRelatedInformation = struct {
/// The location of this related diagnostic information.
location: Location,
/// The message of this related diagnostic information.
message: []const u8,
};
/// Represents a diagnostic, such as a compiler error or warning.
/// Diagnostic objects are only valid in the scope of a resource.
///
/// [Docs](https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#diagnostic)
pub const Diagnostic = struct {
/// The range at which the message applies.
range: Range,
/// The diagnostic's severity. Can be omitted. If omitted it is up to the
/// client to interpret diagnostics as error, warning, info or hint.
severity: ?DiagnosticSeverity = null,
/// The diagnostic's code, which might appear in the user interface.
code: DiagnosticCode,
/// An optional property to describe the error code.
///
/// Since 3.16.0
codeDescription: CodeDescription = null,
/// A human-readable string describing the source of this
/// diagnostic, e.g. 'typescript' or 'super lint'.
source: []const u8 = null,
/// The diagnostic's message.
message: []const u8,
/// Additional metadata about the diagnostic.
///
/// Since 3.15.0
tags: ?[]DiagnosticTag = null,
// An array of related diagnostic information, e.g. when symbol-names within
// a scope collide all definitions can be marked via this property.
relatedInformation: ?[]DiagnosticRelatedInformation = null,
// TODO: wtf is going on here???
// A data entry field that is preserved between a
// `textDocument/publishDiagnostics` notification and
// `textDocument/codeAction` request.
//
// Since 3.16.0
// data?: unknown;
};
/// Hover response
pub const Hover = struct {
contents: MarkupContent,
};
/// Text documents are identified using a URI. On the protocol level, URIs are passed as strings.
///
/// [Docs](https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#textDocumentIdentifier)
pub const TextDocumentIdentifier = struct {
uri: []const u8,
};
/// An item to transfer a text document from the client to the server.
///
/// [Docs](https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#textDocumentItem)
pub const TextDocumentItem = struct {
/// The text document's URI.
uri: DocumentUri,
/// The text document's language identifier.
languageId: []const u8,
/// The version number of this document (it will increase after each
/// change, including undo/redo).
version: integer,
/// The content of the opened text document.
text: []const u8,
};
/// An identifier to denote a specific version of a text document.
/// This information usually flows from the client to the server.
///
/// [Docs](https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#versionedTextDocumentIdentifier)
pub const VersionedTextDocumentIdentifier = struct {
uri: []const u8,
/// The version number of this document.
///
/// The version number of a document will increase after each change,
/// including undo/redo. The number doesn't need to be consecutive.
version: integer,
};
/// An identifier which optionally denotes a specific version of a text document.
/// This information usually flows from the server to the client.
///
/// [Docs](https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#optionalVersionedTextDocumentIdentifier)
pub const OptionalVersionedTextDocumentIdentifier = struct {
uri: []const u8,
/// The version number of this document. If an optional versioned text document
/// identifier is sent from the server to the client and the file is not
/// open in the editor (the server has not received an open notification
/// before) the server can send `null` to indicate that the version is
/// known and the content on disk is the master (as specified with document
/// content ownership).
///
/// The version number of a document will increase after each change,
/// including undo/redo. The number doesn't need to be consecutive.
version: ?integer,
};
/// Id of a request
pub const RequestId = union(enum) {
string: []const u8,
integer: i64,
float: f64,
};
pub const TextDocument = struct {
uri: []const u8,
// This is a substring of mem starting at 0
text: [:0]const u8,
// This holds the memory that we have actually allocated.
mem: []u8,
const Held = struct {
document: *const TextDocument,
popped: u8,
start_index: usize,
end_index: usize,
pub fn data(self: @This()) [:0]const u8 {
return self.document.mem[self.start_index..self.end_index :0];
}
pub fn release(self: *@This()) void {
self.document.mem[self.end_index] = self.popped;
}
};
pub fn borrowNullTerminatedSlice(self: *const @This(), start_idx: usize, end_idx: usize) Held {
std.debug.assert(end_idx >= start_idx);
const popped_char = self.mem[end_idx];
self.mem[end_idx] = 0;
return .{
.document = self,
.popped = popped_char,
.start_index = start_idx,
.end_index = end_idx,
};
}
};
pub const WorkspaceEdit = struct {
changes: ?std.StringHashMap([]TextEdit),
pub fn jsonStringify(self: WorkspaceEdit, options: json.StringifyOptions, writer: anytype) @TypeOf(writer).Error!void {
try writer.writeByte('{');
if (self.changes) |changes| {
try writer.writeAll("\"changes\": {");
var it = changes.iterator();
var idx: usize = 0;
while (it.next()) |entry| : (idx += 1) {
if (idx != 0) try writer.writeAll(", ");
try writer.writeByte('"');
try writer.writeAll(entry.key_ptr.*);
try writer.writeAll("\":");
try json.stringify(entry.value_ptr.*, options, writer);
}
try writer.writeByte('}');
}
try writer.writeByte('}');
}
};
pub const TextEdit = struct {
range: Range,
newText: []const u8,
};
pub const MarkupContent = struct {
pub const Kind = enum(u1) {
plaintext = 0,
markdown = 1,
pub fn jsonStringify(value: Kind, options: json.StringifyOptions, out_stream: anytype) !void {
const str = switch (value) {
.plaintext => "plaintext",
.markdown => "markdown",
};
try json.stringify(str, options, out_stream);
}
};
kind: Kind = .markdown,
value: []const u8,
};
pub const InsertTextFormat = enum(i64) {
plaintext = 1,
snippet = 2,
pub fn jsonStringify(value: InsertTextFormat, options: json.StringifyOptions, writer: anytype) !void {
try json.stringify(@enumToInt(value), options, writer);
}
};
pub const DocumentSymbol = struct {
const Kind = enum(u32) {
file = 1,
module = 2,
namespace = 3,
package = 4,
class = 5,
method = 6,
property = 7,
field = 8,
constructor = 9,
@"enum" = 10,
interface = 11,
function = 12,
variable = 13,
constant = 14,
string = 15,
number = 16,
boolean = 17,
array = 18,
object = 19,
key = 20,
@"null" = 21,
enum_member = 22,
@"struct" = 23,
event = 24,
operator = 25,
type_parameter = 26,
pub fn jsonStringify(value: Kind, options: json.StringifyOptions, writer: anytype) !void {
try json.stringify(@enumToInt(value), options, writer);
}
};
name: []const u8,
detail: ?[]const u8 = null,
kind: Kind,
deprecated: bool = false,
range: Range,
selectionRange: Range,
children: []const DocumentSymbol = &[_]DocumentSymbol{},
};
pub const WorkspaceFolder = struct {
uri: []const u8,
name: []const u8,
}; | src/types/common.zig |
const std = @import("std");
const interop = @import("interop.zig");
const ascii = std.ascii;
const testing = std.testing;
pub const NativeType = enum { Void, Control, Canvas, Dialog, Image, Menu, Other };
pub const Error = error{
///
/// Open function must be called before any action
NotInitialized,
///
/// Only in UNIX can fail to open, because X-Windows may be not initialized.
OpenFailed,
///
/// Action cannot be executed (IUP_ERROR).
InvalidAction,
///
/// Wrong child usage
InvalidChild,
///
/// Wrong element usage
InvalidElement,
};
pub const CallbackResult = error{
///
/// Returning this error inside a callback function means that this event must be ignored and not processed by the control and not propagated
/// Used in keyboard event handlers for example
Ignore,
///
/// Returning this error inside a callback function means that this event will be propagated to the parent of the element receiving it.
/// Used in keyboard event handlers for example
Continue,
///
/// Returning this error inside a callback function means that this event will end the application loop
Close,
};
pub const masks = struct {
pub const float = "[+/-]?(/d+/.?/d*|/./d+)";
pub const u_float = "(/d+/.?/d*|/./d+)";
pub const e_float = "[+/-]?(/d+/.?/d*|/./d+)([eE][+/-]?/d+)?";
pub const ue_float = "(/d+/.?/d*|/./d+)([eE][+/-]?/d+)?";
pub const float_comma = "[+/-]?(/d+/,?/d*|/,/d+)";
pub const u_float_comma = "(/d+/,?/d*|/,/d+)";
pub const int = "[+/-]?/d+";
pub const u_int = "/d+";
};
pub const ScreenSize = union(enum) {
Full,
Half,
Third,
Quarter,
Eighth,
Size: u32,
pub fn parse(value: []const u8) ?ScreenSize {
if (ascii.eqlIgnoreCase(value, @tagName(.Full))) return .Full;
if (ascii.eqlIgnoreCase(value, @tagName(.Half))) return .Half;
if (ascii.eqlIgnoreCase(value, @tagName(.Third))) return .Third;
if (ascii.eqlIgnoreCase(value, @tagName(.Quarter))) return .Quarter;
if (ascii.eqlIgnoreCase(value, @tagName(.Eighth))) return .Eighth;
if (std.fmt.parseInt(u32, value, 10)) |size| {
return ScreenSize{ .Size = size };
} else |_| {
return null;
}
}
};
test "ScreenSize Parse" {
try testing.expect(ScreenSize.parse("FULL").? == .Full);
try testing.expect(ScreenSize.parse("HALF").? == .Half);
try testing.expect(ScreenSize.parse("THIRD").? == .Third);
try testing.expect(ScreenSize.parse("QUARTER").? == .Quarter);
try testing.expect(ScreenSize.parse("EIGHTH").? == .Eighth);
try testing.expect(ScreenSize.parse("10").?.Size == 10);
try testing.expect(ScreenSize.parse("ZZZ") == null);
}
pub const DialogSize = struct {
width: ?ScreenSize,
height: ?ScreenSize,
pub fn parse(value: []const u8) DialogSize {
var iterator = std.mem.split(u8, value, "x");
var ret = DialogSize{
.width = null,
.height = null,
};
if (iterator.next()) |first_value| {
ret.width = ScreenSize.parse(first_value);
}
if (iterator.next()) |second_value| {
ret.height = ScreenSize.parse(second_value);
}
return ret;
}
pub fn toString(self: DialogSize, buffer: []u8) [:0]const u8 {
return screenSizeToString(buffer, self.width, self.height);
}
pub fn screenSizeToString(buffer: []u8, width: ?ScreenSize, height: ?ScreenSize) [:0]const u8 {
var fba = std.heap.FixedBufferAllocator.init(buffer);
var allocator = fba.allocator();
var builder = std.ArrayList(u8).init(allocator);
defer builder.deinit();
const values: [2]?ScreenSize = .{ width, height };
for (values) |item, i| {
if (i > 0) builder.appendSlice("x") catch unreachable;
if (item) |value| {
if (value == .Size) {
var str = std.fmt.allocPrint(allocator, "{}", .{value.Size}) catch unreachable;
defer allocator.free(str);
builder.appendSlice(str) catch unreachable;
} else {
for (@tagName(value)) |char| {
builder.append(ascii.toUpper(char)) catch unreachable;
}
}
}
}
return builder.toOwnedSliceSentinel(0) catch unreachable;
}
};
test "DialogSize Parse" {
try testing.expect(expectDialogSize("FULLxFULL", .Full, .Full));
try testing.expect(expectDialogSize("QUARTERxQUARTER", .Quarter, .Quarter));
try testing.expect(expectDialogSize("HALF", .Half, null));
try testing.expect(expectDialogSize("HALFx", .Half, null));
try testing.expect(expectDialogSize("xHALF", null, .Half));
try testing.expect(expectDialogSize("10x20", ScreenSize{ .Size = 10 }, ScreenSize{ .Size = 20 }));
try testing.expect(expectDialogSize("x", null, null));
try testing.expect(expectDialogSize("", null, null));
}
test "DialogSize ToString" {
var buffer: [128]u8 = undefined;
try testing.expect(ascii.endsWithIgnoreCase(DialogSize.screenSizeToString(&buffer, .Full, .Full), "FULLxFULL"));
try testing.expect(ascii.endsWithIgnoreCase(DialogSize.screenSizeToString(&buffer, .Quarter, .Quarter), "QUARTERxQUARTER"));
try testing.expect(ascii.endsWithIgnoreCase(DialogSize.screenSizeToString(&buffer, .Half, null), "HALFx"));
try testing.expect(ascii.endsWithIgnoreCase(DialogSize.screenSizeToString(&buffer, null, .Half), "xHALF"));
try testing.expect(ascii.endsWithIgnoreCase(DialogSize.screenSizeToString(&buffer, ScreenSize{ .Size = 10 }, ScreenSize{ .Size = 20 }), "10x20"));
try testing.expect(ascii.endsWithIgnoreCase(DialogSize.screenSizeToString(&buffer, null, null), "x"));
}
fn expectDialogSize(str: []const u8, width: ?ScreenSize, height: ?ScreenSize) bool {
var dialog_size = DialogSize.parse(str);
return std.meta.eql(dialog_size.width, width) and std.meta.eql(dialog_size.height, height);
}
pub const DialogPosX = union(enum(i32)) {
Left = interop.consts.IUP_LEFT,
Center = interop.consts.IUP_CENTER,
Right = interop.consts.IUP_RIGHT,
MousePos = interop.consts.IUP_MOUSEPOS,
Current = interop.consts.IUP_CURRENT,
CenterParent = interop.consts.IUP_CENTERPARENT,
LeftParent = interop.consts.IUP_LEFTPARENT,
RightParent = interop.consts.IUP_RIGHTPARENT,
X: i32,
};
pub const DialogPosY = union(enum(i32)) {
Top = interop.consts.IUP_TOP,
Center = interop.consts.IUP_CENTER,
Bottom = interop.consts.IUP_BOTTOM,
MousePos = interop.consts.IUP_MOUSEPOS,
CenterParent = interop.consts.IUP_CENTERPARENT,
Current = interop.consts.IUP_CURRENT,
TopParent = interop.consts.IUP_TOPPARENT,
BottomParent = interop.consts.IUP_BOTTOMPARENT,
Y: i32,
};
pub const Margin = struct {
horiz: i32,
vert: i32,
pub fn parse(value: [:0]const u8) Margin {
const separator = 'x';
var horiz: ?i32 = null;
var vert: ?i32 = null;
interop.strToIntInt(value, separator, &horiz, &vert);
return .{ .horiz = horiz orelse 0, .vert = vert orelse 0 };
}
pub fn toString(self: Margin, buffer: []u8) [:0]const u8 {
return interop.intIntToString(buffer, self.horiz, self.vert, 'x');
}
pub fn intIntToString(buffer: []u8, horiz: i32, vert: i32) [:0]const u8 {
return interop.intIntToString(buffer, horiz, vert, 'x');
}
};
test "Margin Parse" {
var margin: Margin = undefined;
margin = Margin.parse("1x2");
try testing.expect(margin.horiz == 1);
try testing.expect(margin.vert == 2);
}
test "Margin ToString" {
var buffer: [128]u8 = undefined;
var margin: Margin = undefined;
margin = Margin{ .horiz = 1, .vert = 2 };
try testing.expect(std.mem.eql(u8, margin.toString(&buffer), "1x2"));
}
pub const Size = struct {
width: ?i32,
height: ?i32,
pub fn parse(value: [:0]const u8) Size {
const separator = 'x';
var width: ?i32 = null;
var height: ?i32 = null;
interop.strToIntInt(value, separator, &width, &height);
return .{ .width = width, .height = height };
}
pub fn toString(self: Size, buffer: []u8) [:0]const u8 {
return intIntToString(buffer, self.width, self.height);
}
pub fn intIntToString(buffer: []u8, width: ?i32, height: ?i32) [:0]const u8 {
var fbs = std.io.fixedBufferStream(buffer);
if (width) |value| {
std.fmt.format(fbs.writer(), "{}", .{value}) catch unreachable;
}
if (width != null or height != null) {
std.fmt.format(fbs.writer(), "x", .{}) catch unreachable;
}
if (height) |value| {
std.fmt.format(fbs.writer(), "{}", .{value}) catch unreachable;
}
buffer[fbs.pos] = 0;
return buffer[0..fbs.pos :0];
}
};
test "Size Parse" {
var size: Size = undefined;
size = Size.parse("1x2");
try testing.expect(size.width.? == 1);
try testing.expect(size.height.? == 2);
size = Size.parse("1x");
try testing.expect(size.width.? == 1);
try testing.expect(size.height == null);
size = Size.parse("x2");
try testing.expect(size.width == null);
try testing.expect(size.height.? == 2);
size = Size.parse("");
try testing.expect(size.width == null);
try testing.expect(size.height == null);
}
test "Size ToString" {
var buffer: [128]u8 = undefined;
var size: Size = undefined;
size = Size{ .width = 1, .height = 2 };
try testing.expect(std.mem.eql(u8, size.toString(&buffer), "1x2"));
size = Size{ .width = 1, .height = null };
try testing.expect(std.mem.eql(u8, size.toString(&buffer), "1x"));
size = Size{ .width = null, .height = 2 };
try testing.expect(std.mem.eql(u8, size.toString(&buffer), "x2"));
size = Size{ .width = null, .height = null };
try testing.expect(std.mem.eql(u8, size.toString(&buffer), ""));
}
pub const XYPos = struct {
x: i32,
y: i32,
const Self = @This();
pub fn parse(value: [:0]const u8, comptime separator: u8) Self {
var x: ?i32 = null;
var y: ?i32 = null;
interop.strToIntInt(value, separator, &x, &y);
return .{ .x = x orelse 0, .y = y orelse 0 };
}
pub fn toString(self: Self, buffer: []u8, comptime separator: u8) [:0]const u8 {
return interop.intIntToString(buffer, self.x, self.y, separator);
}
pub fn intIntToString(buffer: []u8, x: i32, y: i32, comptime separator: u8) [:0]const u8 {
return interop.intIntToString(buffer, x, y, separator);
}
};
test "XYPos Parse" {
var pos: XYPos = undefined;
pos = XYPos.parse("1x2", 'x');
try testing.expect(pos.x == 1);
try testing.expect(pos.y == 2);
pos = XYPos.parse("1,2", ',');
try testing.expect(pos.x == 1);
try testing.expect(pos.y == 2);
pos = XYPos.parse("1:2", ':');
try testing.expect(pos.x == 1);
try testing.expect(pos.y == 2);
pos = XYPos.parse("1;2", ';');
try testing.expect(pos.x == 1);
try testing.expect(pos.y == 2);
}
test "XYPos ToString" {
var buffer: [128]u8 = undefined;
var pos: XYPos = undefined;
pos = XYPos{ .x = 1, .y = 2 };
try testing.expect(std.mem.eql(u8, pos.toString(&buffer, 'x'), "1x2"));
try testing.expect(std.mem.eql(u8, pos.toString(&buffer, ','), "1,2"));
try testing.expect(std.mem.eql(u8, pos.toString(&buffer, ';'), "1;2"));
try testing.expect(std.mem.eql(u8, pos.toString(&buffer, ':'), "1:2"));
}
pub const LinColPos = struct {
lin: i32,
col: i32,
const Self = @This();
pub fn parse(value: [:0]const u8, comptime separator: u8) Self {
var lin: ?i32 = null;
var col: ?i32 = null;
interop.strToIntInt(value, separator, &lin, &col);
return .{ .col = col orelse 0, .lin = lin orelse 0 };
}
pub fn toString(self: Self, buffer: []u8, comptime separator: u8) [:0]const u8 {
return interop.intIntToString(buffer, self.lin, self.col, separator);
}
pub fn intIntToString(buffer: []u8, x: i32, y: i32, comptime separator: u8) [:0]const u8 {
return interop.intIntToString(buffer, x, y, separator);
}
};
test "LinColPos Parse" {
var pos: LinColPos = undefined;
pos = LinColPos.parse("1x2", 'x');
try testing.expect(pos.lin == 1);
try testing.expect(pos.col == 2);
pos = LinColPos.parse("1,2", ',');
try testing.expect(pos.lin == 1);
try testing.expect(pos.col == 2);
pos = LinColPos.parse("1:2", ':');
try testing.expect(pos.lin == 1);
try testing.expect(pos.col == 2);
pos = LinColPos.parse("1;2", ';');
try testing.expect(pos.lin == 1);
try testing.expect(pos.col == 2);
}
test "LinColPos ToString" {
var buffer: [128]u8 = undefined;
var pos: LinColPos = undefined;
pos = LinColPos{ .lin = 1, .col = 2 };
try testing.expect(std.mem.eql(u8, pos.toString(&buffer, 'x'), "1x2"));
try testing.expect(std.mem.eql(u8, pos.toString(&buffer, ','), "1,2"));
try testing.expect(std.mem.eql(u8, pos.toString(&buffer, ';'), "1;2"));
try testing.expect(std.mem.eql(u8, pos.toString(&buffer, ':'), "1:2"));
}
pub const Range = struct {
begin: i32,
end: i32,
const Self = @This();
pub fn parse(value: [:0]const u8, comptime separator: u8) Self {
var begin: ?i32 = null;
var end: ?i32 = null;
interop.strToIntInt(value, separator, &begin, &end);
return .{ .begin = begin orelse 0, .end = end orelse 0 };
}
pub fn toString(self: Self, buffer: []u8, comptime separator: u8) [:0]const u8 {
return interop.intIntToString(buffer, self.begin, self.end, separator);
}
pub fn intIntToString(buffer: []u8, begin: i32, end: i32, comptime separator: u8) [:0]const u8 {
return interop.intIntToString(buffer, begin, end, separator);
}
};
test "Range Parse" {
var range: Range = undefined;
range = Range.parse("1x2", 'x');
try testing.expect(range.begin == 1);
try testing.expect(range.end == 2);
range = Range.parse("1,2", ',');
try testing.expect(range.begin == 1);
try testing.expect(range.end == 2);
range = Range.parse("1:2", ':');
try testing.expect(range.begin == 1);
try testing.expect(range.end == 2);
range = Range.parse("1;2", ';');
try testing.expect(range.begin == 1);
try testing.expect(range.end == 2);
}
test "Range ToString" {
var buffer: [128]u8 = undefined;
var range: Range = undefined;
range = Range{ .begin = 1, .end = 2 };
try testing.expect(std.mem.eql(u8, range.toString(&buffer, 'x'), "1x2"));
try testing.expect(std.mem.eql(u8, range.toString(&buffer, ','), "1,2"));
try testing.expect(std.mem.eql(u8, range.toString(&buffer, ';'), "1;2"));
try testing.expect(std.mem.eql(u8, range.toString(&buffer, ':'), "1:2"));
}
pub const Date = struct {
year: u16,
month: u8,
day: u8,
const Self = @This();
pub fn parse(value: [:0]const u8) ?Self {
var year: ?u16 = null;
var month: ?u16 = null;
var day: ?u16 = null;
var iterator = std.mem.split(u8, value, "/");
for ([3]*?u16{ &year, &month, &day }) |ref| {
if (iterator.next()) |part| {
if (std.fmt.parseInt(u16, part, 10)) |int| {
ref.* = int;
} else |_| {
break;
}
}
}
if (year != null and
month != null and
day != null)
{
return Self{
.year = year.?,
.month = @intCast(u8, month.?),
.day = @intCast(u8, day.?),
};
} else {
return null;
}
}
pub fn toString(self: Self, buffer: []u8) [:0]const u8 {
var fbs = std.io.fixedBufferStream(buffer);
std.fmt.format(fbs.writer(), "{}/{}/{}\x00", .{ self.year, self.month, self.day }) catch unreachable;
return buffer[0 .. fbs.pos - 1 :0];
}
};
test "Date Parse" {
var date = Date.parse("2015/04/03") orelse unreachable;
try testing.expect(date.year == 2015);
try testing.expect(date.month == 4);
try testing.expect(date.day == 3);
try testing.expect(Date.parse("bad/1/1") == null);
try testing.expect(Date.parse("") == null);
}
test "Date ToString" {
var buffer: [128]u8 = undefined;
var date: Date = undefined;
date = Date{ .year = 2025, .month = 12, .day = 5 };
try testing.expect(std.mem.eql(u8, date.toString(&buffer), "2025/12/5"));
}
pub const Rgb = struct {
r: u8,
g: u8,
b: u8,
a: ?u8 = null,
alias: ?[:0]const u8 = null,
pub const BG_COLOR = Rgb{ .alias = "BGCOLOR", .r = 0, .g = 0, .b = 0 };
pub const FG_COLOR = Rgb{ .alias = "FGCOLOR", .r = 0, .g = 0, .b = 0 };
};
pub const keys = struct {
pub const PAUSE = 0xFF13;
pub const ESC = 0xFF1B;
pub const HOME = 0xFF50;
pub const LEFT = 0xFF51;
pub const UP = 0xFF52;
pub const RIGHT = 0xFF53;
pub const DOWN = 0xFF54;
pub const PGUP = 0xFF55;
pub const PGDN = 0xFF56;
pub const END = 0xFF57;
pub const MIDDLE = 0xFF0B;
pub const Print = 0xFF61;
pub const INS = 0xFF63;
pub const Menu = 0xFF67;
pub const DEL = 0xFFFF;
pub const F1 = 0xFFBE;
pub const F2 = 0xFFBF;
pub const F3 = 0xFFC0;
pub const F4 = 0xFFC1;
pub const F5 = 0xFFC2;
pub const F6 = 0xFFC3;
pub const F7 = 0xFFC4;
pub const F8 = 0xFFC5;
pub const F9 = 0xFFC6;
pub const F10 = 0xFFC7;
pub const F11 = 0xFFC8;
pub const F12 = 0xFFC9;
pub const F13 = 0xFFCA;
pub const F14 = 0xFFCB;
pub const F15 = 0xFFCC;
pub const F16 = 0xFFCD;
pub const F17 = 0xFFCE;
pub const F18 = 0xFFCF;
pub const F19 = 0xFFD0;
pub const F20 = 0xFFD1;
pub const LSHIFT = 0xFFE1;
pub const RSHIFT = 0xFFE2;
pub const LCTRL = 0xFFE3;
pub const RCTRL = 0xFFE4;
pub const LALT = 0xFFE9;
pub const RALT = 0xFFEA;
pub const NUM = 0xFF7F;
pub const SCROLL = 0xFF14;
pub const CAPS = 0xFFE5;
pub const CLEAR = 0xFFD2;
pub const HELP = 0xFFD3;
}; | src/commons.zig |
const std = @import("std");
const mem = std.mem;
const Allocator = mem.Allocator;
pub const ScratchAllocator = struct {
allocator: Allocator,
backup_allocator: *Allocator,
end_index: usize,
buffer: []u8,
pub fn init(allocator: *Allocator) ScratchAllocator {
const scratch_buffer = allocator.alloc(u8, 2 * 1024 * 1024) catch unreachable;
return ScratchAllocator{
.allocator = Allocator{
.allocFn = alloc,
.resizeFn = Allocator.noResize,
},
.backup_allocator = allocator,
.buffer = scratch_buffer,
.end_index = 0,
};
}
fn alloc(allocator: *Allocator, n: usize, ptr_align: u29, len_align: u29, ret_addr: usize) ![]u8 {
const self = @fieldParentPtr(ScratchAllocator, "allocator", allocator);
const addr = @ptrToInt(self.buffer.ptr) + self.end_index;
const adjusted_addr = mem.alignForward(addr, ptr_align);
const adjusted_index = self.end_index + (adjusted_addr - addr);
const new_end_index = adjusted_index + n;
if (new_end_index > self.buffer.len) {
// if more memory is requested then we have in our buffer leak like a sieve!
if (n > self.buffer.len) {
std.debug.warn("\n---------\nwarning: tmp allocated more than is in our temp allocator. This memory WILL leak!\n--------\n", .{});
return self.allocator.allocFn(allocator, n, ptr_align, len_align, ret_addr);
}
const result = self.buffer[0..n];
self.end_index = n;
return result;
}
const result = self.buffer[adjusted_index..new_end_index];
self.end_index = new_end_index;
return result;
}
};
test "scratch allocator" {
var allocator_instance = ScratchAllocator.init(@import("mem.zig").allocator);
var slice = try allocator_instance.allocator.alloc(*i32, 100);
std.testing.expect(slice.len == 100);
_ = try allocator_instance.allocator.create(i32);
slice = try allocator_instance.allocator.realloc(slice, 20000);
std.testing.expect(slice.len == 20000);
allocator_instance.allocator.free(slice);
} | src/mem/scratch_allocator.zig |
const std = @import("std");
const builtin = @import("builtin");
const tvg = @import("tvg");
extern "tinyvg" fn setResultSvg(svg_ptr: [*]const u8, svg_len: usize) void;
extern "tinyvg" fn getSourceTvg(tvg_ptr: [*]u8, tvg_len: usize) void;
extern "platform" fn platformPanic(ptr: [*]const u8, len: usize) void;
extern "platform" fn platformLogWrite(ptr: [*]const u8, len: usize) void;
extern "platform" fn platformLogFlush() void;
fn convertToSvgSafe(tvg_len: usize) !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
const src_buffer = try allocator.alloc(u8, tvg_len);
defer allocator.free(src_buffer);
getSourceTvg(src_buffer.ptr, tvg_len);
var destination = std.ArrayList(u8).init(allocator);
defer destination.deinit();
try tvg.svg.renderBinary(allocator, src_buffer[0..tvg_len], destination.writer());
setResultSvg(destination.items.ptr, destination.items.len);
}
export fn convertToSvg(tvg_len: usize) u32 {
convertToSvgSafe(tvg_len) catch |err| {
return switch (err) {
error.OutOfMemory => 1,
error.EndOfStream => 2,
error.InvalidData => 3,
error.UnsupportedVersion => 4,
error.UnsupportedColorFormat => 5,
};
};
return 0;
}
const WriteError = error{};
const LogWriter = std.io.Writer(void, WriteError, writeLog);
fn writeLog(_: void, msg: []const u8) WriteError!usize {
platformLogWrite(msg.ptr, msg.len);
return msg.len;
}
/// Overwrite default log handler
pub fn log(
comptime message_level: std.log.Level,
comptime scope: @Type(.EnumLiteral),
comptime format: []const u8,
args: anytype,
) void {
if (builtin.mode != .ReleaseSmall) {
const level_txt = switch (message_level) {
.err => "error",
.warn => "warning",
.info => "info",
.debug => "debug",
};
const prefix2 = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): ";
(LogWriter{ .context = {} }).print(level_txt ++ prefix2 ++ format ++ "\n", args) catch return;
platformLogFlush();
}
}
/// Overwrite default panic handler
pub fn panic(msg: []const u8, _: ?*std.builtin.StackTrace) noreturn {
// std.log.crit("panic: {s}", .{msg});
platformPanic(msg.ptr, msg.len);
unreachable;
} | src/polyfill/tinyvg.zig |
const std = @import("std");
const os = std.os;
const mem = std.mem;
const testing = std.testing;
const assert = std.debug.assert;
test "communication via seqpacket unix domain socket" {
const socket = try os.socket(
os.AF_UNIX,
os.SOCK_SEQPACKET | os.SOCK_CLOEXEC,
os.PF_UNIX,
);
defer os.closeSocket(socket);
const runtime_dir = try std.fmt.allocPrint(testing.allocator, "/var/run/user/1000", .{});
const subpath = "/kisa";
var path_builder = std.ArrayList(u8).fromOwnedSlice(testing.allocator, runtime_dir);
defer path_builder.deinit();
try path_builder.appendSlice(subpath);
std.fs.makeDirAbsolute(path_builder.items) catch |err| switch (err) {
error.PathAlreadyExists => {},
else => return err,
};
const filename = try std.fmt.allocPrint(testing.allocator, "{d}", .{os.linux.getpid()});
defer testing.allocator.free(filename);
try path_builder.append('/');
try path_builder.appendSlice(filename);
std.fs.deleteFileAbsolute(path_builder.items) catch |err| switch (err) {
error.FileNotFound => {},
else => return err,
};
const addr = try testing.allocator.create(os.sockaddr_un);
defer testing.allocator.destroy(addr);
addr.* = os.sockaddr_un{ .path = undefined };
mem.copy(u8, &addr.path, path_builder.items);
addr.path[path_builder.items.len] = 0; // null-terminated string
const sockaddr = @ptrCast(*os.sockaddr, addr);
var addrlen: os.socklen_t = @sizeOf(@TypeOf(addr.*));
try os.bind(socket, sockaddr, addrlen);
const pid = try os.fork();
if (pid == 0) {
// Client
const client_socket = try os.socket(
os.AF_UNIX,
os.SOCK_SEQPACKET | os.SOCK_CLOEXEC,
os.PF_UNIX,
);
defer os.closeSocket(client_socket);
const message = try std.fmt.allocPrint(testing.allocator, "hello from client!", .{});
defer testing.allocator.free(message);
var client_connected = false;
var connect_attempts: u8 = 25;
while (!client_connected) {
os.connect(client_socket, sockaddr, addrlen) catch |err| switch (err) {
error.ConnectionRefused => {
// If server is not yet listening, wait a bit.
if (connect_attempts == 0) return err;
std.time.sleep(std.time.ns_per_ms * 10);
connect_attempts -= 1;
continue;
},
else => return err,
};
client_connected = true;
}
var bytes_sent = try os.send(client_socket, message, os.MSG_EOR);
assert(message.len == bytes_sent);
bytes_sent = try os.send(client_socket, message, os.MSG_EOR);
assert(message.len == bytes_sent);
var buf: [256]u8 = undefined;
var bytes_read = try os.recv(client_socket, &buf, 0);
std.debug.print("\nreceived on client: {s}\n", .{buf[0..bytes_read]});
} else {
// Server
std.time.sleep(std.time.ns_per_ms * 200);
try os.listen(socket, 10);
const accepted_socket = try os.accept(socket, null, null, os.SOCK_CLOEXEC);
defer os.closeSocket(accepted_socket);
var buf: [256]u8 = undefined;
var counter: u8 = 0;
while (counter < 2) : (counter += 1) {
const bytes_read = try os.recv(accepted_socket, &buf, 0);
std.debug.print("\n{d}: received on server: {s}\n", .{ counter, buf[0..bytes_read] });
}
const message = try std.fmt.allocPrint(testing.allocator, "hello from server!", .{});
defer testing.allocator.free(message);
var bytes_sent = try os.send(accepted_socket, message, os.MSG_EOR);
assert(message.len == bytes_sent);
}
} | poc/ipc_seqpacket_socket.zig |
const std = @import("std");
const c = @import("c.zig").c;
const Interface = @import("Interface.zig");
const RequestAdapterOptions = Interface.RequestAdapterOptions;
const RequestAdapterErrorCode = Interface.RequestAdapterErrorCode;
const RequestAdapterError = Interface.RequestAdapterError;
const RequestAdapterCallback = Interface.RequestAdapterCallback;
const RequestAdapterResponse = Interface.RequestAdapterResponse;
const Adapter = @import("Adapter.zig");
const RequestDeviceErrorCode = Adapter.RequestDeviceErrorCode;
const RequestDeviceError = Adapter.RequestDeviceError;
const RequestDeviceCallback = Adapter.RequestDeviceCallback;
const RequestDeviceResponse = Adapter.RequestDeviceResponse;
const Limits = @import("data.zig").Limits;
const Color = @import("data.zig").Color;
const Extent3D = @import("data.zig").Extent3D;
const Device = @import("Device.zig");
const Surface = @import("Surface.zig");
const Queue = @import("Queue.zig");
const CommandBuffer = @import("CommandBuffer.zig");
const ShaderModule = @import("ShaderModule.zig");
const SwapChain = @import("SwapChain.zig");
const TextureView = @import("TextureView.zig");
const Texture = @import("Texture.zig");
const Sampler = @import("Sampler.zig");
const RenderPipeline = @import("RenderPipeline.zig");
const RenderPassEncoder = @import("RenderPassEncoder.zig");
const RenderBundleEncoder = @import("RenderBundleEncoder.zig");
const RenderBundle = @import("RenderBundle.zig");
const QuerySet = @import("QuerySet.zig");
const PipelineLayout = @import("PipelineLayout.zig");
const ExternalTexture = @import("ExternalTexture.zig");
const BindGroup = @import("BindGroup.zig");
const BindGroupLayout = @import("BindGroupLayout.zig");
const Buffer = @import("Buffer.zig");
const CommandEncoder = @import("CommandEncoder.zig");
const ComputePassEncoder = @import("ComputePassEncoder.zig");
const ComputePipeline = @import("ComputePipeline.zig");
const PresentMode = @import("enums.zig").PresentMode;
const IndexFormat = @import("enums.zig").IndexFormat;
const ErrorType = @import("enums.zig").ErrorType;
const ErrorFilter = @import("enums.zig").ErrorFilter;
const LoggingType = @import("enums.zig").LoggingType;
const Feature = @import("enums.zig").Feature;
const ImageCopyBuffer = @import("structs.zig").ImageCopyBuffer;
const ImageCopyTexture = @import("structs.zig").ImageCopyTexture;
const ErrorCallback = @import("structs.zig").ErrorCallback;
const LoggingCallback = @import("structs.zig").LoggingCallback;
const NativeInstance = @This();
/// The WGPUInstance that is wrapped by this native instance.
instance: c.WGPUInstance,
/// Wraps a native WGPUInstance to provide an implementation of the gpu.Interface.
pub fn wrap(instance: *anyopaque) NativeInstance {
return .{ .instance = @ptrCast(c.WGPUInstance, instance) };
}
const interface_vtable = Interface.VTable{
.reference = (struct {
pub fn reference(ptr: *anyopaque) void {
const native = @ptrCast(*NativeInstance, @alignCast(std.meta.alignment(*NativeInstance), ptr));
c.wgpuInstanceReference(native.instance);
}
}).reference,
.release = (struct {
pub fn release(ptr: *anyopaque) void {
const native = @ptrCast(*NativeInstance, @alignCast(std.meta.alignment(*NativeInstance), ptr));
c.wgpuInstanceRelease(native.instance);
}
}).release,
.requestAdapter = (struct {
pub fn requestAdapter(
ptr: *anyopaque,
options: *const RequestAdapterOptions,
callback: *RequestAdapterCallback,
) void {
const native = @ptrCast(*NativeInstance, @alignCast(std.meta.alignment(*NativeInstance), ptr));
const opt = c.WGPURequestAdapterOptions{
.nextInChain = null,
.compatibleSurface = if (options.compatible_surface) |surface| @ptrCast(c.WGPUSurface, surface.ptr) else null,
.powerPreference = @enumToInt(options.power_preference),
.forceFallbackAdapter = options.force_fallback_adapter,
};
const cCallback = (struct {
pub fn cCallback(status: c.WGPURequestAdapterStatus, adapter: c.WGPUAdapter, message: [*c]const u8, userdata: ?*anyopaque) callconv(.C) void {
const callback_info = @ptrCast(*RequestAdapterCallback, @alignCast(std.meta.alignment(*RequestAdapterCallback), userdata.?));
// Store the response into a field on the native instance for later reading.
const response = if (status == c.WGPURequestAdapterStatus_Success) RequestAdapterResponse{
.adapter = wrapAdapter(adapter.?),
} else RequestAdapterResponse{
.err = Interface.RequestAdapterError{
.message = std.mem.span(message),
.code = switch (status) {
c.WGPURequestAdapterStatus_Unavailable => RequestAdapterErrorCode.Unavailable,
c.WGPURequestAdapterStatus_Error => RequestAdapterErrorCode.Error,
c.WGPURequestAdapterStatus_Unknown => RequestAdapterErrorCode.Unknown,
else => unreachable,
},
},
};
callback_info.type_erased_callback(callback_info.type_erased_ctx, response);
}
}).cCallback;
c.wgpuInstanceRequestAdapter(native.instance, &opt, cCallback, callback);
}
}).requestAdapter,
};
/// Returns the gpu.Interface for interacting with this native instance.
pub fn interface(native: *NativeInstance) Interface {
return .{
.ptr = native,
.vtable = &interface_vtable,
};
}
pub fn createSurface(native: *const NativeInstance, descriptor: *const Surface.Descriptor) Surface {
const surface = switch (descriptor.*) {
.metal_layer => |src| blk: {
var desc: c.WGPUSurfaceDescriptorFromMetalLayer = undefined;
desc.chain.next = null;
desc.chain.sType = c.WGPUSType_SurfaceDescriptorFromMetalLayer;
desc.layer = src.layer;
break :blk c.wgpuInstanceCreateSurface(native.instance, &c.WGPUSurfaceDescriptor{
.nextInChain = @ptrCast(*c.WGPUChainedStruct, &desc),
.label = if (src.label) |l| l else null,
});
},
.windows_hwnd => |src| blk: {
var desc: c.WGPUSurfaceDescriptorFromWindowsHWND = undefined;
desc.chain.next = null;
desc.chain.sType = c.WGPUSType_SurfaceDescriptorFromWindowsHWND;
desc.hinstance = src.hinstance;
desc.hwnd = src.hwnd;
break :blk c.wgpuInstanceCreateSurface(native.instance, &c.WGPUSurfaceDescriptor{
.nextInChain = @ptrCast(*c.WGPUChainedStruct, &desc),
.label = if (src.label) |l| l else null,
});
},
.windows_core_window => |src| blk: {
var desc: c.WGPUSurfaceDescriptorFromWindowsCoreWindow = undefined;
desc.chain.next = null;
desc.chain.sType = c.WGPUSType_SurfaceDescriptorFromWindowsCoreWindow;
desc.coreWindow = src.core_window;
break :blk c.wgpuInstanceCreateSurface(native.instance, &c.WGPUSurfaceDescriptor{
.nextInChain = @ptrCast(*c.WGPUChainedStruct, &desc),
.label = if (src.label) |l| l else null,
});
},
.windows_swap_chain_panel => |src| blk: {
var desc: c.WGPUSurfaceDescriptorFromWindowsSwapChainPanel = undefined;
desc.chain.next = null;
desc.chain.sType = c.WGPUSType_SurfaceDescriptorFromWindowsSwapChainPanel;
desc.swapChainPanel = src.swap_chain_panel;
break :blk c.wgpuInstanceCreateSurface(native.instance, &c.WGPUSurfaceDescriptor{
.nextInChain = @ptrCast(*c.WGPUChainedStruct, &desc),
.label = if (src.label) |l| l else null,
});
},
.xlib => |src| blk: {
var desc: c.WGPUSurfaceDescriptorFromXlibWindow = undefined;
desc.chain.next = null;
desc.chain.sType = c.WGPUSType_SurfaceDescriptorFromXlibWindow;
desc.display = src.display;
desc.window = src.window;
break :blk c.wgpuInstanceCreateSurface(native.instance, &c.WGPUSurfaceDescriptor{
.nextInChain = @ptrCast(*c.WGPUChainedStruct, &desc),
.label = if (src.label) |l| l else null,
});
},
.canvas_html_selector => |src| blk: {
var desc: c.WGPUSurfaceDescriptorFromCanvasHTMLSelector = undefined;
desc.chain.next = null;
desc.chain.sType = c.WGPUSType_SurfaceDescriptorFromCanvasHTMLSelector;
desc.selector = src.selector;
break :blk c.wgpuInstanceCreateSurface(native.instance, &c.WGPUSurfaceDescriptor{
.nextInChain = @ptrCast(*c.WGPUChainedStruct, &desc),
.label = if (src.label) |l| l else null,
});
},
};
return Surface{
.ptr = surface.?,
.vtable = &surface_vtable,
};
}
const surface_vtable = Surface.VTable{
.reference = (struct {
pub fn reference(ptr: *anyopaque) void {
c.wgpuSurfaceReference(@ptrCast(c.WGPUSurface, ptr));
}
}).reference,
.release = (struct {
pub fn release(ptr: *anyopaque) void {
c.wgpuSurfaceRelease(@ptrCast(c.WGPUSurface, ptr));
}
}).release,
};
pub inline fn fromWGPUAdapter(adapter: *anyopaque) Adapter {
return wrapAdapter(@ptrCast(c.WGPUAdapter, adapter));
}
pub fn wrapAdapter(adapter: c.WGPUAdapter) Adapter {
var c_props: c.WGPUAdapterProperties = undefined;
c.wgpuAdapterGetProperties(adapter, &c_props);
const properties = Adapter.Properties{
.vendor_id = c_props.vendorID,
.device_id = c_props.deviceID,
.name = std.mem.span(c_props.name),
.driver_description = std.mem.span(c_props.driverDescription),
.adapter_type = @intToEnum(Adapter.Type, c_props.adapterType),
.backend_type = @intToEnum(Adapter.BackendType, c_props.backendType),
};
var supported_limits: c.WGPUSupportedLimits = undefined;
supported_limits.nextInChain = null;
if (!c.wgpuAdapterGetLimits(adapter.?, &supported_limits)) @panic("failed to get adapter limits (this is a bug in mach/gpu)");
var wrapped = Adapter{
.features = undefined,
.limits = @bitCast(Limits, supported_limits.limits),
.properties = properties,
// TODO: why is fallback not queryable on Dawn?
.fallback = false,
.ptr = adapter.?,
.vtable = &adapter_vtable,
};
const features_len = c.wgpuAdapterEnumerateFeatures(adapter.?, @ptrCast([*]c.WGPUFeatureName, &wrapped._features));
wrapped.features = wrapped._features[0..features_len];
return wrapped;
}
const adapter_vtable = Adapter.VTable{
.reference = (struct {
pub fn reference(ptr: *anyopaque) void {
c.wgpuAdapterReference(@ptrCast(c.WGPUAdapter, ptr));
}
}).reference,
.release = (struct {
pub fn release(ptr: *anyopaque) void {
c.wgpuAdapterRelease(@ptrCast(c.WGPUAdapter, ptr));
}
}).release,
.requestDevice = (struct {
pub fn requestDevice(
ptr: *anyopaque,
descriptor: *const Device.Descriptor,
callback: *RequestDeviceCallback,
) void {
const adapter = @ptrCast(c.WGPUAdapter, @alignCast(@alignOf(c.WGPUAdapter), ptr));
const required_limits = if (descriptor.required_limits) |l| c.WGPURequiredLimits{
.nextInChain = null,
.limits = @bitCast(c.WGPULimits, l),
} else null;
const desc = c.WGPUDeviceDescriptor{
.nextInChain = null,
.label = if (descriptor.label) |l| l else null,
.requiredFeaturesCount = if (descriptor.required_features) |f| @intCast(u32, f.len) else 0,
.requiredFeatures = if (descriptor.required_features) |f| @ptrCast([*]const c_uint, f.ptr) else null,
.requiredLimits = if (required_limits) |*l| l else null,
.defaultQueue = if (descriptor.default_queue) |q| .{ .nextInChain = null, .label = q.label } else .{ .nextInChain = null, .label = null },
};
const cCallback = (struct {
pub fn cCallback(status: c.WGPURequestDeviceStatus, device: c.WGPUDevice, message: [*c]const u8, userdata: ?*anyopaque) callconv(.C) void {
const callback_info = @ptrCast(*RequestDeviceCallback, @alignCast(std.meta.alignment(*RequestDeviceCallback), userdata.?));
const response = if (status == c.WGPURequestDeviceStatus_Success) RequestDeviceResponse{
.device = wrapDevice(device.?),
} else RequestDeviceResponse{
.err = Adapter.RequestDeviceError{
.message = std.mem.span(message),
.code = switch (status) {
c.WGPURequestDeviceStatus_Error => RequestDeviceErrorCode.Error,
c.WGPURequestDeviceStatus_Unknown => RequestDeviceErrorCode.Unknown,
else => unreachable,
},
},
};
callback_info.type_erased_callback(callback_info.type_erased_ctx, response);
}
}).cCallback;
c.wgpuAdapterRequestDevice(adapter, &desc, cCallback, callback);
}
}).requestDevice,
};
fn wrapDevice(device: c.WGPUDevice) Device {
var supported_limits: c.WGPUSupportedLimits = undefined;
supported_limits.nextInChain = null;
if (!c.wgpuDeviceGetLimits(device.?, &supported_limits)) @panic("failed to get device limits (this is a bug in mach/gpu)");
var wrapped = Device{
.features = undefined,
.limits = @bitCast(Limits, supported_limits.limits),
.ptr = device.?,
.vtable = &device_vtable,
};
const features_len = c.wgpuDeviceEnumerateFeatures(device.?, @ptrCast([*]c.WGPUFeatureName, &wrapped._features));
wrapped.features = wrapped._features[0..features_len];
return wrapped;
}
const device_vtable = Device.VTable{
.reference = (struct {
pub fn reference(ptr: *anyopaque) void {
c.wgpuDeviceReference(@ptrCast(c.WGPUDevice, ptr));
}
}).reference,
.release = (struct {
pub fn release(ptr: *anyopaque) void {
c.wgpuDeviceRelease(@ptrCast(c.WGPUDevice, ptr));
}
}).release,
.getQueue = (struct {
pub fn getQueue(ptr: *anyopaque) Queue {
return wrapQueue(c.wgpuDeviceGetQueue(@ptrCast(c.WGPUDevice, ptr)));
}
}).getQueue,
.injectError = (struct {
pub fn injectError(ptr: *anyopaque, typ: ErrorType, message: [*:0]const u8) void {
c.wgpuDeviceInjectError(@ptrCast(c.WGPUDevice, ptr), @enumToInt(typ), message);
}
}).injectError,
.loseForTesting = (struct {
pub fn loseForTesting(ptr: *anyopaque) void {
c.wgpuDeviceLoseForTesting(@ptrCast(c.WGPUDevice, ptr));
}
}).loseForTesting,
.popErrorScope = (struct {
pub fn popErrorScope(ptr: *anyopaque, callback: *ErrorCallback) bool {
const cCallback = (struct {
pub fn cCallback(
typ: c.WGPUErrorType,
message: [*c]const u8,
userdata: ?*anyopaque,
) callconv(.C) void {
const callback_info = @ptrCast(*ErrorCallback, @alignCast(std.meta.alignment(*ErrorCallback), userdata));
callback_info.type_erased_callback(
callback_info.type_erased_ctx,
@intToEnum(ErrorType, typ),
std.mem.span(message),
);
}
}).cCallback;
return c.wgpuDevicePopErrorScope(
@ptrCast(c.WGPUDevice, ptr),
cCallback,
callback,
);
}
}).popErrorScope,
.createBindGroup = (struct {
pub fn createBindGroup(ptr: *anyopaque, descriptor: *const BindGroup.Descriptor) BindGroup {
var few_entries: [16]c.WGPUBindGroupEntry = undefined;
const entries = if (descriptor.entries.len <= 8)
few_entries[0..descriptor.entries.len]
else
std.heap.page_allocator.alloc(c.WGPUBindGroupEntry, descriptor.entries.len) catch unreachable;
defer if (entries.len > 8) std.heap.page_allocator.free(entries);
for (descriptor.entries) |entry, i| {
entries[i] = c.WGPUBindGroupEntry{
.nextInChain = null,
.binding = entry.binding,
.buffer = if (entry.buffer) |buf|
@ptrCast(c.WGPUBuffer, buf.ptr)
else
null,
.offset = entry.offset,
.size = entry.size,
.sampler = if (entry.sampler) |samp|
@ptrCast(c.WGPUSampler, samp.ptr)
else
null,
.textureView = if (entry.texture_view) |tex|
@ptrCast(c.WGPUTextureView, tex.ptr)
else
null,
};
}
const desc = c.WGPUBindGroupDescriptor{
.nextInChain = null,
.label = if (descriptor.label) |l| l else null,
.layout = @ptrCast(c.WGPUBindGroupLayout, descriptor.layout.ptr),
.entryCount = @intCast(u32, entries.len),
.entries = entries.ptr,
};
return wrapBindGroup(c.wgpuDeviceCreateBindGroup(@ptrCast(c.WGPUDevice, ptr), &desc));
}
}).createBindGroup,
.pushErrorScope = (struct {
pub fn pushErrorScope(ptr: *anyopaque, filter: ErrorFilter) void {
c.wgpuDevicePushErrorScope(@ptrCast(c.WGPUDevice, ptr), @enumToInt(filter));
}
}).pushErrorScope,
.setLostCallback = (struct {
pub fn setLostCallback(ptr: *anyopaque, callback: *Device.LostCallback) void {
const cCallback = (struct {
pub fn cCallback(
reason: c.WGPUDeviceLostReason,
message: [*c]const u8,
userdata: ?*anyopaque,
) callconv(.C) void {
const callback_info = @ptrCast(*Device.LostCallback, @alignCast(std.meta.alignment(*Device.LostCallback), userdata));
callback_info.type_erased_callback(
callback_info.type_erased_ctx,
@intToEnum(Device.LostReason, reason),
std.mem.span(message),
);
}
}).cCallback;
c.wgpuDeviceSetDeviceLostCallback(
@ptrCast(c.WGPUDevice, ptr),
cCallback,
callback,
);
}
}).setLostCallback,
.createBindGroupLayout = (struct {
pub fn createBindGroupLayout(ptr: *anyopaque, descriptor: *const BindGroupLayout.Descriptor) BindGroupLayout {
const desc = c.WGPUBindGroupLayoutDescriptor{
.nextInChain = null,
.label = if (descriptor.label) |l| l else null,
.entryCount = @intCast(u32, descriptor.entries.len),
.entries = @ptrCast([*]const c.WGPUBindGroupLayoutEntry, descriptor.entries.ptr),
};
return wrapBindGroupLayout(c.wgpuDeviceCreateBindGroupLayout(@ptrCast(c.WGPUDevice, ptr), &desc));
}
}).createBindGroupLayout,
.createSampler = (struct {
pub fn createSampler(ptr: *anyopaque, descriptor: *const Sampler.Descriptor) Sampler {
return wrapSampler(c.wgpuDeviceCreateSampler(
@ptrCast(c.WGPUDevice, ptr),
@ptrCast(*const c.WGPUSamplerDescriptor, descriptor),
));
}
}).createSampler,
.createShaderModule = (struct {
pub fn createShaderModule(ptr: *anyopaque, descriptor: *const ShaderModule.Descriptor) ShaderModule {
switch (descriptor.code) {
.wgsl => |wgsl| {
const wgsl_desc = c.WGPUShaderModuleWGSLDescriptor{
.chain = c.WGPUChainedStruct{
.next = null,
.sType = c.WGPUSType_ShaderModuleWGSLDescriptor,
},
.source = wgsl,
};
const desc = c.WGPUShaderModuleDescriptor{
.nextInChain = @ptrCast(*const c.WGPUChainedStruct, &wgsl_desc),
.label = if (descriptor.label) |l| l else null,
};
return wrapShaderModule(c.wgpuDeviceCreateShaderModule(@ptrCast(c.WGPUDevice, ptr), &desc));
},
.spirv => |spirv| {
const spirv_desc = c.WGPUShaderModuleSPIRVDescriptor{
.chain = c.WGPUChainedStruct{
.next = null,
.sType = c.WGPUSType_ShaderModuleSPIRVDescriptor,
},
.code = spirv.ptr,
.codeSize = @intCast(u32, spirv.len),
};
const desc = c.WGPUShaderModuleDescriptor{
.nextInChain = @ptrCast(*const c.WGPUChainedStruct, &spirv_desc),
.label = if (descriptor.label) |l| l else null,
};
return wrapShaderModule(c.wgpuDeviceCreateShaderModule(@ptrCast(c.WGPUDevice, ptr), &desc));
},
}
}
}).createShaderModule,
.nativeCreateSwapChain = (struct {
pub fn nativeCreateSwapChain(ptr: *anyopaque, surface: ?Surface, descriptor: *const SwapChain.Descriptor) SwapChain {
const desc = c.WGPUSwapChainDescriptor{
.nextInChain = null,
.label = if (descriptor.label) |l| l else null,
.usage = @bitCast(u32, descriptor.usage),
.format = @enumToInt(descriptor.format),
.width = descriptor.width,
.height = descriptor.height,
.presentMode = @enumToInt(descriptor.present_mode),
.implementation = descriptor.implementation,
};
return wrapSwapChain(c.wgpuDeviceCreateSwapChain(
@ptrCast(c.WGPUDevice, ptr),
if (surface) |surf| @ptrCast(c.WGPUSurface, surf.ptr) else null,
&desc,
));
}
}).nativeCreateSwapChain,
.createTexture = (struct {
pub fn createTexture(ptr: *anyopaque, descriptor: *const Texture.Descriptor) Texture {
const desc = c.WGPUTextureDescriptor{
.nextInChain = null,
.label = if (descriptor.label) |l| l else null,
.usage = @bitCast(u32, descriptor.usage),
.dimension = @enumToInt(descriptor.dimension),
.size = @bitCast(c.WGPUExtent3D, descriptor.size),
.format = @enumToInt(descriptor.format),
.mipLevelCount = descriptor.mip_level_count,
.sampleCount = descriptor.sample_count,
.viewFormatCount = if (descriptor.view_formats) |vf| @intCast(u32, vf.len) else 0,
.viewFormats = if (descriptor.view_formats) |vf| @ptrCast([*]const c.WGPUTextureFormat, vf.ptr) else null,
};
return wrapTexture(c.wgpuDeviceCreateTexture(@ptrCast(c.WGPUDevice, ptr), &desc));
}
}).createTexture,
.destroy = (struct {
pub fn destroy(ptr: *anyopaque) void {
c.wgpuDeviceDestroy(@ptrCast(c.WGPUDevice, ptr));
}
}).destroy,
.createBuffer = (struct {
pub fn createBuffer(ptr: *anyopaque, descriptor: *const Buffer.Descriptor) Buffer {
return wrapBuffer(c.wgpuDeviceCreateBuffer(
@ptrCast(c.WGPUDevice, ptr),
@ptrCast(*const c.WGPUBufferDescriptor, descriptor),
));
}
}).createBuffer,
.createCommandEncoder = (struct {
pub fn createCommandEncoder(ptr: *anyopaque, descriptor: ?*const CommandEncoder.Descriptor) CommandEncoder {
const desc: ?*c.WGPUCommandEncoderDescriptor = if (descriptor) |d| &.{
.nextInChain = null,
.label = if (d.label) |l| l else "",
} else null;
return wrapCommandEncoder(c.wgpuDeviceCreateCommandEncoder(@ptrCast(c.WGPUDevice, ptr), desc));
}
}).createCommandEncoder,
.createComputePipeline = (struct {
pub fn createComputePipeline(
ptr: *anyopaque,
descriptor: *const ComputePipeline.Descriptor,
) ComputePipeline {
const desc = convertComputePipelineDescriptor(descriptor);
return wrapComputePipeline(c.wgpuDeviceCreateComputePipeline(
@ptrCast(c.WGPUDevice, ptr),
&desc,
));
}
}).createComputePipeline,
.createComputePipelineAsync = (struct {
pub fn createComputePipelineAsync(
ptr: *anyopaque,
descriptor: *const ComputePipeline.Descriptor,
callback: *ComputePipeline.CreateCallback,
) void {
const desc = convertComputePipelineDescriptor(descriptor);
const cCallback = (struct {
pub fn cCallback(
status: c.WGPUCreatePipelineAsyncStatus,
pipeline: c.WGPUComputePipeline,
message: [*c]const u8,
userdata: ?*anyopaque,
) callconv(.C) void {
const callback_info = @ptrCast(*ComputePipeline.CreateCallback, @alignCast(std.meta.alignment(*ComputePipeline.CreateCallback), userdata));
callback_info.type_erased_callback(
callback_info.type_erased_ctx,
@intToEnum(ComputePipeline.CreateStatus, status),
wrapComputePipeline(pipeline),
std.mem.span(message),
);
}
}).cCallback;
c.wgpuDeviceCreateComputePipelineAsync(
@ptrCast(c.WGPUDevice, ptr),
&desc,
cCallback,
callback,
);
}
}).createComputePipelineAsync,
.createErrorBuffer = (struct {
pub fn createErrorBuffer(ptr: *anyopaque) Buffer {
return wrapBuffer(c.wgpuDeviceCreateErrorBuffer(
@ptrCast(c.WGPUDevice, ptr),
));
}
}).createErrorBuffer,
.createExternalTexture = (struct {
pub fn createExternalTexture(ptr: *anyopaque, descriptor: *const ExternalTexture.Descriptor) ExternalTexture {
const desc = c.WGPUExternalTextureDescriptor{
.nextInChain = null,
.label = if (descriptor.label) |l| l else null,
.plane0 = @ptrCast(c.WGPUTextureView, descriptor.plane0.ptr),
.plane1 = @ptrCast(c.WGPUTextureView, descriptor.plane1.ptr),
.colorSpace = @enumToInt(descriptor.color_space),
};
return wrapExternalTexture(c.wgpuDeviceCreateExternalTexture(@ptrCast(c.WGPUDevice, ptr), &desc));
}
}).createExternalTexture,
.createPipelineLayout = (struct {
pub fn createPipelineLayout(ptr: *anyopaque, descriptor: *const PipelineLayout.Descriptor) PipelineLayout {
var few_bind_group_layouts: [16]c.WGPUBindGroupLayout = undefined;
const bind_group_layouts = if (descriptor.bind_group_layouts.len <= 16) blk: {
for (descriptor.bind_group_layouts) |layout, i| {
few_bind_group_layouts[i] = @ptrCast(c.WGPUBindGroupLayout, layout.ptr);
}
break :blk few_bind_group_layouts[0..descriptor.bind_group_layouts.len];
} else blk: {
const mem = std.heap.page_allocator.alloc(c.WGPUBindGroupLayout, descriptor.bind_group_layouts.len) catch unreachable;
for (descriptor.bind_group_layouts) |layout, i| {
mem[i] = @ptrCast(c.WGPUBindGroupLayout, layout.ptr);
}
break :blk mem;
};
defer if (descriptor.bind_group_layouts.len > 16) std.heap.page_allocator.free(descriptor.bind_group_layouts);
const desc = c.WGPUPipelineLayoutDescriptor{
.nextInChain = null,
.label = if (descriptor.label) |l| l else null,
.bindGroupLayoutCount = @intCast(u32, bind_group_layouts.len),
.bindGroupLayouts = bind_group_layouts.ptr,
};
return wrapPipelineLayout(c.wgpuDeviceCreatePipelineLayout(@ptrCast(c.WGPUDevice, ptr), &desc));
}
}).createPipelineLayout,
.createQuerySet = (struct {
pub fn createQuerySet(ptr: *anyopaque, descriptor: *const QuerySet.Descriptor) QuerySet {
const desc = c.WGPUQuerySetDescriptor{
.nextInChain = null,
.label = if (descriptor.label) |l| l else null,
.type = @enumToInt(descriptor.type),
.count = descriptor.count,
.pipelineStatistics = @ptrCast([*]const c.WGPUPipelineStatisticName, descriptor.pipeline_statistics.ptr),
.pipelineStatisticsCount = @intCast(u32, descriptor.pipeline_statistics.len),
};
return wrapQuerySet(c.wgpuDeviceCreateQuerySet(@ptrCast(c.WGPUDevice, ptr), &desc));
}
}).createQuerySet,
.createRenderBundleEncoder = (struct {
pub fn createRenderBundleEncoder(ptr: *anyopaque, descriptor: *const RenderBundleEncoder.Descriptor) RenderBundleEncoder {
const desc = c.WGPURenderBundleEncoderDescriptor{
.nextInChain = null,
.label = if (descriptor.label) |l| l else null,
.colorFormatsCount = @intCast(u32, descriptor.color_formats.len),
.colorFormats = @ptrCast([*]const c.WGPUTextureFormat, descriptor.color_formats.ptr),
.depthStencilFormat = @enumToInt(descriptor.depth_stencil_format),
.sampleCount = descriptor.sample_count,
.depthReadOnly = descriptor.depth_read_only,
.stencilReadOnly = descriptor.stencil_read_only,
};
return wrapRenderBundleEncoder(c.wgpuDeviceCreateRenderBundleEncoder(@ptrCast(c.WGPUDevice, ptr), &desc));
}
}).createRenderBundleEncoder,
.createRenderPipeline = (struct {
pub fn createRenderPipeline(ptr: *anyopaque, descriptor: *const RenderPipeline.Descriptor) RenderPipeline {
var tmp_depth_stencil: c.WGPUDepthStencilState = undefined;
var tmp_fragment_state: c.WGPUFragmentState = undefined;
const desc = convertRenderPipelineDescriptor(descriptor, &tmp_depth_stencil, &tmp_fragment_state);
return wrapRenderPipeline(c.wgpuDeviceCreateRenderPipeline(@ptrCast(c.WGPUDevice, ptr), &desc));
}
}).createRenderPipeline,
.createRenderPipelineAsync = (struct {
pub fn createRenderPipelineAsync(
ptr: *anyopaque,
descriptor: *const RenderPipeline.Descriptor,
callback: *RenderPipeline.CreateCallback,
) void {
var tmp_depth_stencil: c.WGPUDepthStencilState = undefined;
var tmp_fragment_state: c.WGPUFragmentState = undefined;
const desc = convertRenderPipelineDescriptor(descriptor, &tmp_depth_stencil, &tmp_fragment_state);
const cCallback = (struct {
pub fn cCallback(
status: c.WGPUCreatePipelineAsyncStatus,
pipeline: c.WGPURenderPipeline,
message: [*c]const u8,
userdata: ?*anyopaque,
) callconv(.C) void {
const callback_info = @ptrCast(*RenderPipeline.CreateCallback, @alignCast(std.meta.alignment(*RenderPipeline.CreateCallback), userdata));
callback_info.type_erased_callback(
callback_info.type_erased_ctx,
@intToEnum(RenderPipeline.CreateStatus, status),
wrapRenderPipeline(pipeline),
std.mem.span(message),
);
}
}).cCallback;
c.wgpuDeviceCreateRenderPipelineAsync(
@ptrCast(c.WGPUDevice, ptr),
&desc,
cCallback,
callback,
);
}
}).createRenderPipelineAsync,
.setUncapturedErrorCallback = (struct {
pub fn setUncapturedErrorCallback(
ptr: *anyopaque,
callback: *ErrorCallback,
) void {
const cCallback = (struct {
pub fn cCallback(
typ: c.WGPUErrorType,
message: [*c]const u8,
userdata: ?*anyopaque,
) callconv(.C) void {
const callback_info = @ptrCast(*ErrorCallback, @alignCast(std.meta.alignment(*ErrorCallback), userdata));
callback_info.type_erased_callback(
callback_info.type_erased_ctx,
@intToEnum(ErrorType, typ),
std.mem.span(message),
);
}
}).cCallback;
return c.wgpuDeviceSetUncapturedErrorCallback(
@ptrCast(c.WGPUDevice, ptr),
cCallback,
callback,
);
}
}).setUncapturedErrorCallback,
.setLoggingCallback = (struct {
pub fn setLoggingCallback(
ptr: *anyopaque,
callback: *LoggingCallback,
) void {
const cCallback = (struct {
pub fn cCallback(
typ: c.WGPULoggingType,
message: [*c]const u8,
userdata: ?*anyopaque,
) callconv(.C) void {
const callback_info = @ptrCast(*LoggingCallback, @alignCast(std.meta.alignment(*LoggingCallback), userdata));
callback_info.type_erased_callback(
callback_info.type_erased_ctx,
@intToEnum(LoggingType, typ),
std.mem.span(message),
);
}
}).cCallback;
return c.wgpuDeviceSetLoggingCallback(
@ptrCast(c.WGPUDevice, ptr),
cCallback,
callback,
);
}
}).setLoggingCallback,
.tick = (struct {
pub fn tick(ptr: *anyopaque) void {
c.wgpuDeviceTick(@ptrCast(c.WGPUDevice, ptr));
}
}.tick),
};
inline fn convertComputePipelineDescriptor(descriptor: *const ComputePipeline.Descriptor) c.WGPUComputePipelineDescriptor {
return .{
.nextInChain = null,
.label = if (descriptor.label) |l| l else null,
.layout = if (descriptor.layout) |l| @ptrCast(c.WGPUPipelineLayout, l.ptr) else null,
.compute = c.WGPUProgrammableStageDescriptor{
.nextInChain = null,
.module = @ptrCast(c.WGPUShaderModule, descriptor.compute.module.ptr),
.entryPoint = descriptor.compute.entry_point,
.constantCount = if (descriptor.compute.constants) |v| @intCast(u32, v.len) else 0,
.constants = if (descriptor.compute.constants) |v| @ptrCast([*]const c.WGPUConstantEntry, v.ptr) else null,
},
};
}
inline fn convertRenderPipelineDescriptor(
d: *const RenderPipeline.Descriptor,
tmp_depth_stencil: *c.WGPUDepthStencilState,
tmp_fragment_state: *c.WGPUFragmentState,
) c.WGPURenderPipelineDescriptor {
if (d.depth_stencil) |ds| {
tmp_depth_stencil.* = c.WGPUDepthStencilState{
.nextInChain = null,
.format = @enumToInt(ds.format),
.depthWriteEnabled = ds.depth_write_enabled,
.depthCompare = @enumToInt(ds.depth_compare),
.stencilFront = @bitCast(c.WGPUStencilFaceState, ds.stencil_front),
.stencilBack = @bitCast(c.WGPUStencilFaceState, ds.stencil_back),
.stencilReadMask = ds.stencil_read_mask,
.stencilWriteMask = ds.stencil_write_mask,
.depthBias = ds.depth_bias,
.depthBiasSlopeScale = ds.depth_bias_slope_scale,
.depthBiasClamp = ds.depth_bias_clamp,
};
}
if (d.fragment) |frag| {
tmp_fragment_state.* = c.WGPUFragmentState{
.nextInChain = null,
.module = @ptrCast(c.WGPUShaderModule, frag.module.ptr),
.entryPoint = frag.entry_point,
.constantCount = if (frag.constants) |v| @intCast(u32, v.len) else 0,
.constants = if (frag.constants) |v| @ptrCast([*]const c.WGPUConstantEntry, v.ptr) else null,
.targetCount = if (frag.targets) |v| @intCast(u32, v.len) else 0,
.targets = if (frag.targets) |v| @ptrCast([*]const c.WGPUColorTargetState, v.ptr) else null,
};
}
return c.WGPURenderPipelineDescriptor{
.nextInChain = null,
.label = if (d.label) |l| l else null,
.layout = if (d.layout) |v| @ptrCast(c.WGPUPipelineLayout, v.ptr) else null,
.vertex = c.WGPUVertexState{
.nextInChain = null,
.module = @ptrCast(c.WGPUShaderModule, d.vertex.module.ptr),
.entryPoint = d.vertex.entry_point,
.constantCount = if (d.vertex.constants) |v| @intCast(u32, v.len) else 0,
.constants = if (d.vertex.constants) |v| @ptrCast([*]const c.WGPUConstantEntry, v.ptr) else null,
.bufferCount = if (d.vertex.buffers) |v| @intCast(u32, v.len) else 0,
.buffers = if (d.vertex.buffers) |v| @ptrCast([*]const c.WGPUVertexBufferLayout, v.ptr) else null,
},
.primitive = c.WGPUPrimitiveState{
.nextInChain = null,
.topology = @enumToInt(d.primitive.topology),
.stripIndexFormat = @enumToInt(d.primitive.strip_index_format),
.frontFace = @enumToInt(d.primitive.front_face),
.cullMode = @enumToInt(d.primitive.cull_mode),
},
.depthStencil = if (d.depth_stencil != null) tmp_depth_stencil else null,
.multisample = c.WGPUMultisampleState{
.nextInChain = null,
.count = d.multisample.count,
.mask = d.multisample.mask,
.alphaToCoverageEnabled = d.multisample.alpha_to_coverage_enabled,
},
.fragment = if (d.fragment != null) tmp_fragment_state else null,
};
}
fn wrapQueue(queue: c.WGPUQueue) Queue {
return .{
.ptr = queue.?,
.vtable = &queue_vtable,
};
}
const queue_vtable = Queue.VTable{
.reference = (struct {
pub fn reference(ptr: *anyopaque) void {
c.wgpuQueueReference(@ptrCast(c.WGPUQueue, ptr));
}
}).reference,
.release = (struct {
pub fn release(ptr: *anyopaque) void {
c.wgpuQueueRelease(@ptrCast(c.WGPUQueue, ptr));
}
}).release,
.submit = (struct {
pub fn submit(queue: *Queue, cmds: []const CommandBuffer) void {
const wgpu_queue = @ptrCast(c.WGPUQueue, queue.ptr);
if (queue.on_submitted_work_done) |_| {
// Note: signalValue is not available in the web API, and it's usage is undocumented
// kainino says "It's basically reserved for future use, though it's been suggested
// to remove it instead"
const signal_value: u64 = 0;
const cCallback = (struct {
pub fn cCallback(status: c.WGPUQueueWorkDoneStatus, userdata: ?*anyopaque) callconv(.C) void {
const callback_info = @ptrCast(*Queue.WorkDoneCallback, @alignCast(std.meta.alignment(*Queue.WorkDoneCallback), userdata));
callback_info.type_erased_callback(
callback_info.type_erased_ctx,
@intToEnum(Queue.WorkDoneStatus, status),
);
}
}).cCallback;
c.wgpuQueueOnSubmittedWorkDone(
wgpu_queue,
signal_value,
cCallback,
&queue.on_submitted_work_done,
);
}
var few_commands: [16]c.WGPUCommandBuffer = undefined;
const commands = if (cmds.len <= 16) blk: {
for (cmds) |cmd, i| {
few_commands[i] = @ptrCast(c.WGPUCommandBuffer, cmd.ptr);
}
break :blk few_commands[0..cmds.len];
} else blk: {
const mem = std.heap.page_allocator.alloc(c.WGPUCommandBuffer, cmds.len) catch unreachable;
for (cmds) |cmd, i| {
mem[i] = @ptrCast(c.WGPUCommandBuffer, cmd.ptr);
}
break :blk mem;
};
defer if (cmds.len > 16) std.heap.page_allocator.free(cmds);
c.wgpuQueueSubmit(
wgpu_queue,
@intCast(u32, commands.len),
@ptrCast([*]c.WGPUCommandBuffer, commands.ptr),
);
}
}).submit,
.writeBuffer = (struct {
pub fn writeBuffer(ptr: *anyopaque, buffer: Buffer, buffer_offset: u64, data: *const anyopaque, size: u64) void {
c.wgpuQueueWriteBuffer(
@ptrCast(c.WGPUQueue, ptr),
@ptrCast(c.WGPUBuffer, buffer.ptr),
buffer_offset,
data,
size,
);
}
}).writeBuffer,
.writeTexture = (struct {
pub fn writeTexture(
ptr: *anyopaque,
destination: *const ImageCopyTexture,
data: *const anyopaque,
data_size: usize,
data_layout: *const Texture.DataLayout,
write_size: *const Extent3D,
) void {
c.wgpuQueueWriteTexture(
@ptrCast(c.WGPUQueue, ptr),
&c.WGPUImageCopyTexture{
.nextInChain = null,
.texture = @ptrCast(c.WGPUTexture, destination.texture.ptr),
.mipLevel = destination.mip_level,
.origin = @bitCast(c.WGPUOrigin3D, destination.origin),
.aspect = @bitCast(c.WGPUTextureAspect, destination.aspect),
},
data,
data_size,
@ptrCast(*const c.WGPUTextureDataLayout, data_layout),
@ptrCast(*const c.WGPUExtent3D, write_size),
);
}
}).writeTexture,
};
fn wrapShaderModule(shader_module: c.WGPUShaderModule) ShaderModule {
return .{
.ptr = shader_module.?,
.vtable = &shader_module_vtable,
};
}
const shader_module_vtable = ShaderModule.VTable{
.reference = (struct {
pub fn reference(ptr: *anyopaque) void {
c.wgpuShaderModuleReference(@ptrCast(c.WGPUShaderModule, ptr));
}
}).reference,
.release = (struct {
pub fn release(ptr: *anyopaque) void {
c.wgpuShaderModuleRelease(@ptrCast(c.WGPUShaderModule, ptr));
}
}).release,
.setLabel = (struct {
pub fn setLabel(ptr: *anyopaque, label: [:0]const u8) void {
c.wgpuShaderModuleSetLabel(@ptrCast(c.WGPUShaderModule, ptr), label);
}
}).setLabel,
.getCompilationInfo = (struct {
pub fn getCompilationInfo(ptr: *anyopaque, callback: *ShaderModule.CompilationInfoCallback) void {
const cCallback = (struct {
pub fn cCallback(status: c.WGPUCompilationInfoRequestStatus, info: [*c]const c.WGPUCompilationInfo, userdata: ?*anyopaque) callconv(.C) void {
const callback_info = @ptrCast(*ShaderModule.CompilationInfoCallback, @alignCast(std.meta.alignment(*ShaderModule.CompilationInfoCallback), userdata.?));
callback_info.type_erased_callback(
callback_info.type_erased_ctx,
@intToEnum(ShaderModule.CompilationInfoRequestStatus, status),
&ShaderModule.CompilationInfo{
.messages = @bitCast([]const ShaderModule.CompilationMessage, info[0].messages[0..info[0].messageCount]),
},
);
}
}).cCallback;
c.wgpuShaderModuleGetCompilationInfo(@ptrCast(c.WGPUShaderModule, ptr), cCallback, callback);
}
}).getCompilationInfo,
};
fn wrapSwapChain(swap_chain: c.WGPUSwapChain) SwapChain {
return .{
.ptr = swap_chain.?,
.vtable = &swap_chain_vtable,
};
}
const swap_chain_vtable = SwapChain.VTable{
.reference = (struct {
pub fn reference(ptr: *anyopaque) void {
c.wgpuSwapChainReference(@ptrCast(c.WGPUSwapChain, ptr));
}
}).reference,
.release = (struct {
pub fn release(ptr: *anyopaque) void {
c.wgpuSwapChainRelease(@ptrCast(c.WGPUSwapChain, ptr));
}
}).release,
.configure = (struct {
pub fn configure(ptr: *anyopaque, format: Texture.Format, allowed_usage: Texture.Usage, width: u32, height: u32) void {
c.wgpuSwapChainConfigure(
@ptrCast(c.WGPUSwapChain, ptr),
@enumToInt(format),
@bitCast(u32, allowed_usage),
width,
height,
);
}
}).configure,
.getCurrentTextureView = (struct {
pub fn getCurrentTextureView(ptr: *anyopaque) TextureView {
return wrapTextureView(c.wgpuSwapChainGetCurrentTextureView(@ptrCast(c.WGPUSwapChain, ptr)));
}
}).getCurrentTextureView,
.present = (struct {
pub fn present(ptr: *anyopaque) void {
c.wgpuSwapChainPresent(@ptrCast(c.WGPUSwapChain, ptr));
}
}).present,
};
fn wrapTextureView(texture_view: c.WGPUTextureView) TextureView {
return .{
.ptr = texture_view.?,
.vtable = &texture_view_vtable,
};
}
const texture_view_vtable = TextureView.VTable{
.reference = (struct {
pub fn reference(ptr: *anyopaque) void {
c.wgpuTextureViewReference(@ptrCast(c.WGPUTextureView, ptr));
}
}).reference,
.release = (struct {
pub fn release(ptr: *anyopaque) void {
c.wgpuTextureViewRelease(@ptrCast(c.WGPUTextureView, ptr));
}
}).release,
.setLabel = (struct {
pub fn setLabel(ptr: *anyopaque, label: [:0]const u8) void {
c.wgpuTextureViewSetLabel(@ptrCast(c.WGPUTextureView, ptr), label);
}
}).setLabel,
};
fn wrapTexture(texture: c.WGPUTexture) Texture {
return .{
.ptr = texture.?,
.vtable = &texture_vtable,
};
}
const texture_vtable = Texture.VTable{
.reference = (struct {
pub fn reference(ptr: *anyopaque) void {
c.wgpuTextureReference(@ptrCast(c.WGPUTexture, ptr));
}
}).reference,
.release = (struct {
pub fn release(ptr: *anyopaque) void {
c.wgpuTextureRelease(@ptrCast(c.WGPUTexture, ptr));
}
}).release,
.setLabel = (struct {
pub fn setLabel(ptr: *anyopaque, label: [:0]const u8) void {
c.wgpuTextureSetLabel(@ptrCast(c.WGPUTexture, ptr), label);
}
}).setLabel,
.destroy = (struct {
pub fn destroy(ptr: *anyopaque) void {
c.wgpuTextureDestroy(@ptrCast(c.WGPUTexture, ptr));
}
}).destroy,
.createView = (struct {
pub fn createView(ptr: *anyopaque, descriptor: *const TextureView.Descriptor) TextureView {
const desc = c.WGPUTextureViewDescriptor{
.nextInChain = null,
.label = if (descriptor.label) |l| l else "",
.format = @enumToInt(descriptor.format),
.dimension = @enumToInt(descriptor.dimension),
.baseMipLevel = descriptor.base_mip_level,
.mipLevelCount = descriptor.mip_level_count,
.baseArrayLayer = descriptor.base_array_layer,
.arrayLayerCount = descriptor.array_layer_count,
.aspect = @enumToInt(descriptor.aspect),
};
return wrapTextureView(c.wgpuTextureCreateView(
@ptrCast(c.WGPUTexture, ptr),
&desc,
));
}
}).createView,
};
fn wrapSampler(sampler: c.WGPUSampler) Sampler {
return .{
.ptr = sampler.?,
.vtable = &sampler_vtable,
};
}
const sampler_vtable = Sampler.VTable{
.reference = (struct {
pub fn reference(ptr: *anyopaque) void {
c.wgpuSamplerReference(@ptrCast(c.WGPUSampler, ptr));
}
}).reference,
.release = (struct {
pub fn release(ptr: *anyopaque) void {
c.wgpuSamplerRelease(@ptrCast(c.WGPUSampler, ptr));
}
}).release,
.setLabel = (struct {
pub fn setLabel(ptr: *anyopaque, label: [:0]const u8) void {
c.wgpuSamplerSetLabel(@ptrCast(c.WGPUSampler, ptr), label);
}
}).setLabel,
};
fn wrapRenderPipeline(pipeline: c.WGPURenderPipeline) RenderPipeline {
return .{
.ptr = pipeline.?,
.vtable = &render_pipeline_vtable,
};
}
const render_pipeline_vtable = RenderPipeline.VTable{
.reference = (struct {
pub fn reference(ptr: *anyopaque) void {
c.wgpuRenderPipelineReference(@ptrCast(c.WGPURenderPipeline, ptr));
}
}).reference,
.release = (struct {
pub fn release(ptr: *anyopaque) void {
c.wgpuRenderPipelineRelease(@ptrCast(c.WGPURenderPipeline, ptr));
}
}).release,
.setLabel = (struct {
pub fn setLabel(ptr: *anyopaque, label: [:0]const u8) void {
c.wgpuRenderPipelineSetLabel(@ptrCast(c.WGPURenderPipeline, ptr), label);
}
}).setLabel,
.getBindGroupLayout = (struct {
pub fn getBindGroupLayout(ptr: *anyopaque, group_index: u32) BindGroupLayout {
return wrapBindGroupLayout(c.wgpuRenderPipelineGetBindGroupLayout(
@ptrCast(c.WGPURenderPipeline, ptr),
group_index,
));
}
}).getBindGroupLayout,
};
fn wrapRenderPassEncoder(pass: c.WGPURenderPassEncoder) RenderPassEncoder {
return .{
.ptr = pass.?,
.vtable = &render_pass_encoder_vtable,
};
}
const render_pass_encoder_vtable = RenderPassEncoder.VTable{
.reference = (struct {
pub fn reference(ptr: *anyopaque) void {
c.wgpuRenderPassEncoderReference(@ptrCast(c.WGPURenderPassEncoder, ptr));
}
}).reference,
.release = (struct {
pub fn release(ptr: *anyopaque) void {
c.wgpuRenderPassEncoderRelease(@ptrCast(c.WGPURenderPassEncoder, ptr));
}
}).release,
.setLabel = (struct {
pub fn setLabel(ptr: *anyopaque, label: [:0]const u8) void {
c.wgpuRenderPassEncoderSetLabel(@ptrCast(c.WGPURenderPassEncoder, ptr), label);
}
}).setLabel,
.setPipeline = (struct {
pub fn setPipeline(ptr: *anyopaque, pipeline: RenderPipeline) void {
c.wgpuRenderPassEncoderSetPipeline(@ptrCast(c.WGPURenderPassEncoder, ptr), @ptrCast(c.WGPURenderPipeline, pipeline.ptr));
}
}).setPipeline,
.draw = (struct {
pub fn draw(ptr: *anyopaque, vertex_count: u32, instance_count: u32, first_vertex: u32, first_instance: u32) void {
c.wgpuRenderPassEncoderDraw(@ptrCast(c.WGPURenderPassEncoder, ptr), vertex_count, instance_count, first_vertex, first_instance);
}
}).draw,
.drawIndexed = (struct {
pub fn drawIndexed(
ptr: *anyopaque,
index_count: u32,
instance_count: u32,
first_index: u32,
base_vertex: i32,
first_instance: u32,
) void {
c.wgpuRenderPassEncoderDrawIndexed(
@ptrCast(c.WGPURenderPassEncoder, ptr),
index_count,
instance_count,
first_index,
base_vertex,
first_instance,
);
}
}).drawIndexed,
.drawIndexedIndirect = (struct {
pub fn drawIndexedIndirect(ptr: *anyopaque, indirect_buffer: Buffer, indirect_offset: u64) void {
c.wgpuRenderPassEncoderDrawIndexedIndirect(
@ptrCast(c.WGPURenderPassEncoder, ptr),
@ptrCast(c.WGPUBuffer, indirect_buffer.ptr),
indirect_offset,
);
}
}).drawIndexedIndirect,
.drawIndirect = (struct {
pub fn drawIndirect(ptr: *anyopaque, indirect_buffer: Buffer, indirect_offset: u64) void {
c.wgpuRenderPassEncoderDrawIndexedIndirect(
@ptrCast(c.WGPURenderPassEncoder, ptr),
@ptrCast(c.WGPUBuffer, indirect_buffer.ptr),
indirect_offset,
);
}
}).drawIndirect,
.beginOcclusionQuery = (struct {
pub fn beginOcclusionQuery(ptr: *anyopaque, query_index: u32) void {
c.wgpuRenderPassEncoderBeginOcclusionQuery(@ptrCast(c.WGPURenderPassEncoder, ptr), query_index);
}
}).beginOcclusionQuery,
.endOcclusionQuery = (struct {
pub fn endOcclusionQuery(ptr: *anyopaque) void {
c.wgpuRenderPassEncoderEndOcclusionQuery(@ptrCast(c.WGPURenderPassEncoder, ptr));
}
}).endOcclusionQuery,
.end = (struct {
pub fn end(ptr: *anyopaque) void {
c.wgpuRenderPassEncoderEnd(@ptrCast(c.WGPURenderPassEncoder, ptr));
}
}).end,
.executeBundles = (struct {
pub fn executeBundles(ptr: *anyopaque, bundles: []RenderBundle) void {
var few_bundles: [16]c.WGPURenderBundle = undefined;
const c_bundles = if (bundles.len <= 8) blk: {
for (bundles) |bundle, i| {
few_bundles[i] = @ptrCast(c.WGPURenderBundle, bundle.ptr);
}
break :blk few_bundles[0..bundles.len];
} else blk: {
const mem = std.heap.page_allocator.alloc(c.WGPURenderBundle, bundles.len) catch unreachable;
for (bundles) |bundle, i| {
mem[i] = @ptrCast(c.WGPURenderBundle, bundle.ptr);
}
break :blk mem;
};
defer if (bundles.len > 8) std.heap.page_allocator.free(c_bundles);
c.wgpuRenderPassEncoderExecuteBundles(
@ptrCast(c.WGPURenderPassEncoder, ptr),
@intCast(u32, c_bundles.len),
c_bundles.ptr,
);
}
}).executeBundles,
.insertDebugMarker = (struct {
pub fn insertDebugMarker(ptr: *anyopaque, marker_label: [*:0]const u8) void {
c.wgpuRenderPassEncoderInsertDebugMarker(@ptrCast(c.WGPURenderPassEncoder, ptr), marker_label);
}
}).insertDebugMarker,
.popDebugGroup = (struct {
pub fn popDebugGroup(ptr: *anyopaque) void {
c.wgpuRenderPassEncoderPopDebugGroup(@ptrCast(c.WGPURenderPassEncoder, ptr));
}
}).popDebugGroup,
.pushDebugGroup = (struct {
pub fn pushDebugGroup(ptr: *anyopaque, group_label: [*:0]const u8) void {
c.wgpuRenderPassEncoderPushDebugGroup(@ptrCast(c.WGPURenderPassEncoder, ptr), group_label);
}
}).pushDebugGroup,
.setBindGroup = (struct {
pub fn setBindGroup(
ptr: *anyopaque,
group_index: u32,
group: BindGroup,
dynamic_offsets: ?[]const u32,
) void {
c.wgpuRenderPassEncoderSetBindGroup(
@ptrCast(c.WGPURenderPassEncoder, ptr),
group_index,
@ptrCast(c.WGPUBindGroup, group.ptr),
if (dynamic_offsets) |d| @intCast(u32, d.len) else 0,
if (dynamic_offsets) |d| d.ptr else null,
);
}
}).setBindGroup,
.setBlendConstant = (struct {
pub fn setBlendConstant(ptr: *anyopaque, color: *const Color) void {
c.wgpuRenderPassEncoderSetBlendConstant(
@ptrCast(c.WGPURenderPassEncoder, ptr),
@ptrCast(*const c.WGPUColor, color),
);
}
}).setBlendConstant,
.setIndexBuffer = (struct {
pub fn setIndexBuffer(
ptr: *anyopaque,
buffer: Buffer,
format: IndexFormat,
offset: u64,
size: u64,
) void {
c.wgpuRenderPassEncoderSetIndexBuffer(
@ptrCast(c.WGPURenderPassEncoder, ptr),
@ptrCast(c.WGPUBuffer, buffer.ptr),
@enumToInt(format),
offset,
size,
);
}
}).setIndexBuffer,
.setScissorRect = (struct {
pub fn setScissorRect(ptr: *anyopaque, x: u32, y: u32, width: u32, height: u32) void {
c.wgpuRenderPassEncoderSetScissorRect(
@ptrCast(c.WGPURenderPassEncoder, ptr),
x,
y,
width,
height,
);
}
}).setScissorRect,
.setStencilReference = (struct {
pub fn setStencilReference(ptr: *anyopaque, reference: u32) void {
c.wgpuRenderPassEncoderSetStencilReference(
@ptrCast(c.WGPURenderPassEncoder, ptr),
reference,
);
}
}).setStencilReference,
.setVertexBuffer = (struct {
pub fn setVertexBuffer(ptr: *anyopaque, slot: u32, buffer: Buffer, offset: u64, size: u64) void {
c.wgpuRenderPassEncoderSetVertexBuffer(
@ptrCast(c.WGPURenderPassEncoder, ptr),
slot,
@ptrCast(c.WGPUBuffer, buffer.ptr),
offset,
size,
);
}
}).setVertexBuffer,
.setViewport = (struct {
pub fn setViewport(
ptr: *anyopaque,
x: f32,
y: f32,
width: f32,
height: f32,
min_depth: f32,
max_depth: f32,
) void {
c.wgpuRenderPassEncoderSetViewport(
@ptrCast(c.WGPURenderPassEncoder, ptr),
x,
y,
width,
height,
min_depth,
max_depth,
);
}
}).setViewport,
.writeTimestamp = (struct {
pub fn writeTimestamp(ptr: *anyopaque, query_set: QuerySet, query_index: u32) void {
c.wgpuRenderPassEncoderWriteTimestamp(
@ptrCast(c.WGPURenderPassEncoder, ptr),
@ptrCast(c.WGPUQuerySet, query_set.ptr),
query_index,
);
}
}).writeTimestamp,
};
fn wrapRenderBundleEncoder(enc: c.WGPURenderBundleEncoder) RenderBundleEncoder {
return .{
.ptr = enc.?,
.vtable = &render_bundle_encoder_vtable,
};
}
const render_bundle_encoder_vtable = RenderBundleEncoder.VTable{
.reference = (struct {
pub fn reference(ptr: *anyopaque) void {
c.wgpuRenderBundleEncoderReference(@ptrCast(c.WGPURenderBundleEncoder, ptr));
}
}).reference,
.release = (struct {
pub fn release(ptr: *anyopaque) void {
c.wgpuRenderBundleEncoderRelease(@ptrCast(c.WGPURenderBundleEncoder, ptr));
}
}).release,
.setLabel = (struct {
pub fn setLabel(ptr: *anyopaque, label: [:0]const u8) void {
c.wgpuRenderBundleEncoderSetLabel(@ptrCast(c.WGPURenderBundleEncoder, ptr), label);
}
}).setLabel,
.setPipeline = (struct {
pub fn setPipeline(ptr: *anyopaque, pipeline: RenderPipeline) void {
c.wgpuRenderBundleEncoderSetPipeline(@ptrCast(c.WGPURenderBundleEncoder, ptr), @ptrCast(c.WGPURenderPipeline, pipeline.ptr));
}
}).setPipeline,
.draw = (struct {
pub fn draw(ptr: *anyopaque, vertex_count: u32, instance_count: u32, first_vertex: u32, first_instance: u32) void {
c.wgpuRenderBundleEncoderDraw(@ptrCast(c.WGPURenderBundleEncoder, ptr), vertex_count, instance_count, first_vertex, first_instance);
}
}).draw,
.drawIndexed = (struct {
pub fn drawIndexed(
ptr: *anyopaque,
index_count: u32,
instance_count: u32,
first_index: u32,
base_vertex: i32,
first_instance: u32,
) void {
c.wgpuRenderBundleEncoderDrawIndexed(
@ptrCast(c.WGPURenderBundleEncoder, ptr),
index_count,
instance_count,
first_index,
base_vertex,
first_instance,
);
}
}).drawIndexed,
.drawIndexedIndirect = (struct {
pub fn drawIndexedIndirect(ptr: *anyopaque, indirect_buffer: Buffer, indirect_offset: u64) void {
c.wgpuRenderBundleEncoderDrawIndexedIndirect(
@ptrCast(c.WGPURenderBundleEncoder, ptr),
@ptrCast(c.WGPUBuffer, indirect_buffer.ptr),
indirect_offset,
);
}
}).drawIndexedIndirect,
.drawIndirect = (struct {
pub fn drawIndirect(ptr: *anyopaque, indirect_buffer: Buffer, indirect_offset: u64) void {
c.wgpuRenderBundleEncoderDrawIndexedIndirect(
@ptrCast(c.WGPURenderBundleEncoder, ptr),
@ptrCast(c.WGPUBuffer, indirect_buffer.ptr),
indirect_offset,
);
}
}).drawIndirect,
.finish = (struct {
pub fn finish(ptr: *anyopaque, descriptor: *const RenderBundle.Descriptor) RenderBundle {
const desc = c.WGPURenderBundleDescriptor{
.nextInChain = null,
.label = if (descriptor.label) |l| l else null,
};
return wrapRenderBundle(c.wgpuRenderBundleEncoderFinish(@ptrCast(c.WGPURenderBundleEncoder, ptr), &desc));
}
}).finish,
.insertDebugMarker = (struct {
pub fn insertDebugMarker(ptr: *anyopaque, marker_label: [*:0]const u8) void {
c.wgpuRenderBundleEncoderInsertDebugMarker(@ptrCast(c.WGPURenderBundleEncoder, ptr), marker_label);
}
}).insertDebugMarker,
.popDebugGroup = (struct {
pub fn popDebugGroup(ptr: *anyopaque) void {
c.wgpuRenderBundleEncoderPopDebugGroup(@ptrCast(c.WGPURenderBundleEncoder, ptr));
}
}).popDebugGroup,
.pushDebugGroup = (struct {
pub fn pushDebugGroup(ptr: *anyopaque, group_label: [*:0]const u8) void {
c.wgpuRenderBundleEncoderPushDebugGroup(@ptrCast(c.WGPURenderBundleEncoder, ptr), group_label);
}
}).pushDebugGroup,
.setBindGroup = (struct {
pub fn setBindGroup(
ptr: *anyopaque,
group_index: u32,
group: BindGroup,
dynamic_offsets: ?[]const u32,
) void {
c.wgpuRenderBundleEncoderSetBindGroup(
@ptrCast(c.WGPURenderBundleEncoder, ptr),
group_index,
@ptrCast(c.WGPUBindGroup, group.ptr),
if (dynamic_offsets) |d| @intCast(u32, d.len) else 0,
if (dynamic_offsets) |d| d.ptr else null,
);
}
}).setBindGroup,
.setIndexBuffer = (struct {
pub fn setIndexBuffer(
ptr: *anyopaque,
buffer: Buffer,
format: IndexFormat,
offset: u64,
size: u64,
) void {
c.wgpuRenderBundleEncoderSetIndexBuffer(
@ptrCast(c.WGPURenderBundleEncoder, ptr),
@ptrCast(c.WGPUBuffer, buffer.ptr),
@enumToInt(format),
offset,
size,
);
}
}).setIndexBuffer,
.setVertexBuffer = (struct {
pub fn setVertexBuffer(ptr: *anyopaque, slot: u32, buffer: Buffer, offset: u64, size: u64) void {
c.wgpuRenderBundleEncoderSetVertexBuffer(
@ptrCast(c.WGPURenderBundleEncoder, ptr),
slot,
@ptrCast(c.WGPUBuffer, buffer.ptr),
offset,
size,
);
}
}).setVertexBuffer,
};
fn wrapRenderBundle(bundle: c.WGPURenderBundle) RenderBundle {
return .{
.ptr = bundle.?,
.vtable = &render_bundle_vtable,
};
}
const render_bundle_vtable = RenderBundle.VTable{
.reference = (struct {
pub fn reference(ptr: *anyopaque) void {
c.wgpuRenderBundleReference(@ptrCast(c.WGPURenderBundle, ptr));
}
}).reference,
.release = (struct {
pub fn release(ptr: *anyopaque) void {
c.wgpuRenderBundleRelease(@ptrCast(c.WGPURenderBundle, ptr));
}
}).release,
};
fn wrapQuerySet(qset: c.WGPUQuerySet) QuerySet {
return .{
.ptr = qset.?,
.vtable = &query_set_vtable,
};
}
const query_set_vtable = QuerySet.VTable{
.reference = (struct {
pub fn reference(ptr: *anyopaque) void {
c.wgpuQuerySetReference(@ptrCast(c.WGPUQuerySet, ptr));
}
}).reference,
.release = (struct {
pub fn release(ptr: *anyopaque) void {
c.wgpuQuerySetRelease(@ptrCast(c.WGPUQuerySet, ptr));
}
}).release,
.setLabel = (struct {
pub fn setLabel(ptr: *anyopaque, label: [:0]const u8) void {
c.wgpuQuerySetSetLabel(@ptrCast(c.WGPUQuerySet, ptr), label);
}
}).setLabel,
.destroy = (struct {
pub fn destroy(ptr: *anyopaque) void {
c.wgpuQuerySetDestroy(@ptrCast(c.WGPUQuerySet, ptr));
}
}).destroy,
};
fn wrapPipelineLayout(layout: c.WGPUPipelineLayout) PipelineLayout {
return .{
.ptr = layout.?,
.vtable = &pipeline_layout_vtable,
};
}
const pipeline_layout_vtable = PipelineLayout.VTable{
.reference = (struct {
pub fn reference(ptr: *anyopaque) void {
c.wgpuPipelineLayoutReference(@ptrCast(c.WGPUPipelineLayout, ptr));
}
}).reference,
.release = (struct {
pub fn release(ptr: *anyopaque) void {
c.wgpuPipelineLayoutRelease(@ptrCast(c.WGPUPipelineLayout, ptr));
}
}).release,
.setLabel = (struct {
pub fn setLabel(ptr: *anyopaque, label: [:0]const u8) void {
c.wgpuPipelineLayoutSetLabel(@ptrCast(c.WGPUPipelineLayout, ptr), label);
}
}).setLabel,
};
fn wrapExternalTexture(texture: c.WGPUExternalTexture) ExternalTexture {
return .{
.ptr = texture.?,
.vtable = &external_texture_vtable,
};
}
const external_texture_vtable = ExternalTexture.VTable{
.reference = (struct {
pub fn reference(ptr: *anyopaque) void {
c.wgpuExternalTextureReference(@ptrCast(c.WGPUExternalTexture, ptr));
}
}).reference,
.release = (struct {
pub fn release(ptr: *anyopaque) void {
c.wgpuExternalTextureRelease(@ptrCast(c.WGPUExternalTexture, ptr));
}
}).release,
.setLabel = (struct {
pub fn setLabel(ptr: *anyopaque, label: [:0]const u8) void {
c.wgpuExternalTextureSetLabel(@ptrCast(c.WGPUExternalTexture, ptr), label);
}
}).setLabel,
.destroy = (struct {
pub fn destroy(ptr: *anyopaque) void {
c.wgpuExternalTextureDestroy(@ptrCast(c.WGPUExternalTexture, ptr));
}
}).destroy,
};
fn wrapBindGroup(group: c.WGPUBindGroup) BindGroup {
return .{
.ptr = group.?,
.vtable = &bind_group_vtable,
};
}
const bind_group_vtable = BindGroup.VTable{
.reference = (struct {
pub fn reference(ptr: *anyopaque) void {
c.wgpuBindGroupReference(@ptrCast(c.WGPUBindGroup, ptr));
}
}).reference,
.release = (struct {
pub fn release(ptr: *anyopaque) void {
c.wgpuBindGroupRelease(@ptrCast(c.WGPUBindGroup, ptr));
}
}).release,
.setLabel = (struct {
pub fn setLabel(ptr: *anyopaque, label: [:0]const u8) void {
c.wgpuBindGroupSetLabel(@ptrCast(c.WGPUBindGroup, ptr), label);
}
}).setLabel,
};
fn wrapBindGroupLayout(layout: c.WGPUBindGroupLayout) BindGroupLayout {
return .{
.ptr = layout.?,
.vtable = &bind_group_layout_vtable,
};
}
const bind_group_layout_vtable = BindGroupLayout.VTable{
.reference = (struct {
pub fn reference(ptr: *anyopaque) void {
c.wgpuBindGroupLayoutReference(@ptrCast(c.WGPUBindGroupLayout, ptr));
}
}).reference,
.release = (struct {
pub fn release(ptr: *anyopaque) void {
c.wgpuBindGroupLayoutRelease(@ptrCast(c.WGPUBindGroupLayout, ptr));
}
}).release,
.setLabel = (struct {
pub fn setLabel(ptr: *anyopaque, label: [:0]const u8) void {
c.wgpuBindGroupLayoutSetLabel(@ptrCast(c.WGPUBindGroupLayout, ptr), label);
}
}).setLabel,
};
fn wrapBuffer(buffer: c.WGPUBuffer) Buffer {
return .{
.ptr = buffer.?,
.vtable = &buffer_vtable,
};
}
const buffer_vtable = Buffer.VTable{
.reference = (struct {
pub fn reference(ptr: *anyopaque) void {
c.wgpuBufferReference(@ptrCast(c.WGPUBuffer, ptr));
}
}).reference,
.release = (struct {
pub fn release(ptr: *anyopaque) void {
c.wgpuBufferRelease(@ptrCast(c.WGPUBuffer, ptr));
}
}).release,
.getConstMappedRange = (struct {
pub fn getConstMappedRange(ptr: *anyopaque, offset: usize, size: usize) []const u8 {
const range = c.wgpuBufferGetConstMappedRange(@ptrCast(c.WGPUBuffer, ptr), offset, size);
return @ptrCast([*c]const u8, range.?)[0..size];
}
}).getConstMappedRange,
.getMappedRange = (struct {
pub fn getMappedRange(ptr: *anyopaque, offset: usize, size: usize) []u8 {
const range = c.wgpuBufferGetMappedRange(@ptrCast(c.WGPUBuffer, ptr), offset, size);
return @ptrCast([*c]u8, range.?)[0..size];
}
}).getMappedRange,
.setLabel = (struct {
pub fn setLabel(ptr: *anyopaque, label: [:0]const u8) void {
c.wgpuBufferSetLabel(@ptrCast(c.WGPUBuffer, ptr), label);
}
}).setLabel,
.destroy = (struct {
pub fn destroy(ptr: *anyopaque) void {
c.wgpuBufferDestroy(@ptrCast(c.WGPUBuffer, ptr));
}
}).destroy,
.mapAsync = (struct {
pub fn mapAsync(
ptr: *anyopaque,
mode: Buffer.MapMode,
offset: usize,
size: usize,
callback: *Buffer.MapCallback,
) void {
const cCallback = (struct {
pub fn cCallback(status: c.WGPUBufferMapAsyncStatus, userdata: ?*anyopaque) callconv(.C) void {
const callback_info = @ptrCast(*Buffer.MapCallback, @alignCast(std.meta.alignment(*Buffer.MapCallback), userdata.?));
callback_info.type_erased_callback(callback_info.type_erased_ctx, @intToEnum(Buffer.MapAsyncStatus, status));
}
}).cCallback;
c.wgpuBufferMapAsync(@ptrCast(c.WGPUBuffer, ptr), @enumToInt(mode), offset, size, cCallback, callback);
}
}).mapAsync,
.unmap = (struct {
pub fn unmap(ptr: *anyopaque) void {
c.wgpuBufferUnmap(@ptrCast(c.WGPUBuffer, ptr));
}
}).unmap,
};
fn wrapCommandBuffer(buffer: c.WGPUCommandBuffer) CommandBuffer {
return .{
.ptr = buffer.?,
.vtable = &command_buffer_vtable,
};
}
const command_buffer_vtable = CommandBuffer.VTable{
.reference = (struct {
pub fn reference(ptr: *anyopaque) void {
c.wgpuCommandBufferReference(@ptrCast(c.WGPUCommandBuffer, ptr));
}
}).reference,
.release = (struct {
pub fn release(ptr: *anyopaque) void {
c.wgpuCommandBufferRelease(@ptrCast(c.WGPUCommandBuffer, ptr));
}
}).release,
.setLabel = (struct {
pub fn setLabel(ptr: *anyopaque, label: [:0]const u8) void {
c.wgpuCommandBufferSetLabel(@ptrCast(c.WGPUCommandBuffer, ptr), label);
}
}).setLabel,
};
fn wrapCommandEncoder(enc: c.WGPUCommandEncoder) CommandEncoder {
return .{
.ptr = enc.?,
.vtable = &command_encoder_vtable,
};
}
const command_encoder_vtable = CommandEncoder.VTable{
.reference = (struct {
pub fn reference(ptr: *anyopaque) void {
c.wgpuCommandEncoderReference(@ptrCast(c.WGPUCommandEncoder, ptr));
}
}).reference,
.release = (struct {
pub fn release(ptr: *anyopaque) void {
c.wgpuCommandEncoderRelease(@ptrCast(c.WGPUCommandEncoder, ptr));
}
}).release,
.finish = (struct {
pub fn finish(ptr: *anyopaque, descriptor: ?*const CommandBuffer.Descriptor) CommandBuffer {
const desc: ?*c.WGPUCommandBufferDescriptor = if (descriptor) |d| &.{
.nextInChain = null,
.label = if (d.label) |l| l else "",
} else null;
return wrapCommandBuffer(c.wgpuCommandEncoderFinish(@ptrCast(c.WGPUCommandEncoder, ptr), desc));
}
}).finish,
.injectValidationError = (struct {
pub fn injectValidationError(ptr: *anyopaque, message: [*:0]const u8) void {
c.wgpuCommandEncoderInjectValidationError(@ptrCast(c.WGPUCommandEncoder, ptr), message);
}
}).injectValidationError,
.insertDebugMarker = (struct {
pub fn insertDebugMarker(ptr: *anyopaque, marker_label: [*:0]const u8) void {
c.wgpuCommandEncoderInsertDebugMarker(@ptrCast(c.WGPUCommandEncoder, ptr), marker_label);
}
}).insertDebugMarker,
.resolveQuerySet = (struct {
pub fn resolveQuerySet(
ptr: *anyopaque,
query_set: QuerySet,
first_query: u32,
query_count: u32,
destination: Buffer,
destination_offset: u64,
) void {
c.wgpuCommandEncoderResolveQuerySet(
@ptrCast(c.WGPUCommandEncoder, ptr),
@ptrCast(c.WGPUQuerySet, query_set.ptr),
first_query,
query_count,
@ptrCast(c.WGPUBuffer, destination.ptr),
destination_offset,
);
}
}).resolveQuerySet,
.setLabel = (struct {
pub fn setLabel(ptr: *anyopaque, label: [:0]const u8) void {
c.wgpuCommandEncoderSetLabel(@ptrCast(c.WGPUCommandEncoder, ptr), label);
}
}).setLabel,
.beginComputePass = (struct {
pub fn beginComputePass(ptr: *anyopaque, descriptor: ?*const ComputePassEncoder.Descriptor) ComputePassEncoder {
if (descriptor) |d| {
var few_timestamp_writes: [8]c.WGPUComputePassTimestampWrite = undefined;
const timestamp_writes = if (d.timestamp_writes.len <= 8) blk: {
for (d.timestamp_writes) |v, i| {
few_timestamp_writes[i] = c.WGPUComputePassTimestampWrite{
.querySet = @ptrCast(c.WGPUQuerySet, v.query_set.ptr),
.queryIndex = v.query_index,
.location = @enumToInt(v.location),
};
}
break :blk few_timestamp_writes[0..d.timestamp_writes.len];
} else blk: {
const mem = std.heap.page_allocator.alloc(c.WGPUComputePassTimestampWrite, d.timestamp_writes.len) catch unreachable;
for (d.timestamp_writes) |v, i| {
mem[i] = c.WGPUComputePassTimestampWrite{
.querySet = @ptrCast(c.WGPUQuerySet, v.query_set.ptr),
.queryIndex = v.query_index,
.location = @enumToInt(v.location),
};
}
break :blk mem;
};
defer if (d.timestamp_writes.len > 8) std.heap.page_allocator.free(timestamp_writes);
const desc = c.WGPUComputePassDescriptor{
.nextInChain = null,
.label = if (d.label) |l| l else null,
.timestampWriteCount = @intCast(u32, timestamp_writes.len),
.timestampWrites = @ptrCast([*]const c.WGPUComputePassTimestampWrite, timestamp_writes.ptr),
};
return wrapComputePassEncoder(c.wgpuCommandEncoderBeginComputePass(@ptrCast(c.WGPUCommandEncoder, ptr), &desc));
} else {
return wrapComputePassEncoder(c.wgpuCommandEncoderBeginComputePass(@ptrCast(c.WGPUCommandEncoder, ptr), null));
}
}
}).beginComputePass,
.beginRenderPass = (struct {
pub fn beginRenderPass(ptr: *anyopaque, d: *const RenderPassEncoder.Descriptor) RenderPassEncoder {
var few_color_attachments: [8]c.WGPURenderPassColorAttachment = undefined;
const color_attachments = if (d.color_attachments.len <= 8) blk: {
for (d.color_attachments) |v, i| {
few_color_attachments[i] = c.WGPURenderPassColorAttachment{
.view = @ptrCast(c.WGPUTextureView, v.view.ptr),
.resolveTarget = if (v.resolve_target) |t| @ptrCast(c.WGPUTextureView, t.ptr) else null,
.loadOp = @enumToInt(v.load_op),
.storeOp = @enumToInt(v.store_op),
.clearValue = @bitCast(c.WGPUColor, v.clear_value),
// deprecated:
.clearColor = c.WGPUColor{
.r = std.math.nan(f32),
.g = std.math.nan(f32),
.b = std.math.nan(f32),
.a = std.math.nan(f32),
},
};
}
break :blk few_color_attachments[0..d.color_attachments.len];
} else blk: {
const mem = std.heap.page_allocator.alloc(c.WGPURenderPassColorAttachment, d.color_attachments.len) catch unreachable;
for (d.color_attachments) |v, i| {
mem[i] = c.WGPURenderPassColorAttachment{
.view = @ptrCast(c.WGPUTextureView, v.view.ptr),
.resolveTarget = if (v.resolve_target) |t| @ptrCast(c.WGPUTextureView, t.ptr) else null,
.loadOp = @enumToInt(v.load_op),
.storeOp = @enumToInt(v.store_op),
.clearValue = @bitCast(c.WGPUColor, v.clear_value),
// deprecated:
.clearColor = c.WGPUColor{
.r = std.math.nan(f32),
.g = std.math.nan(f32),
.b = std.math.nan(f32),
.a = std.math.nan(f32),
},
};
}
break :blk mem;
};
defer if (d.color_attachments.len > 8) std.heap.page_allocator.free(color_attachments);
var few_timestamp_writes: [8]c.WGPURenderPassTimestampWrite = undefined;
const timestamp_writes = if (d.timestamp_writes) |writes| blk: {
if (writes.len <= 8) {
for (writes) |v, i| {
few_timestamp_writes[i] = c.WGPURenderPassTimestampWrite{
.querySet = @ptrCast(c.WGPUQuerySet, v.query_set.ptr),
.queryIndex = v.query_index,
.location = @enumToInt(v.location),
};
}
break :blk few_timestamp_writes[0..writes.len];
} else {
const mem = std.heap.page_allocator.alloc(c.WGPURenderPassTimestampWrite, writes.len) catch unreachable;
for (writes) |v, i| {
mem[i] = c.WGPURenderPassTimestampWrite{
.querySet = @ptrCast(c.WGPUQuerySet, v.query_set.ptr),
.queryIndex = v.query_index,
.location = @enumToInt(v.location),
};
}
break :blk mem;
}
} else null;
defer if (timestamp_writes != null and timestamp_writes.?.len > 8) std.heap.page_allocator.free(timestamp_writes.?);
const desc = c.WGPURenderPassDescriptor{
.nextInChain = null,
.label = if (d.label) |l| l else null,
.colorAttachmentCount = @intCast(u32, color_attachments.len),
.colorAttachments = color_attachments.ptr,
.depthStencilAttachment = if (d.depth_stencil_attachment) |v| &c.WGPURenderPassDepthStencilAttachment{
.view = @ptrCast(c.WGPUTextureView, v.view.ptr),
.depthLoadOp = @enumToInt(v.depth_load_op),
.depthStoreOp = @enumToInt(v.depth_store_op),
.clearDepth = v.clear_depth,
.depthClearValue = v.depth_clear_value,
.depthReadOnly = v.depth_read_only,
.stencilLoadOp = @enumToInt(v.stencil_load_op),
.stencilStoreOp = @enumToInt(v.stencil_store_op),
.clearStencil = v.clear_stencil,
.stencilClearValue = v.stencil_clear_value,
.stencilReadOnly = v.stencil_read_only,
} else null,
.occlusionQuerySet = if (d.occlusion_query_set) |v| @ptrCast(c.WGPUQuerySet, v.ptr) else null,
.timestampWriteCount = if (timestamp_writes) |v| @intCast(u32, v.len) else 0,
.timestampWrites = if (timestamp_writes) |v| @ptrCast([*]const c.WGPURenderPassTimestampWrite, v.ptr) else null,
};
return wrapRenderPassEncoder(c.wgpuCommandEncoderBeginRenderPass(@ptrCast(c.WGPUCommandEncoder, ptr), &desc));
}
}).beginRenderPass,
.clearBuffer = (struct {
pub fn clearBuffer(ptr: *anyopaque, buffer: Buffer, offset: u64, size: u64) void {
c.wgpuCommandEncoderClearBuffer(
@ptrCast(c.WGPUCommandEncoder, ptr),
@ptrCast(c.WGPUBuffer, buffer.ptr),
offset,
size,
);
}
}).clearBuffer,
.copyBufferToBuffer = (struct {
pub fn copyBufferToBuffer(
ptr: *anyopaque,
source: Buffer,
source_offset: u64,
destination: Buffer,
destination_offset: u64,
size: u64,
) void {
c.wgpuCommandEncoderCopyBufferToBuffer(
@ptrCast(c.WGPUCommandEncoder, ptr),
@ptrCast(c.WGPUBuffer, source.ptr),
source_offset,
@ptrCast(c.WGPUBuffer, destination.ptr),
destination_offset,
size,
);
}
}).copyBufferToBuffer,
.copyBufferToTexture = (struct {
pub fn copyBufferToTexture(
ptr: *anyopaque,
source: *const ImageCopyBuffer,
destination: *const ImageCopyTexture,
copy_size: *const Extent3D,
) void {
c.wgpuCommandEncoderCopyBufferToTexture(
@ptrCast(c.WGPUCommandEncoder, ptr),
&convertImageCopyBuffer(source),
&convertImageCopyTexture(destination),
@ptrCast(*const c.WGPUExtent3D, copy_size),
);
}
}).copyBufferToTexture,
.copyTextureToBuffer = (struct {
pub fn copyTextureToBuffer(
ptr: *anyopaque,
source: *const ImageCopyTexture,
destination: *const ImageCopyBuffer,
copy_size: *const Extent3D,
) void {
c.wgpuCommandEncoderCopyTextureToBuffer(
@ptrCast(c.WGPUCommandEncoder, ptr),
&convertImageCopyTexture(source),
&convertImageCopyBuffer(destination),
@ptrCast(*const c.WGPUExtent3D, copy_size),
);
}
}).copyTextureToBuffer,
.copyTextureToTexture = (struct {
pub fn copyTextureToTexture(
ptr: *anyopaque,
source: *const ImageCopyTexture,
destination: *const ImageCopyTexture,
copy_size: *const Extent3D,
) void {
c.wgpuCommandEncoderCopyTextureToTexture(
@ptrCast(c.WGPUCommandEncoder, ptr),
&convertImageCopyTexture(source),
&convertImageCopyTexture(destination),
@ptrCast(*const c.WGPUExtent3D, copy_size),
);
}
}).copyTextureToTexture,
.popDebugGroup = (struct {
pub fn popDebugGroup(ptr: *anyopaque) void {
c.wgpuCommandEncoderPopDebugGroup(@ptrCast(c.WGPUCommandEncoder, ptr));
}
}).popDebugGroup,
.pushDebugGroup = (struct {
pub fn pushDebugGroup(ptr: *anyopaque, group_label: [*:0]const u8) void {
c.wgpuCommandEncoderPushDebugGroup(@ptrCast(c.WGPUCommandEncoder, ptr), group_label);
}
}).pushDebugGroup,
.writeBuffer = (struct {
pub fn writeBuffer(ptr: *anyopaque, buffer: Buffer, buffer_offset: u64, data: [*]const u8, size: u64) void {
c.wgpuCommandEncoderWriteBuffer(
@ptrCast(c.WGPUCommandEncoder, ptr),
@ptrCast(c.WGPUBuffer, buffer.ptr),
buffer_offset,
data,
size,
);
}
}).writeBuffer,
.writeTimestamp = (struct {
pub fn writeTimestamp(ptr: *anyopaque, query_set: QuerySet, query_index: u32) void {
c.wgpuCommandEncoderWriteTimestamp(
@ptrCast(c.WGPUCommandEncoder, ptr),
@ptrCast(c.WGPUQuerySet, query_set.ptr),
query_index,
);
}
}).writeTimestamp,
};
inline fn convertImageCopyBuffer(v: *const ImageCopyBuffer) c.WGPUImageCopyBuffer {
return .{
.nextInChain = null,
.layout = convertTextureDataLayout(v.layout),
.buffer = @ptrCast(c.WGPUBuffer, v.buffer.ptr),
};
}
inline fn convertImageCopyTexture(v: *const ImageCopyTexture) c.WGPUImageCopyTexture {
return .{
.nextInChain = null,
.texture = @ptrCast(c.WGPUTexture, v.texture.ptr),
.mipLevel = v.mip_level,
.origin = @bitCast(c.WGPUOrigin3D, v.origin),
.aspect = @enumToInt(v.aspect),
};
}
inline fn convertTextureDataLayout(v: Texture.DataLayout) c.WGPUTextureDataLayout {
return .{
.nextInChain = null,
.offset = v.offset,
.bytesPerRow = v.bytes_per_row,
.rowsPerImage = v.rows_per_image,
};
}
fn wrapComputePassEncoder(enc: c.WGPUComputePassEncoder) ComputePassEncoder {
return .{
.ptr = enc.?,
.vtable = &compute_pass_encoder_vtable,
};
}
const compute_pass_encoder_vtable = ComputePassEncoder.VTable{
.reference = (struct {
pub fn reference(ptr: *anyopaque) void {
c.wgpuComputePassEncoderReference(@ptrCast(c.WGPUComputePassEncoder, ptr));
}
}).reference,
.release = (struct {
pub fn release(ptr: *anyopaque) void {
c.wgpuComputePassEncoderRelease(@ptrCast(c.WGPUComputePassEncoder, ptr));
}
}).release,
.dispatch = (struct {
pub fn dispatch(
ptr: *anyopaque,
workgroup_count_x: u32,
workgroup_count_y: u32,
workgroup_count_z: u32,
) void {
c.wgpuComputePassEncoderDispatch(
@ptrCast(c.WGPUComputePassEncoder, ptr),
workgroup_count_x,
workgroup_count_y,
workgroup_count_z,
);
}
}).dispatch,
.dispatchIndirect = (struct {
pub fn dispatchIndirect(
ptr: *anyopaque,
indirect_buffer: Buffer,
indirect_offset: u64,
) void {
c.wgpuComputePassEncoderDispatchIndirect(
@ptrCast(c.WGPUComputePassEncoder, ptr),
@ptrCast(c.WGPUBuffer, indirect_buffer.ptr),
indirect_offset,
);
}
}).dispatchIndirect,
.end = (struct {
pub fn end(ptr: *anyopaque) void {
c.wgpuComputePassEncoderEnd(@ptrCast(c.WGPUComputePassEncoder, ptr));
}
}).end,
.setBindGroup = (struct {
pub fn setBindGroup(
ptr: *anyopaque,
group_index: u32,
group: BindGroup,
dynamic_offsets: ?[]const u32,
) void {
c.wgpuComputePassEncoderSetBindGroup(
@ptrCast(c.WGPUComputePassEncoder, ptr),
group_index,
@ptrCast(c.WGPUBindGroup, group.ptr),
if (dynamic_offsets) |d| @intCast(u32, d.len) else 0,
if (dynamic_offsets) |d| d.ptr else null,
);
}
}).setBindGroup,
.setLabel = (struct {
pub fn setLabel(ptr: *anyopaque, label: [:0]const u8) void {
c.wgpuComputePassEncoderSetLabel(@ptrCast(c.WGPUComputePassEncoder, ptr), label);
}
}).setLabel,
.insertDebugMarker = (struct {
pub fn insertDebugMarker(ptr: *anyopaque, marker_label: [*:0]const u8) void {
c.wgpuComputePassEncoderInsertDebugMarker(@ptrCast(c.WGPUComputePassEncoder, ptr), marker_label);
}
}).insertDebugMarker,
.popDebugGroup = (struct {
pub fn popDebugGroup(ptr: *anyopaque) void {
c.wgpuComputePassEncoderPopDebugGroup(@ptrCast(c.WGPUComputePassEncoder, ptr));
}
}).popDebugGroup,
.pushDebugGroup = (struct {
pub fn pushDebugGroup(ptr: *anyopaque, group_label: [*:0]const u8) void {
c.wgpuComputePassEncoderPushDebugGroup(@ptrCast(c.WGPUComputePassEncoder, ptr), group_label);
}
}).pushDebugGroup,
.setPipeline = (struct {
pub fn setPipeline(ptr: *anyopaque, pipeline: ComputePipeline) void {
c.wgpuComputePassEncoderSetPipeline(@ptrCast(c.WGPUComputePassEncoder, ptr), @ptrCast(c.WGPUComputePipeline, pipeline.ptr));
}
}).setPipeline,
.writeTimestamp = (struct {
pub fn writeTimestamp(ptr: *anyopaque, query_set: QuerySet, query_index: u32) void {
c.wgpuComputePassEncoderWriteTimestamp(
@ptrCast(c.WGPUComputePassEncoder, ptr),
@ptrCast(c.WGPUQuerySet, query_set.ptr),
query_index,
);
}
}).writeTimestamp,
};
fn wrapComputePipeline(pipeline: c.WGPUComputePipeline) ComputePipeline {
return .{
.ptr = pipeline.?,
.vtable = &compute_pipeline_vtable,
};
}
const compute_pipeline_vtable = ComputePipeline.VTable{
.reference = (struct {
pub fn reference(ptr: *anyopaque) void {
c.wgpuComputePipelineReference(@ptrCast(c.WGPUComputePipeline, ptr));
}
}).reference,
.release = (struct {
pub fn release(ptr: *anyopaque) void {
c.wgpuComputePipelineRelease(@ptrCast(c.WGPUComputePipeline, ptr));
}
}).release,
.setLabel = (struct {
pub fn setLabel(ptr: *anyopaque, label: [:0]const u8) void {
c.wgpuComputePipelineSetLabel(@ptrCast(c.WGPUComputePipeline, ptr), label);
}
}).setLabel,
.getBindGroupLayout = (struct {
pub fn getBindGroupLayout(ptr: *anyopaque, group_index: u32) BindGroupLayout {
return wrapBindGroupLayout(c.wgpuComputePipelineGetBindGroupLayout(
@ptrCast(c.WGPUComputePipeline, ptr),
group_index,
));
}
}).getBindGroupLayout,
};
test {
_ = wrap;
_ = interface_vtable;
_ = interface;
_ = createSurface;
_ = surface_vtable;
_ = adapter_vtable;
_ = wrapDevice;
_ = device_vtable;
_ = wrapQueue;
_ = wrapShaderModule;
_ = wrapSwapChain;
_ = wrapTextureView;
_ = wrapTexture;
_ = wrapSampler;
_ = wrapRenderPipeline;
_ = wrapRenderPassEncoder;
_ = wrapRenderBundleEncoder;
_ = wrapRenderBundle;
_ = wrapQuerySet;
_ = wrapPipelineLayout;
_ = wrapExternalTexture;
_ = wrapBindGroup;
_ = wrapBindGroupLayout;
_ = wrapBuffer;
_ = wrapCommandBuffer;
_ = wrapCommandEncoder;
_ = wrapComputePassEncoder;
_ = wrapComputePipeline;
} | gpu/src/NativeInstance.zig |
const std = @import("std");
const tracy = @import("tracy.zig");
usingnamespace @import("threadpool");
usingnamespace @import("av-common.zig");
// we have to use 2 threads because sws_scale doesn't allow slicing in the middle for whatever reason
const PoolSize = 2;
pub fn FrameProcessor(comptime UserDataType: type) type {
return struct {
const CallbackFunction = fn ([*]const u8, ?UserDataType) void;
const PoolType = ThreadPool(rescaleFrame, freeScaler);
const Self = @This();
formatContext: [*c]AVFormatContext = undefined,
codecContext: [*c]AVCodecContext = undefined,
packet: [*c]AVPacket = undefined,
inFrame: [*c]AVFrame = undefined,
outFrame: [*c]AVFrame = undefined,
working: @Frame(__processNextFrame) = undefined,
videoIndex: usize = undefined,
callback: ?CallbackFunction = null,
userData: ?UserDataType = null,
scalingPool: *PoolType = undefined,
started: bool = false,
done: bool = false,
pub fn open(self: *Self, source: [*:0]const u8, width: u16, height: u16) !f64 {
if (avformat_alloc_context()) |formatContext| {
self.formatContext = formatContext;
errdefer avformat_close_input(&self.formatContext);
} else {
return error.AllocFailed;
}
if (av_frame_alloc()) |inFrame| {
self.inFrame = inFrame;
errdefer av_frame_free(&self.inFrame);
} else {
return error.AllocFailed;
}
if (av_frame_alloc()) |outFrame| {
self.outFrame = outFrame;
errdefer av_frame_free(&self.outFrame);
} else {
return error.AllocFailed;
}
if (av_packet_alloc()) |packet| {
self.packet = packet;
errdefer av_packet_free(&self.packet);
} else {
return error.AllocFailed;
}
if (avformat_open_input(&self.formatContext, source, null, null) < 0) {
return error.OpenInputFailed;
}
if (avformat_find_stream_info(self.formatContext, null) < 0) {
return error.NoStreamInfo;
}
var codec: [*c]AVCodec = undefined;
self.videoIndex = try findVideoIndex(self.formatContext, &codec);
self.codecContext = avcodec_alloc_context3(codec);
errdefer avcodec_free_context(&self.codecContext);
if (avcodec_parameters_to_context(self.codecContext, self.formatContext.*.streams[self.videoIndex].*.codecpar) < 0) {
return error.CodecParamConversionFailed;
}
if (avcodec_open2(self.codecContext, codec, null) < 0) {
return error.CodecOpenFailed;
}
try populateOutFrame(self.outFrame, width, height);
self.scalingPool = try PoolType.init(std.heap.c_allocator, PoolSize);
self.started = false;
self.done = false;
return 1000.0 * (1.0 / av_q2d(self.formatContext.*.streams[self.videoIndex].*.r_frame_rate));
}
pub fn processNextFrame(self: *Self) bool {
if (self.done) {
return false;
}
if (self.started) {
resume self.working;
} else {
self.working = async self.__processNextFrame();
self.started = true;
}
return true;
}
fn __processNextFrame(self: *Self) void {
if (self.done) return;
while (av_read_frame(self.formatContext, self.packet) == 0) {
if (self.packet.*.stream_index == self.videoIndex) {
if (avcodec_send_packet(self.codecContext, self.packet) < 0) {
self.done = true;
return;
}
while (true) {
const response = avcodec_receive_frame(self.codecContext, self.inFrame);
if (response == AVERROR(EAGAIN) or response == AVERROR_EOF) {
break;
} else if (response < 0) {
self.done = true;
return;
}
const tracy_scale = tracy.ZoneN(@src(), "Scaling");
var start: c_int = 0;
var end: c_int = 0;
var offsetMul: c_int = 1;
while (offsetMul <= PoolSize) : (offsetMul += 1) {
start = end;
end = @divFloor((self.inFrame.*.height * offsetMul), PoolSize);
self.scalingPool.submitTask(.{
self.inFrame,
self.outFrame,
start,
end - start,
}) catch @panic("Failed to submit scaling task");
}
self.scalingPool.awaitTermination() catch |err| {
if (err == error.Forced) {
self.done = true;
return;
} else {
@panic("awaitTermination error: not forced?");
}
};
tracy_scale.End();
if (self.callback) |cb| {
const tracy_callback = tracy.ZoneN(@src(), "Callback");
@call(.{}, cb, .{ self.outFrame.*.data[0], self.userData });
tracy_callback.End();
}
suspend {}
}
}
av_packet_unref(self.packet);
}
self.done = true;
}
pub fn close(self: *Self) !void {
self.scalingPool.shutdown();
avcodec_free_context(&self.codecContext);
avformat_close_input(&self.formatContext);
av_packet_free(&self.packet);
av_frame_free(&self.inFrame);
av_frame_free(&self.outFrame);
// we need to free scaler, but i'm not exactly sure how?
// just leak it for now, figure it out later
}
};
}
fn findVideoIndex(formatContext: [*c]AVFormatContext, codec: *[*c]AVCodec) !usize {
var tmpIndex = av_find_best_stream(formatContext, AVMEDIA_TYPE_VIDEO, -1, -1, codec, 0);
if (tmpIndex < 0) {
return error.NoSuitableStream;
}
return @intCast(usize, tmpIndex);
}
fn populateOutFrame(outFrame: [*c]AVFrame, width: u16, height: u16) !void {
const alignment = @alignOf(u16);
const bufferSize = av_image_get_buffer_size(
AV_PIX_FMT_RGB444LE,
width,
height,
alignment,
);
if (bufferSize < 0) {
return error.AllocFailed;
}
if (av_malloc(@intCast(usize, bufferSize) * @sizeOf(u8))) |buffer| {
errdefer av_freep(buffer);
if (av_image_fill_arrays(
@ptrCast([*c][*c]u8, &outFrame.*.data[0]),
@ptrCast([*c]c_int, &outFrame.*.linesize[0]),
@ptrCast([*c]const u8, buffer),
AV_PIX_FMT_RGB444LE,
width,
height,
alignment,
) < 0) {
return error.AllocFailed;
}
outFrame.*.width = width;
outFrame.*.height = height;
outFrame.*.format = AV_PIX_FMT_RGB444LE;
} else {
return error.AllocFailed;
}
}
threadlocal var scaler: ?*SwsContext = null;
fn rescaleFrame(in: [*c]AVFrame, out: [*c]AVFrame, y: c_int, h: c_int) void {
if (scaler == null) {
scaler = sws_getContext(
// source parameters
in.*.width,
in.*.height,
in.*.format,
// target parameters
out.*.width,
out.*.height,
// note, if it crashes, i'm a dipshit and populateOutFrame doesn't set this
out.*.format,
SWS_POINT,
null,
null,
null,
) orelse @panic("Failed scaler context creation");
}
var inSlicedPlanes: [8][*c]u8 = undefined;
// populate inSlicedPlanes with... planes that are sliced
// we can't just add offsets and be done with it because of formats like YUV,
// where U and V has half the amount of Y's.
var plane: usize = 0;
while (plane < av_pix_fmt_count_planes(in.*.format)) : (plane += 1) {
var vsub: u5 = undefined;
if ((plane + 1) & 2 > 0) {
const fmt = av_pix_fmt_desc_get(in.*.format);
vsub = @truncate(u5, fmt.*.log2_chroma_h);
} else {
vsub = 0;
}
const inOffset = (y >> vsub) * in.*.linesize[plane];
inSlicedPlanes[plane] = addDataOffset(in.*.data[plane], @intCast(usize, inOffset));
}
if (sws_scale(
scaler,
@ptrCast([*c]const [*c]const u8, &inSlicedPlanes[0]),
@ptrCast([*c]const c_int, &in.*.linesize[0]),
y,
h,
@ptrCast([*c]const [*c]u8, &out.*.data[0]),
@ptrCast([*c]c_int, &out.*.linesize[0]),
) < 0) {
@panic("Failed to scale");
}
}
fn freeScaler() void {
sws_freeContext(scaler);
}
inline fn addDataOffset(src: [*c]u8, offset: usize) [*c]u8 {
return @intToPtr([*c]u8, @ptrToInt(src) + offset);
} | nativemap/src/frame-processor.zig |
const std = @import("std");
const log = std.log;
const sql = @import("sqlite");
const mem = std.mem;
const print = std.debug.print;
const process = std.process;
const Allocator = std.mem.Allocator;
const command = @import("cli.zig");
const Storage = @import("feed_db.zig").Storage;
const Cli = command.Cli;
const clap = @import("clap");
const known_folders = @import("known-folders");
const server = @import("server.zig");
// NOTE: This will return error.CouldNotConnect when adding url
// pub const io_mode = .evented;
// TODO: wait for https://github.com/truemedian/zfetch/issues/10
pub const log_level = std.log.Level.debug;
pub const known_folders_config = .{
.xdg_on_mac = true,
};
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const base_allocator = gpa.allocator();
var arena = std.heap.ArenaAllocator.init(base_allocator);
defer arena.deinit();
const arena_allocator = arena.allocator();
const help_flag = comptime newFlag("help", false, "Display this help and exit.");
const db_flag = comptime newFlag("db", "~/.config/feedgaze/feedgaze.sqlite", "Sqlite database location.");
const url_flag = comptime newFlag("url", true, "Apply action only to url feeds.");
const local_flag = comptime newFlag("local", true, "Apply action only to local feeds.");
const force_flag = comptime newFlag("force", false, "Force update all feeds.");
const default_flag = comptime newFlag("default", @as(u32, 1), "Auto pick a item from printed out list.");
const add_tags_flag = comptime newFlag("tags", "", "Add (comma separated) tags to feed .");
comptime var base_flags = [_]FlagOpt{ help_flag, url_flag, local_flag, db_flag };
comptime var remove_flags = base_flags ++ [_]FlagOpt{default_flag};
comptime var add_flags = remove_flags ++ [_]FlagOpt{add_tags_flag};
comptime var update_flags = base_flags ++ [_]FlagOpt{force_flag};
// TODO?: maybe make add and remove flags into subcommands: tag add, tag remove
// Another option would be make separate 'tag' commands: tag-add, tag-remove
comptime var tag_flags = [_]FlagOpt{
help_flag,
db_flag,
newFlag("add", false, "Add tag."),
newFlag("remove", false, "Remove tag."),
newFlag("id", @as(u64, 0), "Feed's id."),
newFlag("location", "", "Feed's location."),
newFlag("remove-all", false, "Will remove all tags from feed. Requires --id or --location flag."),
};
comptime var server_flags = [_]FlagOpt{ help_flag, db_flag };
const BaseCmd = FlagSet(&base_flags);
const subcmds = struct {
const add = FlagSet(&add_flags);
const remove = FlagSet(&remove_flags);
const update = FlagSet(&update_flags);
const search = BaseCmd;
const clean = BaseCmd;
const @"print-feeds" = BaseCmd;
const @"print-items" = BaseCmd;
const tag = FlagSet(&tag_flags);
const server = FlagSet(&server_flags);
};
var args = try process.argsAlloc(std.testing.allocator);
defer process.argsFree(std.testing.allocator, args);
if (args.len == 1) {
log.err("No subcommand entered.", .{});
try usage(subcmds);
return error.MissingSubCommand;
}
const Subcommand = std.meta.DeclEnum(subcmds);
const subcmd_str = args[1];
const subcmd = std.meta.stringToEnum(Subcommand, subcmd_str) orelse {
// Check if help flag was entered
comptime var root_flags = [_]FlagOpt{help_flag};
var root_cmd = FlagSet(&root_flags){};
try root_cmd.parse(args[1..]);
if (root_cmd.getFlag("help")) |f| {
if (try f.getBoolean()) {
try usage(subcmds);
return;
}
}
log.err("Unknown subcommand '{s}'.", .{subcmd_str});
return error.UnknownSubCommand;
};
var args_rest: [][:0]const u8 = undefined;
var db_path: []const u8 = undefined;
var has_help = false;
var is_tag_add = false;
var is_tag_remove = false;
var is_tag_remove_all = false;
var tags: []const u8 = "";
var cli_options = command.CliOptions{};
var tag_args = command.TagArgs{};
// Parse input args
inline for (comptime std.meta.declarations(subcmds)) |decl| {
if (subcmd == std.meta.stringToEnum(Subcommand, decl.name)) {
var cmd = @field(subcmds, decl.name){};
try cmd.parse(args[2..]);
args_rest = cmd.args;
if (cmd.getFlag("help")) |f| {
has_help = try f.getBoolean();
}
db_path = try cmd.getFlag("db").?.getString();
var local = cli_options.local;
if (cmd.getFlag("local")) |value| {
local = try value.getBoolean();
}
var url = cli_options.url;
if (cmd.getFlag("url")) |value| {
url = try value.getBoolean();
}
cli_options.url = url or !local;
cli_options.local = local or !url;
if (cmd.getFlag("force")) |force| {
cli_options.force = try force.getBoolean();
}
if (cmd.getFlag("default")) |value| {
cli_options.default = try value.getInt();
}
if (cmd.getFlag("tags")) |value| {
tags = try value.getString();
}
// Tag command flags
if (cmd.getFlag("add")) |some| {
is_tag_add = try some.getBoolean();
}
if (cmd.getFlag("remove")) |some| {
is_tag_remove = try some.getBoolean();
}
if (cmd.getFlag("remove-all")) |some| {
is_tag_remove_all = try some.getBoolean();
}
if (cmd.getFlag("location")) |some| {
tag_args.location = try some.getString();
}
if (cmd.getFlag("id")) |some| {
tag_args.id = @intCast(u64, try some.getInt());
}
// Don't use break, continue, return inside inline loops
// https://github.com/ziglang/zig/issues/2727
// https://github.com/ziglang/zig/issues/9524
}
}
if (has_help) {
try usage(subcmds);
return;
}
const subcom_input_required = [_]Subcommand{ .add, .remove, .search };
for (subcom_input_required) |required| {
if (required == subcmd and args_rest.len == 0) {
log.err("Subcommand '{s}' requires input(s)", .{subcmd_str});
return error.SubcommandRequiresInput;
}
}
// Check tag command conditions
if (subcmd == .tag) {
if (!(is_tag_add or is_tag_remove or is_tag_remove_all)) {
log.err("Subcommand '{s}' requires --add, --remove or --remove-all flag", .{subcmd_str});
return error.MissingFlag;
} else if (is_tag_add and is_tag_remove) {
log.err("Subcommand '{s}' can't have both --add and --remove flag", .{subcmd_str});
return error.ConflictWithFlags;
} else if (is_tag_add and is_tag_remove_all) {
log.err("Subcommand '{s}' can't have both --add and --remove-all flag", .{subcmd_str});
return error.ConflictWithFlags;
} else if (is_tag_add and is_tag_remove_all) {
log.err("Subcommand '{s}' can't have both --remove and --remove-all flag", .{subcmd_str});
return error.ConflictWithFlags;
} else if (tag_args.location.len == 0 and tag_args.id == 0) {
if (is_tag_remove_all) {
log.err("Subcommand '{s}' with --remove-all flag requires --id or --location flag", .{subcmd_str});
return error.MissingFlag;
} else if (is_tag_add) {
log.err("Subcommand '{s}' with --add flag requires --id or --location flag", .{subcmd_str});
return error.MissingFlag;
}
} else if ((is_tag_add or is_tag_remove) and args_rest.len == 0) {
log.err("Subcommand '{s}' with flag --add or --remove requires input(s)", .{subcmd_str});
}
if (is_tag_add) {
tag_args.action = .add;
} else if (is_tag_remove) {
tag_args.action = .remove;
} else if (is_tag_remove_all) {
tag_args.action = .remove_all;
}
}
var storage = blk: {
var tmp_arena = std.heap.ArenaAllocator.init(base_allocator);
defer tmp_arena.deinit();
const tmp_allocator = tmp_arena.allocator();
if (mem.eql(u8, ":memory:", db_path)) {
break :blk try Storage.init(arena_allocator, null);
}
var db_location = try getDatabaseLocation(tmp_allocator, db_path);
break :blk try Storage.init(arena_allocator, db_location);
};
var writer = std.io.getStdOut().writer();
const reader = std.io.getStdIn().reader();
var cli = command.makeCli(arena_allocator, &storage, cli_options, writer, reader);
switch (subcmd) {
.server => try server.run(&storage),
.add => try cli.addFeed(args_rest, tags),
.update => try cli.updateFeeds(),
.remove => try cli.deleteFeed(args_rest),
.search => try cli.search(args_rest),
.clean => try cli.cleanItems(),
.tag => try cli.tagCmd(args_rest, tag_args),
.@"print-feeds" => try cli.printFeeds(),
.@"print-items" => try cli.printAllItems(),
}
}
fn getDatabaseLocation(allocator: Allocator, db_option: ?[]const u8) ![:0]const u8 {
if (db_option) |loc| {
const db_file = block: {
if (std.fs.path.isAbsolute(loc)) {
break :block try std.mem.joinZ(allocator, loc, &.{});
}
break :block try std.fs.path.joinZ(allocator, &.{ try std.process.getCwdAlloc(allocator), loc });
};
std.fs.accessAbsolute(db_file, .{}) catch |err| switch (err) {
error.FileNotFound => {
const stderr = std.io.getStdErr().writer();
try stderr.print("Provided path '{s}' doesn't exist\n", .{db_file});
var buf: [1]u8 = undefined;
while (true) {
try stderr.print("Do you want to create database in '{s}' (Y/n)? ", .{db_file});
_ = try std.io.getStdIn().read(&buf);
const first = buf[0];
// Clear characters from stdin
while ((try std.io.getStdIn().read(&buf)) != 0) if (buf[0] == '\n') break;
const char = std.ascii.toLower(first);
if (char == 'y') {
break;
} else if (char == 'n') {
print("Exit app\n", .{});
std.os.exit(0);
}
try stderr.print("Invalid input '{s}' try again.\n", .{db_file});
}
},
else => return err,
};
const db_dir = std.fs.path.dirname(db_file).?;
std.fs.makeDirAbsolute(db_dir) catch |err| switch (err) {
error.PathAlreadyExists => {},
else => {
log.err("Failed to create directory in '{s}' for database file feedgaze.sqlite", .{db_dir});
return err;
},
};
return db_file;
}
// Get default database location
const db_file = block: {
if (try known_folders.getPath(allocator, .local_configuration)) |path| {
break :block try std.fs.path.joinZ(allocator, &.{ path, "feedgaze", "feedgaze.sqlite" });
}
const builtin = @import("builtin");
if (builtin.target.os.tag == .linux) {
if (try known_folders.getPath(allocator, .home)) |path| {
break :block try std.fs.path.joinZ(allocator, &.{ path, ".config", "feedgaze", "feedgaze.sqlite" });
}
}
log.err("Failed to find local configuration or home directory\n", .{});
return error.MissingConfigAndHomeDir;
};
const db_dir = std.fs.path.dirname(db_file).?;
std.fs.makeDirAbsolute(db_dir) catch |err| switch (err) {
error.PathAlreadyExists => {},
else => {
log.err("Failed to create directory in '{s}' for database file feedgaze.sqlite", .{db_dir});
return err;
},
};
return db_file;
}
const FlagOpt = struct {
name: []const u8,
description: []const u8,
ty: type,
default_value: ?*const anyopaque,
input_value: ?[]const u8 = null,
};
const Flag = struct {
const Self = @This();
name: []const u8,
description: []const u8,
default_value: FlagValue,
input_value: ?[]const u8 = null,
fn parseBoolean(value: []const u8) ?bool {
const true_values = .{ "1", "t", "T", "true", "TRUE", "True" };
const false_values = .{ "0", "f", "F", "false", "FALSE", "False" };
inline for (true_values) |t_value| if (mem.eql(u8, value, t_value)) return true;
inline for (false_values) |f_value| if (mem.eql(u8, value, f_value)) return false;
return null;
}
pub fn getBoolean(self: Self) !bool {
if (self.default_value != .boolean) {
return error.NotBooleanValueType;
}
if (self.input_value) |input| {
return parseBoolean(input) orelse self.default_value.boolean;
}
return self.default_value.boolean;
}
pub fn getString(self: Self) ![]const u8 {
if (self.default_value != .string) {
return error.NotStringValueType;
}
return self.input_value orelse self.default_value.string;
}
pub fn getInt(self: Self) !i32 {
if (self.input_value) |value| {
return try std.fmt.parseInt(i32, value, 10);
}
return self.default_value.int;
}
};
const FlagValue = union(enum) {
boolean: bool,
string: []const u8,
int: i32,
};
// TODO: for saving different types in same field check https://github.com/ziglang/zig/issues/10705
// * Tried to save default_value as '?*const anyopaque'. Also default_type fields as 'type'.
// The problem became default_type which requires comptime. Try to replace default_type
// 'type' with 'TypeInfo'
// * Try to create one functions (getValue) to get flag value. Current setup doesn't allow
// to figure out return type during comptime. To achive this would have to make Flag type
// take a comptime type arg. Then probably would have to store different types into
// different type arrays in FlagSet.
// TODO?: try to add null type that would be parsed as bool or value
// Can cause problems when it is last flag without arguement but there is pos/input value
// Flags can be:
// '--flag-null' - default value will be used
// '--flag-null 2' - 2 will be used
// <no flag> - default value will be used
fn FlagSet(comptime inputs: []FlagOpt) type {
comptime var precomputed = blk: {
var flags: [inputs.len]Flag = undefined;
for (inputs) |flag, i| {
const type_info = @typeInfo(flag.ty);
const default_value = switch (type_info) {
.Bool => .{ .boolean = @ptrCast(*const flag.ty, flag.default_value.?).* },
.Pointer => |ptr| blk_ptr: {
const child_type = std.meta.Child(ptr.child);
if (child_type == u8) {
break :blk_ptr .{ .string = @ptrCast(*const flag.ty, flag.default_value.?).* };
}
@compileError("Expecting a u8 slice ([]const u8, []u8), got slice with " ++ @typeName(child_type));
},
.Int => .{ .int = @intCast(i64, @ptrCast(*const flag.ty, flag.default_value.?).*) },
else => unreachable,
};
flags[i] = Flag{
.name = flag.name,
.description = flag.description,
.default_value = default_value,
.input_value = flag.input_value,
};
}
break :blk .{ .flags = flags };
};
return struct {
const Self = @This();
pub var flags = precomputed.flags;
args: [][:0]const u8 = &[_][:0]u8{},
pub fn parse(self: *Self, args: [][:0]const u8) !void {
self.args = args;
while (try self.parseFlag()) {}
}
fn parseFlag(self: *Self) !bool {
if (self.args.len == 0) return false;
const args = self.args;
const str = args[0];
// Check if value is valid flag
if (str.len < 2 or str[0] != '-') return false;
var minuses: u8 = 1;
if (str[1] == '-') {
minuses += 1;
if (str.len == 2) {
self.args = self.args[1..];
return error.InvalidFlag;
}
}
var name = str[minuses..];
if (name.len == 0 or name[0] == '-' or name[0] == '=') {
return error.BadFlagSyntax;
}
// Have a valid flag
self.args = self.args[1..];
// Check if flag has value
var value: ?[]const u8 = null;
var equal_index: u32 = 1;
for (name[equal_index..]) |char| {
if (char == '=') {
name = name[0..equal_index :0];
value = name[equal_index + 1 ..];
}
equal_index += 1;
}
var flag = self.getFlagPtr(name) orelse {
log.err("Unknown flag provided: -{s}", .{name});
return error.UnknownFlag;
};
if (flag.default_value == .boolean and value == null) {
value = "true";
} else {
if (value == null and self.args.len > 0) {
value = self.args[0];
self.args = self.args[1..];
}
if (value == null) {
log.err("Flag -{s} requires a value", .{name});
return error.NeedFlagValue;
}
}
flag.input_value = value;
return true;
}
fn getFlagPtr(_: Self, name: []const u8) ?*Flag {
for (flags) |*flag| {
if (mem.eql(u8, name, flag.name)) return flag;
}
return null;
}
pub fn getFlag(_: Self, name: []const u8) ?Flag {
for (flags) |flag| {
if (mem.eql(u8, name, flag.name)) return flag;
}
return null;
}
};
}
pub fn newFlag(name: []const u8, default_value: anytype, description: []const u8) FlagOpt {
return .{
.name = name,
.description = description,
.ty = @TypeOf(default_value),
.default_value = @ptrCast(?*const anyopaque, &default_value),
};
}
pub fn usage(comptime cmds: anytype) !void {
const stderr = std.io.getStdErr();
const writer = stderr.writer();
try writer.writeAll("Usage: feedgaze <subcommand> [flags] [inputs]\n");
const decls = comptime std.meta.declarations(cmds);
// TODO: exmaple how to concat unknown length array at compile time
// https://github.com/Vexu/routez/blob/master/src/routez/router.zig#L18
const NameArr = std.BoundedArray([]const u8, decls.len);
const CmdArr = std.BoundedArray(struct { flags: []Flag, names: NameArr }, decls.len);
comptime var cmd_arr = try CmdArr.init(0);
inline for (decls) |decl| {
const cmd = @field(cmds, decl.name);
comptime var same_flags = false;
inline for (comptime cmd_arr.slice()) |*c| {
if (c.flags.ptr == &cmd.flags) {
same_flags = true;
comptime try c.names.append(decl.name);
}
}
if (!same_flags) {
comptime var new_flag = try cmd_arr.addOne();
new_flag.* = .{ .flags = &cmd.flags, .names = comptime try NameArr.init(0) };
comptime try new_flag.names.append(decl.name);
}
}
inline for (comptime cmd_arr.slice()) |c| {
const names = comptime c.names.constSlice();
const suffix = if (names.len == 1) "" else "s";
try writer.print("\nSubcommand{s}: {s}", .{ suffix, names[0] });
inline for (names[1..]) |name| {
try writer.print(", {s}", .{name});
}
try writer.writeAll("\n");
var max_flag_len = @as(usize, 0);
for (c.flags) |flag| {
max_flag_len = std.math.max(max_flag_len, flag.name.len);
}
for (c.flags) |*flag| {
try writer.print(" --{s}", .{flag.name});
var nr_of_spaces = max_flag_len - flag.name.len;
while (nr_of_spaces > 0) : (nr_of_spaces -= 1) {
try writer.writeAll(" ");
}
try writer.print(" {s}\n", .{flag.description});
}
}
} | src/main.zig |
const std = @import("std");
const Stream = std.net.Stream;
const Allocator = std.mem.Allocator;
const c = @cImport({
@cInclude("openssl/ssl.h");
@cInclude("openssl/err.h");
});
pub const SSLError = error {
InitializationError,
ConnectionError
};
pub const SSLReadError = error {
};
pub const SSLWriteError = error {
};
pub extern "c" var stderr: [*c]c.FILE;
fn print_errors() void {
c.ERR_print_errors_fp(stderr);
}
fn print_ssl_error(err: c_int) void {
std.debug.warn("detailled error: ", .{});
switch (err) {
c.SSL_ERROR_ZERO_RETURN => std.debug.warn("SSL_ERROR_ZERO_RETURN\n", .{}),
c.SSL_ERROR_SSL => std.debug.warn("SSL_ERROR_SSL\n", .{}),
c.SSL_ERROR_SYSCALL => std.debug.warn("SSL_ERROR_SYSCALL\n", .{}),
c.SSL_ERROR_WANT_READ => std.debug.warn("SSL_ERROR_WANT_READ\n", .{}),
c.SSL_ERROR_WANT_WRITE => std.debug.warn("SSL_ERROR_WANT_WRITE\n", .{}),
c.SSL_ERROR_WANT_CONNECT => std.debug.warn("SSL_ERROR_WANT_CONNECT\n", .{}),
c.SSL_ERROR_WANT_ACCEPT => std.debug.warn("SSL_ERROR_WANT_ACCEPT\n", .{}),
else => unreachable
}
}
pub fn init() SSLError!void {
//c.ERR_load_crypto_strings();
//c.OpenSSL_add_all_algorithms();
//c.OPENSSL_config(null);
if (c.OPENSSL_init_ssl(0, null) != 1) {
return error.InitializationError;
}
if (c.OPENSSL_init_crypto(c.OPENSSL_INIT_ADD_ALL_CIPHERS | c.OPENSSL_INIT_ADD_ALL_DIGESTS, null) != 1) {
return error.InitializationError;
}
}
pub fn deinit() void {
//c.CONF_modules_unload(1);
//c.EVP_cleanup();
//c.CRYPTO_cleanup_all_ex_data();
//c.ERR_remove_state();
//c.ERR_free_strings();
}
pub const SSLConnection = struct {
ctx: *c.SSL_CTX,
ssl: *c.SSL,
stream: ?Stream,
pub const Reader = std.io.Reader(*const SSLConnection, anyerror, read);
pub const Writer = std.io.Writer(*const SSLConnection, anyerror, write);
pub fn init(allocator: *Allocator, stream: Stream, host: []const u8, secure: bool) !SSLConnection {
var ctx: *c.SSL_CTX = undefined;
var ssl: *c.SSL = undefined;
if (secure) {
const method = c.TLS_client_method();
ctx = c.SSL_CTX_new(method) orelse return error.ConnectionError;
errdefer c.SSL_CTX_free(ctx);
_ = c.SSL_CTX_set_mode(ctx, c.SSL_MODE_AUTO_RETRY | c.SSL_MODE_ENABLE_PARTIAL_WRITE);
ssl = c.SSL_new(ctx) orelse return error.ConnectionError;
var buf = try allocator.dupeZ(u8, host);
defer allocator.free(buf);
if (c.SSL_ctrl(ssl, c.SSL_CTRL_SET_TLSEXT_HOSTNAME, c.TLSEXT_NAMETYPE_host_name, buf.ptr) != 1) {
print_errors();
return error.ConnectionError;
}
if (c.SSL_set_fd(ssl, stream.handle) != 1) {
print_errors();
return error.ConnectionError;
}
accept: while (true) {
const result = c.SSL_connect(ssl);
if (result != 1) {
if (result < 0) {
const err = c.SSL_get_error(ssl, result);
if (err == c.SSL_ERROR_WANT_READ) {
var pollfds = [1]std.os.pollfd { .{ .fd=stream.handle, .events=std.os.POLLIN, .revents=0 } };
_ = try std.os.poll(&pollfds, 1000);
continue :accept;
}
print_ssl_error(err);
}
print_errors();
return SSLError.ConnectionError;
}
break;
}
}
return SSLConnection {
.ctx = ctx,
.ssl = ssl,
.stream = stream
};
}
pub fn reader(self: *const SSLConnection) Reader {
return .{
.context = self
};
}
pub fn writer(self: *const SSLConnection) Writer {
return .{
.context = self
};
}
pub fn read(self: *const SSLConnection, data: []u8) anyerror!usize {
var readed: usize = undefined;
const result = c.SSL_read_ex(self.ssl, data.ptr, data.len, &readed);
if (result == 1) {
return readed;
} else {
const err = c.SSL_get_error(self.ssl, result);
if (err == c.SSL_ERROR_ZERO_RETURN or err == c.SSL_ERROR_SYSCALL) { // connection closed
return 0;
} else if (err == c.SSL_ERROR_WANT_READ or err == c.SSL_ERROR_WANT_WRITE) {
var pollfds = [1]std.os.pollfd { .{ .fd=self.stream.?.handle, .events=std.os.POLLIN, .revents=0 } };
_ = try std.os.poll(&pollfds, 1000);
return try self.read(data);
}
print_ssl_error(err);
return SSLError.ConnectionError;
}
return 0;
}
pub fn write(self: *const SSLConnection, data: []const u8) anyerror!usize {
var written: usize = undefined;
const result = c.SSL_write_ex(self.ssl, data.ptr, data.len, &written);
if (result == 0) {
const err = c.SSL_get_error(self.ssl, result);
if (err == c.SSL_ERROR_WANT_READ or err == c.SSL_ERROR_WANT_WRITE) {
var pollfds = [1]std.os.pollfd { .{ .fd=self.stream.?.handle, .events=std.os.POLLIN, .revents=0 } };
_ = try std.os.poll(&pollfds, 1000);
return try self.write(data);
}
print_ssl_error(err);
return SSLError.ConnectionError;
}
return @intCast(usize, written);
}
pub fn deinit(self: *const SSLConnection) void {
if (self.stream == null) c.SSL_CTX_free(self.ctx);
}
}; | openssl/ssl.zig |
const ImageReader = zigimg.ImageReader;
const ImageSeekStream = zigimg.ImageSeekStream;
const PixelFormat = zigimg.PixelFormat;
const assert = std.debug.assert;
const color = zigimg.color;
const errors = zigimg.errors;
const png = zigimg.png;
const std = @import("std");
const testing = std.testing;
const zigimg = @import("zigimg");
const helpers = @import("../helpers.zig");
test "Should error on non PNG images" {
const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/bmp/simple_v4.bmp");
defer file.close();
var stream_source = std.io.StreamSource{ .file = file };
var png_file = png.PNG.init(helpers.zigimg_test_allocator);
defer png_file.deinit();
var pixelsOpt: ?color.ColorStorage = null;
const invalidFile = png_file.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt);
defer {
if (pixelsOpt) |pixels| {
pixels.deinit(helpers.zigimg_test_allocator);
}
}
try helpers.expectError(invalidFile, errors.ImageError.InvalidMagicHeader);
}
test "Read PNG header properly" {
const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/png/basn0g01.png");
defer file.close();
var stream_source = std.io.StreamSource{ .file = file };
var png_file = png.PNG.init(helpers.zigimg_test_allocator);
defer png_file.deinit();
var pixelsOpt: ?color.ColorStorage = null;
try png_file.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt);
defer {
if (pixelsOpt) |pixels| {
pixels.deinit(helpers.zigimg_test_allocator);
}
}
try helpers.expectEq(png_file.header.width, 32);
try helpers.expectEq(png_file.header.height, 32);
try helpers.expectEq(png_file.header.bit_depth, 1);
try testing.expect(png_file.header.color_type == .Grayscale);
try helpers.expectEq(png_file.header.compression_method, 0);
try helpers.expectEq(png_file.header.filter_method, 0);
try testing.expect(png_file.header.interlace_method == .Standard);
try testing.expect(pixelsOpt != null);
if (pixelsOpt) |pixels| {
try testing.expect(pixels == .Grayscale1);
}
}
test "Read gAMA chunk properly" {
const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/png/basn0g01.png");
defer file.close();
var stream_source = std.io.StreamSource{ .file = file };
var png_file = png.PNG.init(helpers.zigimg_test_allocator);
defer png_file.deinit();
var pixelsOpt: ?color.ColorStorage = null;
try png_file.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt);
defer {
if (pixelsOpt) |pixels| {
pixels.deinit(helpers.zigimg_test_allocator);
}
}
const gammaChunkOpt = png_file.findFirstChunk("gAMA");
try testing.expect(gammaChunkOpt != null);
if (gammaChunkOpt) |gammaChunk| {
try helpers.expectEq(gammaChunk.gAMA.toGammaExponent(), 1.0);
}
}
test "Png Suite" {
_ = @import("png_basn_test.zig");
_ = @import("png_basi_test.zig");
_ = @import("png_odd_sizes_test.zig");
_ = @import("png_bkgd_test.zig");
}
test "Misc tests" {
_ = @import("png_misc_test.zig");
} | tests/formats/png_test.zig |
const std = @import("std");
const c = @import("internal/c.zig");
const bitjuggle = @import("internal/bitjuggle.zig");
const internal = @import("internal/internal.zig");
const log = std.log.scoped(.git);
const git = @import("git.zig");
pub const Worktree = opaque {
pub fn deinit(self: *Worktree) void {
log.debug("Worktree.deinit called", .{});
c.git_worktree_free(@ptrCast(*c.git_worktree, self));
log.debug("worktree freed successfully", .{});
}
/// Check if worktree is valid
///
/// A valid worktree requires both the git data structures inside the linked parent repository and the linked working
/// copy to be present.
pub fn valid(self: *const Worktree) !void {
log.debug("Worktree.valid called", .{});
try internal.wrapCall("git_worktree_validate", .{
@ptrCast(*const c.git_worktree, self),
});
log.debug("worktree is valid", .{});
}
/// Lock worktree if not already locked
///
/// Lock a worktree, optionally specifying a reason why the linked
/// working tree is being locked.
///
/// ## Parameters
/// * `reason` - Reason why the working tree is being locked
pub fn lock(self: *Worktree, reason: ?[:0]const u8) !void {
log.debug("Worktree.lock called", .{});
const c_reason: [*c]const u8 = if (reason) |s| s.ptr else null;
internal.wrapCall("git_worktree_lock", .{
@ptrCast(*c.git_worktree, self),
c_reason,
}) catch |err| {
if (err == error.Locked) {
log.err("worktree is already locked", .{});
}
return err;
};
log.debug("worktree locked", .{});
}
/// Unlock a locked worktree
///
/// Returns `true` if the worktree was no locked
pub fn unlock(self: *Worktree) !bool {
log.debug("Worktree.unlock called", .{});
const not_locked = (try internal.wrapCallWithReturn("git_worktree_unlock", .{@ptrCast(*c.git_worktree, self)})) != 0;
if (not_locked) {
log.debug("worktree was not locked", .{});
} else {
log.debug("worktree unlocked", .{});
}
return not_locked;
}
/// Check if worktree is locked
//
/// A worktree may be locked if the linked working tree is stored on a portable device which is not available.
///
/// Returns `null` if the worktree is *not* locked, returns the reason for the lock if it is locked.
pub fn is_locked(self: *const Worktree) !?git.Buf {
log.debug("Worktree.is_locked called", .{});
var ret: git.Buf = .{};
const locked = (try internal.wrapCallWithReturn("git_worktree_is_locked", .{
@ptrCast(*c.git_buf, &ret),
@ptrCast(*const c.git_worktree, self),
})) != 0;
if (locked) {
log.debug("worktree is locked, reason: {s}", .{ret.toSlice()});
return ret;
}
log.debug("worktree is not locked", .{});
return null;
}
/// Retrieve the name of the worktree
///
/// The slice returned is valid for the lifetime of the `Worktree`
pub fn name(self: *Worktree) ![:0]const u8 {
log.debug("Worktree.name called", .{});
const ptr = c.git_worktree_name(@ptrCast(*c.git_worktree, self));
const slice = std.mem.sliceTo(ptr, 0);
log.debug("worktree name: {s}", .{slice});
return slice;
}
/// Retrieve the path of the worktree
///
/// The slice returned is valid for the lifetime of the `Worktree`
pub fn path(self: *Worktree) ![:0]const u8 {
log.debug("Worktree.path called", .{});
const ptr = c.git_worktree_path(@ptrCast(*c.git_worktree, self));
const slice = std.mem.sliceTo(ptr, 0);
log.debug("worktree path: {s}", .{slice});
return slice;
}
pub fn repositoryOpen(self: *Worktree) !*git.Repository {
log.debug("Worktree.repositoryOpen called", .{});
var repo: *git.Repository = undefined;
try internal.wrapCall("git_repository_open_from_worktree", .{
@ptrCast(*?*c.git_repository, &repo),
@ptrCast(*c.git_worktree, self),
});
log.debug("repository opened successfully", .{});
return repo;
}
pub const PruneOptions = packed struct {
/// Prune working tree even if working tree is valid
valid: bool = false,
/// Prune working tree even if it is locked
locked: bool = false,
/// Prune checked out working tree
working_tree: bool = false,
z_padding: u29 = 0,
pub fn makeCOptionsObject(self: PruneOptions) c.git_worktree_prune_options {
return .{
.version = c.GIT_WORKTREE_PRUNE_OPTIONS_VERSION,
.flags = @bitCast(u32, self),
};
}
pub fn format(
value: PruneOptions,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = fmt;
return internal.formatWithoutFields(
value,
options,
writer,
&.{"z_padding"},
);
}
test {
try std.testing.expectEqual(@sizeOf(u32), @sizeOf(PruneOptions));
try std.testing.expectEqual(@bitSizeOf(u32), @bitSizeOf(PruneOptions));
}
comptime {
std.testing.refAllDecls(@This());
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// Is the worktree prunable with the given options?
///
/// A worktree is not prunable in the following scenarios:
///
/// - the worktree is linking to a valid on-disk worktree. The `valid` member will cause this check to be ignored.
/// - the worktree is locked. The `locked` flag will cause this check to be ignored.
///
/// If the worktree is not valid and not locked or if the above flags have been passed in, this function will return a
/// `true`
pub fn isPruneable(self: *Worktree, options: PruneOptions) !bool {
log.debug("Worktree.isPruneable called, options={}", .{options});
var c_options = options.makeCOptionsObject();
const ret = (try internal.wrapCallWithReturn("git_worktree_is_prunable", .{
@ptrCast(*c.git_worktree, self),
&c_options,
})) != 0;
log.debug("worktree is pruneable: {}", .{ret});
return ret;
}
/// Prune working tree
///
/// Prune the working tree, that is remove the git data structures on disk. The repository will only be pruned of
/// `Worktree.isPruneable` succeeds.
pub fn prune(self: *Worktree, options: PruneOptions) !void {
log.debug("Worktree.prune called, options={}", .{options});
var c_options = options.makeCOptionsObject();
try internal.wrapCall("git_worktree_prune", .{
@ptrCast(*c.git_worktree, self),
&c_options,
});
log.debug("successfully pruned worktree", .{});
}
comptime {
std.testing.refAllDecls(@This());
}
};
comptime {
std.testing.refAllDecls(@This());
} | src/worktree.zig |
pub const std = @import("std");
pub const enable = if (std.builtin.is_test) false else @import("build_options").enable_tracy;
extern fn ___tracy_emit_frame_mark_start(name: ?[*:0]const u8) void;
extern fn ___tracy_emit_frame_mark_end(name: ?[*:0]const u8) void;
//extern fn ___tracy_set_thread_name(name: ?[*:0]const u8) void;
extern fn ___tracy_emit_zone_begin_callstack(
srcloc: *const ___tracy_source_location_data,
depth: c_int,
active: c_int,
) ___tracy_c_zone_context;
extern fn ___tracy_alloc_srcloc(line: u32, source: ?[*:0]const u8, sourceSz: usize, function: ?[*:0]const u8, functionSz: usize) u64;
extern fn ___tracy_alloc_srcloc_name(line: u32, source: ?[*:0]const u8, sourceSz: usize, function: ?[*:0]const u8, functionSz: usize, name: ?[*:0]const u8, nameSz: usize) u64;
extern fn ___tracy_emit_zone_begin_alloc_callstack(srcloc: u64, depth: c_int, active: c_int) ___tracy_c_zone_context;
extern fn ___tracy_emit_zone_begin_alloc(srcloc: u64, active: c_int) ___tracy_c_zone_context;
extern fn ___tracy_emit_zone_end(ctx: ___tracy_c_zone_context) void;
pub const ___tracy_source_location_data = extern struct {
name: ?[*:0]const u8,
function: [*:0]const u8,
file: [*:0]const u8,
line: u32,
color: u32,
};
pub const ___tracy_c_zone_context = extern struct {
id: u32,
active: c_int,
pub fn end(self: ___tracy_c_zone_context) void {
___tracy_emit_zone_end(self);
}
};
pub const Ctx = if (enable) ___tracy_c_zone_context else struct {
pub fn end(self: Ctx) void {
_ = self;
}
};
pub inline fn trace(comptime src: std.builtin.SourceLocation) Ctx {
if (!enable) return .{};
const loc: ___tracy_source_location_data = .{
.name = null,
.function = src.fn_name.ptr,
.file = src.file.ptr,
.line = src.line,
.color = 0,
};
return ___tracy_emit_zone_begin_callstack(&loc, 1, 1);
}
const TraceOptions = struct { name: ?[:0]const u8 = null, color: u32 = 0, callstack: bool = false };
pub inline fn traceEx(comptime src: std.builtin.SourceLocation, comptime opt: TraceOptions) Ctx {
if (!enable) return .{};
const srcloc = if (opt.name) |name|
___tracy_alloc_srcloc_name(src.line, src.file.ptr, src.file.len, src.fn_name.ptr, src.fn_name.len, name.ptr, name.len)
else
___tracy_alloc_srcloc(src.line, src.file.ptr, src.file.len, src.fn_name.ptr, src.fn_name.len);
if (opt.callstack)
return ___tracy_emit_zone_begin_alloc_callstack(srcloc, 7, 1)
else
return ___tracy_emit_zone_begin_alloc(srcloc, 1);
}
pub const ___tracy_c_frame_context = extern struct {
name: ?[*:0]const u8,
pub fn end(self: ___tracy_c_frame_context) void {
___tracy_emit_frame_mark_end(self.name);
}
};
pub const FrameCtx = if (enable) ___tracy_c_frame_context else struct {
pub fn end(self: FrameCtx) void {
_ = self;
}
};
pub fn traceFrame(name: ?[*:0]const u8) FrameCtx {
if (!enable) return .{};
___tracy_emit_frame_mark_start(name);
return ___tracy_c_frame_context{ .name = name };
} | src/tracy.zig |
const builtin = @import("builtin");
const io = @import("std").io;
pub fn toMagicNumberNative(comptime magic: []const u8) u32 {
var result: u32 = 0;
inline for (magic) |character, index| {
result |= (@as(u32, character) << (index * 8));
}
return result;
}
pub fn toMagicNumberForeign(comptime magic: []const u8) u32 {
var result: u32 = 0;
inline for (magic) |character, index| {
result |= (@as(u32, character) << ((magic.len - 1 - index) * 8));
}
return result;
}
pub const toMagicNumberBig = switch (builtin.endian) {
builtin.Endian.Little => toMagicNumberForeign,
builtin.Endian.Big => toMagicNumberNative,
};
pub const toMagicNumberLittle = switch (builtin.endian) {
builtin.Endian.Little => toMagicNumberNative,
builtin.Endian.Big => toMagicNumberForeign,
};
pub fn readStructNative(inStream: *io.InStream(anyerror), comptime T: type) !T {
return try inStream.readStruct(T);
}
pub fn readStructForeign(inStream: *io.InStream(anyerror), comptime T: type) !T {
comptime assert(@typeInfo(T).Struct.layout != builtin.TypeInfo.ContainerLayout.Auto);
var result: T = undefined;
inline while (field_i < @memberCount(T)) : (field_i += 1) {
const currentType = @TypeOf(@field(result, @memberName(T, field_i)));
switch (@typeInfo(currentType)) {
.ComptimeInt, .Int => {
@field(result, @memberName(T, field_i)) = try inStream.readIntForeign(currentType);
},
.Struct => {
@field(result, @memberName(T, field_i)) = try readStructForeign(inStream, currentType);
},
.Enum => {
@field(result, @memberName(T, field_i)) = try inStream.readEnum(currentType, switch (builtin.endian) {
builtin.Endian.Little => builtin.Endian.Big,
builtin.Endian.Big => builtin.Endian.Little,
});
},
}
}
return result;
}
pub const readStructLittle = switch (builtin.endian) {
builtin.Endian.Little => readStructNative,
builtin.Endian.Big => readStructForeign,
};
pub const readStructBig = switch (builtin.endian) {
builtin.Endian.Little => readStructForeign,
builtin.Endian.Big => readStructNative,
}; | src/utils.zig |
const std = @import("std");
const warn = std.debug.warn;
const Config = @import("config.zig").Config;
const c = @import("c.zig");
const msg = @import("message.zig");
const strtok = msg.strtok;
pub const CachedJValue = struct {
path: []const u8,
// value: ?[]const u8 = null,
value: ?std.json.Value = null,
};
// TODO: replace with hash map
pub const JsonKV = struct {
key: std.json.Value,
value: ?std.json.Value = null,
};
pub const Request = struct {
type: Type,
url: [:0]const u8,
headers: [][:0]const u8,
cached: std.StringHashMap(CachedJValue),
requires: ?std.StringHashMap(JsonKV),
fetched_at: ?c.c.tm = null,
pub const Type = enum(u2) {
GET,
PUT,
POST,
};
pub fn deinit(self: Request) void {
if (self.requires) |rqs| rqs.deinit();
self.cached.deinit();
}
// call fetch on all requires then do macro replacements
// ex: require -> request
// get_stream.requires.get_users.userid -> get_users.cached.userid.value
// TODO: use fetched_at to decide wether to fetch again
pub fn fetch(self: *Request, requests: std.StringHashMap(Request)) anyerror!void {
if (self.requires) |*requires| {
var ritr = requires.iterator();
while (ritr.next()) |requirekv| {
if (requests.get(requirekv.key)) |requestkv| {
try requestkv.value.fetch(requests);
const cachedkv = requestkv.value.cached.get(requirekv.value.key.String) orelse return error.JsonRequireNotCached;
// warn("cachedkv {}\n", .{cachedkv});
requirekv.value.value = cachedkv.value.value;
}
}
// check for ${} macro replacements in url and headers
// TODO: post data replacements
try replaceText(std.heap.c_allocator, &self.url, requires);
for (self.headers) |*hdr| try replaceText(std.heap.c_allocator, hdr, requires);
}
switch (self.type) {
.GET => {
var tree = try c.curl_get(self.url, self.headers);
// warn("{}\n", .{tree.root.dump()});
defer tree.deinit();
var itr = self.cached.iterator();
while (itr.next()) |kv| {
const path = kv.value.path;
const js_val = parseJsonPath(tree, path) catch |e| {
warn("request '{}' unable to parse json path '{}'. Error: {}\n", .{ self.url, path, e });
continue;
};
kv.value.value = js_val;
switch (js_val) {
.Object => self.fetched_at = c.get_time().*,
else => {},
}
}
},
else => return error.NotImplemented,
}
}
// look through cached, parsing and resolving the path as we go
// ex: users[0]._id, a.b.c[10].d
// resolve by visiting json structure
fn parseJsonPath(tree: std.json.ValueTree, path: []const u8) !std.json.Value {
var len: usize = 0;
var json_value = tree.root;
while (true) {
switch (json_value) {
.Object => if (msg.strtoks(path[len..], &[_]?u8{ '.', null })) |path_part| {
len += path_part.len + 1;
// array
if (strtok(path_part, '[')) |arr_name| {
if (strtok(path_part[arr_name.len + 1 ..], ']')) |arr_idx| {
const idx = try std.fmt.parseInt(usize, arr_idx, 10);
const obj = json_value.Object.get(arr_name) orelse return error.JsonPathNotFound;
switch (obj.value) {
.Array => {
if (idx >= obj.value.Array.len) return error.InvalidJsonArrayIndex;
json_value = obj.value.Array.at(idx);
continue;
},
else => return error.JsonPathNotFound,
}
}
} else { // object
const obj = json_value.Object.get(path_part) orelse return error.JsonPathNotFound;
json_value = obj.value;
}
} else {
const obj = json_value.Object.get(path[len..]) orelse return error.JsonPathNotFound;
return obj.value;
},
else => return json_value,
}
}
}
fn print(self: Request) void {
warn("\ntype {} url {} fetched_at {}\nheaders\n", .{ self.type, self.url, self.fetched_at });
for (self.headers) |h| warn(" {}\n", .{h});
if (self.cached) |ts| {
warn("cached\n", .{});
var titr = ts.iterator();
while (titr.next()) |tkv| warn(" {} {}\n", .{ tkv.key, tkv.value });
}
if (self.requires) |ps| {
warn("requires\n", .{});
var titr = ps.iterator();
while (titr.next()) |tkv| warn(" {} {}\n", .{ tkv.key, tkv.value });
}
}
};
test "parseJsonPath" {
const assert = std.debug.assert;
// fn parseJsonPath(self: *Request, tree: std.json.ValueTree, path: []const u8, kv: *std.StringHashMap(CachedJValue).KV) !void {
var parser = std.json.Parser.init(std.heap.c_allocator, false);
const json =
\\ {"a": {"b": [{"c": 42}, {"d": 43}]}, "a2": [0, 11, 22]}
;
var tree = try parser.parse(json);
const jc = try Request.parseJsonPath(tree, "a.b[0].c");
// warn("jc {}\n", .{jc});
assert(jc.Integer == 42);
const jd = try Request.parseJsonPath(tree, "a.b[1].d");
assert(jd.Integer == 43);
std.testing.expectError(error.JsonPathNotFound, Request.parseJsonPath(tree, "a.c"));
std.testing.expectError(error.InvalidJsonArrayIndex, Request.parseJsonPath(tree, "a.b[2]"));
const ja22 = try Request.parseJsonPath(tree, "a2[2]");
assert(ja22.Integer == 22);
}
/// load from json file which defines the api calls
pub fn initRequests(a: *std.mem.Allocator, config: Config) !std.StringHashMap(Request) {
var reqs = std.StringHashMap(Request).init(a);
errdefer reqs.deinit();
const f = try std.fs.File.openRead(config.api_config_file orelse return error.MissingApiConfigFile);
defer f.close();
const stream = &f.inStream().stream;
var p = std.json.Parser.init(a, false);
defer p.deinit();
// @alloc
var tree = try p.parse(try stream.readAllAlloc(a, 1024 * 1024));
defer tree.deinit();
var itr = tree.root.Object.iterator();
while (itr.next()) |kv| {
var req = kv.value;
var urlkv = req.Object.get("url") orelse return error.InvalidJsonMissingUrl;
var url = (try std.mem.dupe(a, u8, urlkv.value.String))[0..:0];
try replaceText(a, &url, config);
const headerskv = req.Object.get("headers");
const headers = if (headerskv) |hkv| (try a.alloc([:0]const u8, hkv.value.Array.len)) else &[_][:0]const u8{};
if (headerskv) |hs| {
for (hs.value.Array.toSliceConst()) |hdr, i| {
headers[i] = (try std.mem.dupe(a, u8, hdr.String))[0..:0];
try replaceText(a, &headers[i], config);
}
}
const _cached = req.Object.get("cached") orelse return error.InvalidJsonMissingCached;
var cached = _cached.value.Object;
var cmap = std.StringHashMap(CachedJValue).init(a);
var citr = cached.iterator();
while (citr.next()) |ckv| _ = try cmap.put(ckv.key, CachedJValue{ .path = ckv.value.String });
const requires_opt = req.Object.get("requires");
var rmap = if (requires_opt) |_requires| blk: {
const requires = _requires.value.Object;
var _rmap = std.StringHashMap(JsonKV).init(a);
var ritr = requires.iterator();
while (ritr.next()) |rkv| _ = try _rmap.put(rkv.key, .{ .key = rkv.value });
break :blk _rmap;
} else null;
var buf: [20]u8 = undefined;
const _reqtype = req.Object.get("type") orelse return error.InvalidJsonMissingType;
var reqtype = _reqtype.value.String;
for (reqtype) |ch, chi| buf[chi] = std.ascii.toUpper(ch);
reqtype = buf[0..reqtype.len];
const reqtype_enum = std.meta.stringToEnum(Request.Type, reqtype) orelse return error.InvalidJsonUnsupportedType;
_ = try reqs.put(kv.key, Request{ .type = reqtype_enum, .url = url, .headers = headers, .cached = cmap, .requires = rmap });
}
return reqs;
}
pub fn printRequests(reqs: std.StringHashMap(Request)) void {
var itr = reqs.iterator();
while (itr.next()) |kv| {
warn("\n{}", .{kv.key});
kv.value.print();
}
}
// insert value at text_field[starti..endi+1]
// reassigns text_field and frees old memory
fn insertText(a: *std.mem.Allocator, text_field: *[]const u8, starti: usize, endi: usize, value: []const u8) !void {
var ptr = text_field.*;
text_field.* = try std.mem.join(a, "", &[_][]const u8{
text_field.*[0..starti],
value,
text_field.*[starti + endi + 1 ..],
// "\x00",
});
a.free(ptr);
}
/// provider must be either a Config or StringHashMap()
pub fn replaceText(a: *std.mem.Allocator, text_field: *[]const u8, provider: var) !void {
// look for ${field} in strings and replace with Config.field or
// if called with a map, search provider for JsonKV.key == field and replace with JsonKV.value
// TODO: support replacing multiple occurrences of field
if (std.mem.indexOf(u8, text_field.*, "${")) |starti| {
// warn("text_field.* {}\n", .{text_field.*});
if (std.mem.indexOf(u8, text_field.*[starti..], "}")) |endi| {
const key = text_field.*[starti + 2 .. starti + endi];
if (@TypeOf(provider) == Config) {
inline for (std.meta.fields(@TypeOf(provider))) |field| {
if (std.mem.eql(u8, field.name, key)) {
const _value = @field(provider, field.name);
// support optional Config fields
const ti = @typeInfo(@TypeOf(_value));
switch (ti) {
.Optional => if (_value) |value|
try insertText(a, text_field, starti, endi, value),
else => try insertText(a, text_field, starti, endi, _value),
}
}
}
} else { // hash map
var ritr = provider.iterator();
while (ritr.next()) |requirekv| {
if (!std.mem.eql(u8, requirekv.value.key.String, key)) continue;
const value = requirekv.value.value orelse continue;
try insertText(a, text_field, starti, endi, value.String);
}
}
}
}
}
test "replaceText" {
const a = std.heap.c_allocator;
var field = try std.mem.dupe(a, u8, "a ${channel} b");
const config = Config{ .channel = "#channel_name", .server = "", .port = "", .nickname = "" };
try replaceText(a, &field, config);
const expected = "a #channel_name b";
std.testing.expectEqualSlices(u8, field, expected);
} | src/api.zig |
const std = @import("std");
const unicode = std.unicode;
const mem = std.mem;
const warn = std.debug.warn;
pub const List = std.ArrayList(Value);
const Value = union(enum) {
Null,
Bool: bool,
Float: float64,
Int: int64,
String: []const u8,
Raw: []const u8,
List: List,
};
pub const Part = union(enum) {
Place: usize,
Raw: []const u8,
};
pub fn sanitizeSQL(allocator: *allocator, sql: []const u8, args: ...) ![]u8 {
var parts = std.ArrayList(Part).init(allocator);
defer parts.deiinit();
var buf = &try std.Buffer.init(allocator, "");
defer buf.deiinit();
try lexParts(&parts, sql);
for (parts.toList()) |part| {
switch (part) {
.Place => |idx| {
if (idx == 0) return error.ZeroIndexPlace;
const args_id = idx - 1;
if (args_id >= args.len) return error.InsufficiendArguments;
switch (args[args_id]) {
.Null => {
try buf.append("null");
},
.Bool => |ok| {
if (ok) {
try buf.append("true");
} else {
try buf.append("false");
}
},
.String => |s| {
try quoteString(buf, s);
},
.Raw => |raw| {
try quoteBytes(buf, raw);
},
}
},
.Raw => |raw| {
try out.append(raw);
},
}
}
return buf.toOwnedSlice();
}
const single_quote = "'";
pub fn quoteString(buf: *std.Buffer, s: []const u8) !void {
try buf.append(single_quote);
if (mem.indexOf(u8, s, "'")) |i| {
try buf.append(s[0..i]);
try buf.append("''");
for (s[i + 1 ..]) |c| {
if (c == single_quote[0]) {
try buf.append(single_quote);
}
try buf.appendByte(c);
}
} else {
try buf.append(s);
}
try buf.append(single_quote);
}
pub fn quoteBytes(buf: *std.Buffer, raw: []const u8) !void {
try buf.append(
\\'\x
);
var stream = &std.io.BufferOutStream.init(buf).stream;
try stream.print("{x}", raw);
try buf.append("'");
}
const apostrophe = '\'';
pub fn lexParts(ls: *std.ArrayList(Part), s: []const u8) !void {
var start: usize = 0;
var pos: usize = 0;
raw_state: while (pos < s.len) {
const n = (try nextRune(s, pos)) orelse break;
pos += n.width;
switch (n.r) {
'e', 'E' => {
const next = (try nextRune(s, pos)) orelse break;
if (next.r == apostrophe) {
pos += n.width;
while (true) {
const r = (try nextRune(s, pos)) orelse break :raw_state;
pos += r.width;
switch (r.r) {
'\\' => {
const x = (try nextRune(s, pos)) orelse break :raw_state;
pos += x.width;
},
apostrophe => {
const x = (try nextRune(s, pos)) orelse break :raw_state;
if (x.r != apostrophe) {
continue :raw_state;
}
pos += x.width;
},
else => {},
}
}
}
},
apostrophe => {
while (true) {
const next = (try nextRune(s, pos)) orelse break :raw_state;
pos += next.width;
if (next.r == apostrophe) {
const x = (try nextRune(s, pos)) orelse break :raw_state;
if (x.r != apostrophe) {
continue :raw_state;
}
pos += n.width;
}
}
},
'"' => {
while (true) {
const next = (try nextRune(s, pos)) orelse break :raw_state;
pos += next.width;
if (next.r == '"') {
const x = (try nextRune(s, pos)) orelse break :raw_state;
if (x.r != '"') {
continue :raw_state;
}
pos += x.width;
}
}
},
'$' => {
const next = (try nextRune(s, pos)) orelse break :raw_state;
if ('0' <= next.r and next.r <= '9') {
if (pos - start > 0) {
try ls.append(Part{ .Raw = s[start .. pos - next.width] });
}
start = pos;
var num: usize = 0;
while (true) {
const x = (try nextRune(s, pos)) orelse {
if (num > 0) {
try ls.append(Part{
.Place = num,
});
start = pos;
}
break :raw_state;
};
pos += x.width;
if ('0' <= x.r and x.r <= '9') {
num *= 10;
num += @intCast(usize, x.r - '0');
} else {
try ls.append(Part{
.Place = num,
});
pos -= x.width;
start = pos;
continue :raw_state;
}
}
}
},
else => {},
}
}
if (pos - start > 0) {
try ls.append(Part{ .Raw = s[start..pos] });
}
}
const Rune = struct {
r: u32,
width: usize,
};
fn nextRune(s: []const u8, pos: usize) !?Rune {
if (pos >= s.len) return null;
const n = unicode.utf8ByteSequenceLength(s[pos]) catch unreachable;
const r = try unicode.utf8Decode(s[pos .. pos + n]);
return Rune{
.r = r,
.width = try unicode.utf8CodepointSequenceLength(r),
};
} | src/db/pq/encoding.zig |
const ReferenceCounter = @import("../RefCount.zig").ReferenceCounter;
const wgi = @import("../WindowGraphicsInput/WindowGraphicsInput.zig");
const Tex2D = wgi.Texture2D;
const Asset = @import("../Assets/Assets.zig").Asset;
// Use the functions in the texture variable for uploading data, changing filtering, etc.
pub const Texture2D = struct {
// Reference counting in WGI texture object is ignored, only this reference counter is used
ref_count: ReferenceCounter = ReferenceCounter{},
texture: Tex2D,
asset: ?*Asset = null,
// Allocates gpu-side memory for a texture object
pub fn init() !Texture2D {
return Texture2D{ .texture = try Tex2D.init(true, Tex2D.MinFilter.Linear) };
}
pub fn loadFromAsset(asset: *Asset) !Texture2D {
if (asset.asset_type != Asset.AssetType.Texture and asset.asset_type != Asset.AssetType.RGB10A2Texture) {
return error.InvalidAssetType;
}
if (asset.state != Asset.AssetState.Ready) {
return error.InvalidAssetState;
}
asset.ref_count.inc();
errdefer asset.ref_count.dec();
var t = try Tex2D.init(false, wgi.MinFilter.Linear);
errdefer t.free();
if (asset.asset_type == Asset.AssetType.RGB10A2Texture) {
try t.upload(asset.texture_width.?, asset.texture_height.?, asset.texture_type.?, asset.rgb10a2_data.?);
} else {
try t.upload(asset.texture_width.?, asset.texture_height.?, asset.texture_type.?, asset.data.?);
}
return Texture2D{
.texture = t,
.asset = asset,
};
}
pub fn free(self: *Texture2D) void {
self.ref_count.deinit();
self.texture.free();
if (self.asset != null) {
self.asset.?.ref_count.dec();
self.asset = null;
}
}
pub fn freeIfUnused(self: *Texture2D) void {
if (self.asset != null and self.ref_count.n == 0) {
self.ref_count.deinit();
self.texture.free();
self.asset.?.ref_count.dec();
if (self.asset.?.ref_count.n == 0) {
self.asset.?.free(false);
}
self.asset = null;
}
}
}; | src/RTRenderEngine/Texture2D.zig |
const std = @import("std");
usingnamespace @import("template.zig");
// -------------
// --- Tests ---
// -------------
const t = std.testing;
const allocator = t.allocator;
fn t_expectEqual(actual: anytype, expected: @TypeOf(actual)) void {
t.expectEqual(expected, actual);
}
fn expectNode(node: Node, comptime node_type: NodeType, expected_text: comptime []const u8) void {
t.expect(node == node_type);
t.expectEqualStrings(expected_text, @field(node, @tagName(node_type)));
}
fn expectPrinted(expected: []const u8, tmpl: anytype, args: anytype) !void {
t.expectEqualStrings(expected, try tmpl.bufPrint(&print_buf, args));
const msg = try tmpl.allocPrint(t.allocator, args);
defer t.allocator.free(msg);
t.expectEqualStrings(expected, msg);
}
test "parser" {
const text = "aabbccdd";
var p = Parser{ .buf = text, .pos = 0 };
t.expectEqualStrings("aa", p.untilStr("bb"));
t.expectEqualStrings("bbccdd", p.buf[p.pos..]);
t.expectEqualStrings("bb", p.untilStr("cc"));
t.expectEqualStrings("ccdd", p.buf[p.pos..]);
t.expectEqualStrings("ccdd", p.untilStr("{{"));
}
test "text" {
{
const text = "";
const tmpl = Template(text, .{});
t_expectEqual(tmpl.tree.root.len, 0);
t.expectEqualStrings(text, try tmpl.bufPrint(&print_buf, .{}));
try expectPrinted(text, tmpl, .{});
}
{
const text = "hello";
const tmpl = Template(text, .{});
t_expectEqual(tmpl.tree.root.len, 1);
expectNode(tmpl.tree.root[0], .text, text);
t.expectEqualStrings(text, try tmpl.bufPrint(&print_buf, .{}));
try expectPrinted(text, tmpl, .{});
}
{
const text = "}{hello{}";
const tmpl = Template(text, .{});
t_expectEqual(tmpl.tree.root.len, 1);
expectNode(tmpl.tree.root[0], .text, text);
try expectPrinted(text, tmpl, .{});
}
}
test "escapes" {
const tmpl = Template("\\{\\{0\\}\\}", .{});
t_expectEqual(tmpl.tree.root.len, 1);
expectNode(tmpl.tree.root[0], .text, "{{0}}");
try expectPrinted("{{0}}", tmpl, .{});
}
test "variables" {
{
const text = "{{.name}}";
const tmpl = Template(text, .{});
t_expectEqual(tmpl.tree.root.len, 1);
// expectNode(tmpl.tree.root[0], .action, "name");
try expectPrinted("zero", tmpl, .{ .name = "zero" });
}
{
const text = "Hi {{.name}} at index #{{.index}}";
const tmpl = Template(text, .{});
t_expectEqual(tmpl.tree.root.len, 4);
expectNode(tmpl.tree.root[0], .text, "Hi ");
// expectNode(tmpl.tree.root[1], .action, "name");
t.expectEqualStrings("name", tmpl.tree.root[1].action.cmds[0].field);
expectNode(tmpl.tree.root[2], .text, " at index #");
t.expectEqualStrings("index", tmpl.tree.root[3].action.cmds[0].field);
try expectPrinted("Hi zero at index #000", tmpl, .{ .name = "zero", .index = "000" });
}
}
test "range" {
{
const text = "{{ range $i, $e := 1..2 }} a {{$i}}:{{$e}} b {{ end }} c";
const tmpl = Template(text, .{ .eval_branch_quota = 8000 });
t_expectEqual(tmpl.tree.root.len, 2);
t.expect(tmpl.tree.root[0] == .range);
t.expect(tmpl.tree.root[1] == .text);
// std.debug.print("tmpl {}\n", .{tmpl.tree.root});
t_expectEqual(tmpl.tree.root[0].range.pipeline.?.decls.len, 2);
t.expectEqualStrings(tmpl.tree.root[0].range.pipeline.?.decls[0], "$i");
t.expectEqualStrings(tmpl.tree.root[0].range.pipeline.?.decls[1], "$e");
t_expectEqual(tmpl.tree.root[0].range.pipeline.?.cmds[0].interval.start, 1);
t_expectEqual(tmpl.tree.root[0].range.pipeline.?.cmds[0].interval.end, 2);
t_expectEqual(tmpl.tree.root[0].range.list.?.len, 5);
try expectPrinted(" a 0:1 b a 1:2 b c", tmpl, .{});
}
{
const text =
\\{{ range $index := 0..1 }}level1 {{$index}}{{
\\ range $index2 := 0..0}} level2 {{$index}}{{$index2}}{{ end }} endlevel1 {{ end }}
;
const tmpl = Template(text, .{});
t_expectEqual(tmpl.tree.root.len, 1);
t.expect(tmpl.tree.root[0] == .range);
t_expectEqual(tmpl.tree.root[0].range.list.?.len, 8);
expectNode(tmpl.tree.root[0].range.list.?.root[0], .text, "level1 ");
// expectNode(tmpl.tree.root[0].range.list.?.root[1], .action, "$index");
t.expectEqualStrings("$index", tmpl.tree.root[0].range.list.?.root[1].action.cmds[0].variable);
t.expect(tmpl.tree.root[0].range.list.?.root[2] == .range);
t.expectEqualStrings("$index2", tmpl.tree.root[0].range.list.?.root[2].range.pipeline.?.decls[0]);
// expectNode(tmpl.tree.root[0].range.list.?.root[1], .action, "$index");
t_expectEqual(tmpl.tree.root[0].range.list.?.root[2].range.list.?.root.len, 3);
expectNode(tmpl.tree.root[0].range.list.?.root[2].range.list.?.root[0], .text, " level2 ");
t.expectEqualStrings("$index", tmpl.tree.root[0].range.list.?.root[2].range.list.?.root[1].action.cmds[0].variable);
t.expectEqualStrings("$index2", tmpl.tree.root[0].range.list.?.root[2].range.list.?.root[2].action.cmds[0].variable);
expectNode(tmpl.tree.root[0].range.list.?.root[3], .text, " endlevel1 ");
try expectPrinted("level1 0 level2 00 endlevel1 level1 1 level2 10 endlevel1 ", tmpl, .{});
}
}
// TODO convert to range
test "range2" {
{
const text =
\\{{ range $index, $item := .list }}
\\Print {{$item}} at {{$index}}{{ end }}
;
const tmpl = Template(text, .{ .eval_branch_quota = 4000 });
t_expectEqual(tmpl.tree.root.len, 1);
t.expect(tmpl.tree.root[0] == .range);
t.expectEqualStrings("$index", tmpl.tree.root[0].range.pipeline.?.decls[0]);
t.expectEqualStrings("$item", tmpl.tree.root[0].range.pipeline.?.decls[1]);
t.expectEqualStrings("list", tmpl.tree.root[0].range.pipeline.?.cmds[0].field);
t_expectEqual(tmpl.tree.root[0].range.list.?.root.len, 4);
expectNode(tmpl.tree.root[0].range.list.?.root[0], .text, "\nPrint ");
t.expectEqualStrings("$item", tmpl.tree.root[0].range.list.?.root[1].action.cmds[0].variable);
t.expectEqualStrings("$index", tmpl.tree.root[0].range.list.?.root[3].action.cmds[0].variable);
expectNode(tmpl.tree.root[0].range.list.?.root[2], .text, " at ");
const list = [_]u8{ 84, 168 };
try expectPrinted("\nPrint 84 at 0\nPrint 168 at 1", tmpl, .{ .list = list });
}
}
test "scopes" {
const text = "{{ range $i := 0..1}}{{ range $i := 0..1}}{{end}}{{end}}";
const tmpl = Template(text, .{ .eval_branch_quota = 4000 });
t.expectError(error.DuplicateKey, tmpl.bufPrint(&print_buf, .{}));
}
test "mixed scope types" { // no for_each capture index
const text = "{{ range $j := 0..0 }}{{ range $i := .list }}{{$i}} - {{$j}}, {{ end }}{{ end }}";
const tmpl = Template(text, .{ .eval_branch_quota = 4000 });
t_expectEqual(tmpl.tree.root.len, 1);
const list = [_]u128{ 1, 2 };
try expectPrinted("1 - 0, 2 - 0, ", tmpl, .{ .list = list });
}
test "if" {
{
const text = "{{if .cond}}a{{end}}";
const tmpl = Template(text, .{});
t.expect(tmpl.tree.root[0] == .if_);
t.expectEqualStrings("cond", tmpl.tree.root[0].if_.pipeline.?.cmds[0].field);
t_expectEqual(tmpl.tree.root[0].if_.list.?.root.len, 1);
try expectPrinted("a", tmpl, .{ .cond = "foo" });
try expectPrinted("", tmpl, .{ .cond = "" });
}
{
const text = "{{if .cond}}a{{else}}b{{end}}";
const tmpl = Template(text, .{});
t.expect(tmpl.tree.root[0] == .if_);
t.expectEqualStrings("cond", tmpl.tree.root[0].if_.pipeline.?.cmds[0].field);
t_expectEqual(tmpl.tree.root[0].if_.list.?.len, 1);
t.expectEqual(tmpl.tree.root[0].if_.else_list.?.len, 1);
t.expect(tmpl.tree.root[0].if_.else_list.?.root[0] == .text);
try expectPrinted("a", tmpl, .{ .cond = "foo" });
try expectPrinted("b", tmpl, .{ .cond = "" });
}
{
const text = "{{if .cond}}a{{else if .cond2}}b{{else}}c{{end}}";
const tmpl = Template(text, .{ .eval_branch_quota = 4000 });
t.expect(tmpl.tree.root[0] == .if_);
t.expectEqualStrings("cond", tmpl.tree.root[0].if_.pipeline.?.cmds[0].field);
t_expectEqual(tmpl.tree.root[0].if_.list.?.len, 1);
t.expectEqual(tmpl.tree.root[0].if_.else_list.?.len, 5);
t.expect(tmpl.tree.root[0].if_.else_list.?.root[0] == .if_);
t.expect(tmpl.tree.root[0].if_.else_list.?.root[0].if_.pipeline.?.cmds[0] == .field);
t.expect(tmpl.tree.root[0].if_.else_list.?.root[0].if_.list.?.root[0] == .text);
t.expect(tmpl.tree.root[0].if_.else_list.?.root[0].if_.else_list.?.root[0] == .text);
t.expectEqualStrings("c", tmpl.tree.root[0].if_.else_list.?.root[0].if_.else_list.?.root[0].text);
try expectPrinted("a", tmpl, .{ .cond = true });
try expectPrinted("a", tmpl, .{ .cond = [1]bool{false} });
try expectPrinted("b", tmpl, .{ .cond2 = true });
try expectPrinted("c", tmpl, .{ .cond = @as(?u8, null), .cond2 = [0]bool{} });
try expectPrinted("c", tmpl, .{ .cond = 0, .cond2 = 0.0 });
try expectPrinted("c", tmpl, .{ .cond = @as(u8, 0), .cond2 = @as(f32, 0.0) });
}
}
test "multiple templates" {
const template = @import("template.zig");
const T1 = Template("T1", .{ .name = "T1" });
const T2 = Template("T2", .{ .name = "T2" });
t.expectEqualStrings("T1", T1.options.name.?);
t.expectEqualStrings("T2", T2.options.name.?);
try expectPrinted("T1", T1, .{});
try expectPrinted("T2", T2, .{});
}
test "trim spaces" {
const tmpl = Template("{{23 -}} < {{- 45}}", .{});
try expectPrinted("23<45", tmpl, .{});
}
test "constants" {
const tmpl = Template("{{-23 -}} < {{- -45}}", .{});
try expectPrinted("-23<-45", tmpl, .{});
}
test "pipe" {
const tmpl = Template("{{.field1 | .field2}}", .{});
t.expect(tmpl.tree.root[0].action.cmds.len == 2);
t.expectEqualStrings("field1", tmpl.tree.root[0].action.cmds[0].field);
t.expectEqualStrings("field2", tmpl.tree.root[0].action.cmds[1].field);
try expectPrinted("value2", tmpl, .{ .field1 = .{ .field2 = "value2" } });
}
fn testfunc1() []const u8 {
return "func1value";
}
test "function" {
const tmpl = Template("{{func1}}", .{});
t.expect(tmpl.tree.root[0].action.cmds.len == 1);
t.expectEqualStrings("func1", tmpl.tree.root[0].action.cmds[0].func[0]);
// struct instance
try expectPrinted("func1value", tmpl, struct {
pub fn func1(self: @This()) []const u8 {
return "func1value";
}
}{});
}
test "pipe function" {
const tmpl = Template("{{.field1 | func1}}", .{});
t.expect(tmpl.tree.root[0].action.cmds.len == 2);
t.expectEqualStrings("field1", tmpl.tree.root[0].action.cmds[0].field);
t.expectEqualStrings("func1", tmpl.tree.root[0].action.cmds[1].func[0]);
// struct instance
try expectPrinted("func1value", tmpl, .{
.field1 = struct {
pub fn func1(self: @This()) []const u8 {
return "func1value";
}
}{},
});
// tuple with 'lambda' field
try expectPrinted("func1value", tmpl, .{
.field1 = .{
.func1 = struct {
pub fn func1() []const u8 {
return "func1value";
}
}.func1,
},
});
// tuple with external func field
try expectPrinted("func1value", tmpl, .{ .field1 = .{ .func1 = testfunc1 } });
}
// --------------------
// --- readme tests ---
// --------------------
var print_buf: [1000]u8 = undefined;
test "template variables" {
const Tmpl = @import("template.zig").Template;
const tmpl = Tmpl(
"Hello {{.world}}",
.{ .eval_branch_quota = 1000 }, // default value. same as .{}
);
// bufPrint
const message = try tmpl.bufPrint(&print_buf, .{ .world = "friends" });
std.testing.expectEqualStrings("Hello friends", message);
// allocPrint
const message2 = try tmpl.allocPrint(std.testing.allocator, .{ .world = "again friends" });
defer std.testing.allocator.free(message2);
std.testing.expectEqualStrings("Hello again friends", message2);
}
test "range over interval" {
const Tmpl = @import("template.zig").Template;
const tmpl = Tmpl(
"5 times: {{ range $index := 0..4 }}{{ $index }}{{ end }}",
.{ .eval_branch_quota = 4000 }, // slightly bigger quota required
);
// bufPrint
const message = try tmpl.bufPrint(&print_buf, .{});
std.testing.expectEqualStrings("5 times: 01234", message);
// allocPrint
const message2 = try tmpl.allocPrint(std.testing.allocator, .{});
defer std.testing.allocator.free(message2);
std.testing.expectEqualStrings("5 times: 01234", message2);
}
test "range over collection with index" {
const Tmpl = @import("template.zig").Template;
const tmpl = Tmpl(
"5 times: {{ range $index, $item := .items }}{{$item}}{{ $index }},{{ end }}",
.{ .eval_branch_quota = 6000 },
);
// bufPrint
const items = [_]u8{ 0, 1, 2, 3, 4 };
const message = try tmpl.bufPrint(&print_buf, .{ .items = items });
std.testing.expectEqualStrings("5 times: 00,11,22,33,44,", message);
// allocPrint
const message2 = try tmpl.allocPrint(std.testing.allocator, .{ .items = items });
defer std.testing.allocator.free(message2);
std.testing.expectEqualStrings("5 times: 00,11,22,33,44,", message2);
}
test "if - else if - else" {
const Tmpl = @import("template.zig").Template;
const tmpl = Tmpl("{{if .cond}}a{{else if .cond2}}b{{else}}c{{end}}", .{ .eval_branch_quota = 2000 });
std.testing.expectEqualStrings("a", try tmpl.bufPrint(&print_buf, .{ .cond = true }));
std.testing.expectEqualStrings("b", try tmpl.bufPrint(&print_buf, .{ .cond2 = 1 }));
std.testing.expectEqualStrings("c", try tmpl.bufPrint(&print_buf, .{}));
}
// --------------------
// - end readme tests -
// -------------------- | src/tests.zig |
const std = @import("std");
const tvg = @import("tinyvg.zig");
/// Renders a binary TinyVG into its text representation.
/// - `allocator` will be used for temporary allocations in the TVG parser.
/// - `tvg_buffer` provides a binary TinyVG file
/// - `writer` will receive the UTF-8 encoded SVG text.
pub fn renderBinary(allocator: std.mem.Allocator, tvg_buffer: []const u8, writer: anytype) !void {
var stream = std.io.fixedBufferStream(tvg_buffer);
var parser = try tvg.parse(allocator, stream.reader());
defer parser.deinit();
return try renderStream(&parser, writer);
}
/// Renders a TinyVG command stream into the TinyVG text representation.
/// - `parser` is a pointer to a `tvg.parsing.Parser(Reader)`
/// - `writer` will receive the UTF-8 encoded TinyVG text.
pub fn renderStream(parser: anytype, writer: anytype) !void {
try writer.print("(tvg {d}\n", .{parser.header.version});
try writer.print(" ({d} {d} {s} {s} {s})\n", .{
parser.header.width,
parser.header.height,
@tagName(parser.header.scale),
@tagName(parser.header.color_encoding),
@tagName(parser.header.coordinate_range),
});
try writer.writeAll(" (\n");
for (parser.color_table) |color| {
if (color.a != 1.0) {
try writer.print(" ({d:.3} {d:.3} {d:.3} {d:.3})\n", .{
color.r, color.g, color.b, color.a,
});
} else {
try writer.print(" ({d:.3} {d:.3} {d:.3})\n", .{
color.r, color.g, color.b,
});
}
}
try writer.writeAll(" )\n");
try writer.writeAll(" (\n");
while (try parser.next()) |command| {
try writer.print(" (\n {s}", .{std.meta.tagName(command)});
switch (command) {
.fill_rectangles => |data| {
try renderStyle("\n ", writer, data.style);
try renderRectangles("\n ", writer, data.rectangles);
},
.outline_fill_rectangles => |data| {
try renderStyle("\n ", writer, data.fill_style);
try renderStyle("\n ", writer, data.line_style);
try writer.print("\n {d}", .{data.line_width});
try renderRectangles("\n ", writer, data.rectangles);
},
.draw_lines => |data| {
try renderStyle("\n ", writer, data.style);
try writer.print("\n {d}", .{data.line_width});
try renderLines("\n ", writer, data.lines);
},
.draw_line_loop => |data| {
try renderStyle("\n ", writer, data.style);
try writer.print("\n {d}", .{data.line_width});
try renderPoints("\n ", writer, data.vertices);
},
.draw_line_strip => |data| {
try renderStyle("\n ", writer, data.style);
try writer.print("\n {d}", .{data.line_width});
try renderPoints("\n ", writer, data.vertices);
},
.fill_polygon => |data| {
try renderStyle("\n ", writer, data.style);
try renderPoints("\n ", writer, data.vertices);
},
.outline_fill_polygon => |data| {
try renderStyle("\n ", writer, data.fill_style);
try renderStyle("\n ", writer, data.line_style);
try writer.print("\n {d}", .{data.line_width});
try renderPoints("\n ", writer, data.vertices);
},
.draw_line_path => |data| {
try renderStyle("\n ", writer, data.style);
try writer.print("\n {d}", .{data.line_width});
try renderPath("\n ", writer, data.path);
},
.fill_path => |data| {
try renderStyle("\n ", writer, data.style);
try renderPath("\n ", writer, data.path);
},
.outline_fill_path => |data| {
try renderStyle("\n ", writer, data.fill_style);
try renderStyle("\n ", writer, data.line_style);
try writer.print("\n {d}", .{data.line_width});
try renderPath("\n ", writer, data.path);
},
}
try writer.writeAll("\n )\n");
}
try writer.writeAll(" )\n");
try writer.writeAll(")\n");
}
fn renderRectangles(line_prefix: []const u8, writer: anytype, rects: []const tvg.Rectangle) !void {
try writer.print("{s}(", .{line_prefix});
for (rects) |r| {
try writer.print("{s} ({d} {d} {d} {d})", .{
line_prefix, r.x, r.y, r.width, r.height,
});
}
try writer.print("{s})", .{line_prefix});
}
fn renderLines(line_prefix: []const u8, writer: anytype, lines: []const tvg.Line) !void {
try writer.print("{s}(", .{line_prefix});
for (lines) |l| {
try writer.print("{s} (({d} {d}) ({d} {d}))", .{
line_prefix, l.start.x, l.start.y, l.end.x, l.end.y,
});
}
try writer.print("{s})", .{line_prefix});
}
fn renderPoints(line_prefix: []const u8, writer: anytype, point: []const tvg.Point) !void {
try writer.print("{s}(", .{line_prefix});
for (point) |p| {
try writer.print("{s} ({d} {d})", .{
line_prefix, p.x, p.y,
});
}
try writer.print("{s})", .{line_prefix});
}
fn renderPath(line_prefix: []const u8, writer: anytype, path: tvg.Path) !void {
try writer.print("{s}(", .{line_prefix});
for (path.segments) |segment| {
try writer.print("{s} ({d} {d}){s} (", .{ line_prefix, segment.start.x, segment.start.y, line_prefix });
for (segment.commands) |node| {
try writer.print("{s} ", .{line_prefix});
try renderPathNode(writer, node);
}
try writer.print("{s} )", .{line_prefix});
}
try writer.print("{s})", .{line_prefix});
}
fn renderPathNode(writer: anytype, node: tvg.Path.Node) !void {
const LineWidth = struct {
lw: ?f32,
pub fn format(self: @This(), comptime fmt: []const u8, options: std.fmt.FormatOptions, writ: anytype) !void {
_ = fmt;
_ = options;
if (self.lw) |lw| {
try writ.print("{d}", .{lw});
} else {
try writ.writeAll("-");
}
}
fn init(lw: ?f32) @This() {
return @This(){ .lw = lw };
}
};
const initLW = LineWidth.init;
switch (node) {
.line => |line| try writer.print("(line {} {d} {d})", .{ initLW(line.line_width), line.data.x, line.data.y }),
.horiz => |horiz| try writer.print("(horiz {} {d})", .{ initLW(horiz.line_width), horiz.data }),
.vert => |vert| try writer.print("(vert {} {d})", .{ initLW(vert.line_width), vert.data }),
.bezier => |bezier| try writer.print("(bezier {} ({d} {d}) ({d} {d}) ({d} {d}))", .{
initLW(bezier.line_width),
bezier.data.c0.x,
bezier.data.c0.y,
bezier.data.c1.x,
bezier.data.c1.y,
bezier.data.p1.x,
bezier.data.p1.y,
}),
.quadratic_bezier => |bezier| try writer.print("(quadratic_bezier {} ({d} {d}) ({d} {d}))", .{
initLW(bezier.line_width),
bezier.data.c.x,
bezier.data.c.y,
bezier.data.p1.x,
bezier.data.p1.y,
}),
.arc_circle => |arc_circle| try writer.print("(arc_circle {} {d} {} {} ({d} {d}))", .{
initLW(arc_circle.line_width),
arc_circle.data.radius,
arc_circle.data.large_arc,
arc_circle.data.sweep,
arc_circle.data.target.x,
arc_circle.data.target.y,
}),
.arc_ellipse => |arc_ellipse| try writer.print("(arc_ellipse {} {d} {d} {d} {} {} ({d} {d}))", .{
initLW(arc_ellipse.line_width),
arc_ellipse.data.radius_x,
arc_ellipse.data.radius_y,
arc_ellipse.data.rotation,
arc_ellipse.data.large_arc,
arc_ellipse.data.sweep,
arc_ellipse.data.target.x,
arc_ellipse.data.target.y,
}),
.close => |close| try writer.print("(close {})", .{initLW(close.line_width)}),
// else => unreachable,
}
}
fn renderStyle(line_prefix: []const u8, writer: anytype, style: tvg.Style) !void {
switch (style) {
.flat => |color| try writer.print("{s}(flat {d})", .{ line_prefix, color }),
.linear, .radial => |grad| {
try writer.print("{s}({s} ({d} {d}) ({d} {d}) {d} {d} )", .{
line_prefix,
std.meta.tagName(style),
grad.point_0.x,
grad.point_0.y,
grad.point_1.x,
grad.point_1.y,
grad.color_0,
grad.color_1,
});
},
}
}
/// Parses the TinyVG text representation and renders a binary file.
/// - `allocator` is used for temporary allocations inside the parser.
/// - `source` contains the textual TinyVG file.
/// - `writer` receives the binary file in small portions.
pub fn parse(allocator: std.mem.Allocator, source: []const u8, writer: anytype) !void {
var builder = tvg.builder.create(writer);
const Builder = @TypeOf(builder);
const Parser = struct {
const Parser = @This();
const ptk = @import("ptk");
const TokenType = enum {
begin,
end,
space,
atom,
};
const Pattern = ptk.Pattern(TokenType);
const Tokenizer = ptk.Tokenizer(TokenType, &[_]Pattern{
Pattern.create(.space, ptk.matchers.whitespace),
Pattern.create(.begin, ptk.matchers.literal("(")),
Pattern.create(.end, ptk.matchers.literal(")")),
Pattern.create(.atom, matchAtom),
});
const Token = union(enum) {
begin,
end,
atom: []const u8,
pub fn format(self: @This(), comptime fmt: []const u8, options: std.fmt.FormatOptions, writ: anytype) !void {
_ = fmt;
_ = options;
switch (self) {
.begin => try writ.writeAll("'('"),
.end => try writ.writeAll("')'"),
.atom => |text| try writ.print("atom('{s}')", .{text}),
}
}
};
builder: *Builder,
tokenizer: Tokenizer,
allocator: std.mem.Allocator,
fn next(self: *Parser) !?Token {
while (true) {
const maybe_tok = try self.tokenizer.next();
if (maybe_tok) |tok| {
const token = switch (tok.type) {
.begin => .begin,
.end => .end,
.atom => Token{ .atom = tok.text },
.space => continue,
};
// std.debug.print("{}\n", .{token});
return token;
} else {
return null;
}
}
}
fn matchAtom(slice: []const u8) ?usize {
for (slice) |c, i| {
if (c == ')' or c == '(' or std.ascii.isSpace(c))
return i;
}
return slice.len;
}
fn expectAny(self: *Parser) !Token {
return (try self.next()) orelse return error.SyntaxError;
}
fn expectBegin(self: *Parser) !void {
const tok = (try self.next()) orelse return error.SyntaxError;
if (tok != .begin)
return error.SyntaxError;
}
fn expectEnd(self: *Parser) !void {
const tok = (try self.next()) orelse return error.SyntaxError;
if (tok != .end)
return error.SyntaxError;
}
fn expectAtom(self: *Parser) ![]const u8 {
const tok = (try self.next()) orelse return error.SyntaxError;
if (tok != .atom)
return unexpectedToken(tok);
return tok.atom;
}
fn unexpectedToken(tok: Token) error{SyntaxError} {
std.log.err("unexpected token: {}", .{tok});
return error.SyntaxError;
}
fn unexpectedText(str: []const u8) error{SyntaxError} {
std.log.err("unexpected text: '{s}'", .{str});
return error.SyntaxError;
}
fn parseNumber(self: *Parser) !f32 {
const text = try self.expectAtom();
return std.fmt.parseFloat(f32, text) catch return unexpectedText(text);
}
fn parseInteger(self: *Parser, comptime I: type) !I {
const text = try self.expectAtom();
return std.fmt.parseInt(I, text, 0) catch return unexpectedText(text);
}
fn parseEnum(self: *Parser, comptime E: type) !E {
const text = try self.expectAtom();
return std.meta.stringToEnum(E, text) orelse return unexpectedText(text);
}
fn parseBoolean(self: *Parser) !bool {
const text = try self.expectAtom();
return if (std.mem.eql(u8, text, "true"))
true
else if (std.mem.eql(u8, text, "false"))
false
else
return unexpectedText(text);
}
fn parseOptionalNumber(self: *Parser) !?f32 {
const text = try self.expectAtom();
if (std.mem.eql(u8, text, "-")) {
return null;
}
return std.fmt.parseFloat(f32, text) catch return unexpectedText(text);
}
fn parseHeader(self: *Parser) !tvg.parsing.Header {
try self.expectBegin();
const width = try self.parseInteger(u32);
const height = try self.parseInteger(u32);
const scale = try self.parseEnum(tvg.Scale);
const format = try self.parseEnum(tvg.ColorEncoding);
const range = try self.parseEnum(tvg.Range);
try self.expectEnd();
return tvg.parsing.Header{
.version = 1,
.width = width,
.height = height,
.scale = scale,
.color_encoding = format,
.coordinate_range = range,
};
}
fn parseColorTable(self: *Parser) ![]tvg.Color {
try self.expectBegin();
var colors = std.ArrayList(tvg.Color).init(self.allocator);
defer colors.deinit();
while (true) {
const item = try self.expectAny();
if (item == .atom)
return error.SyntaxError;
if (item == .end)
break;
const r = try self.parseNumber();
const g = try self.parseNumber();
const b = try self.parseNumber();
const maybe_a = try self.expectAny();
if (maybe_a == .begin)
return error.SyntaxError;
const a = if (maybe_a == .atom) blk: {
const a = try std.fmt.parseFloat(f32, maybe_a.atom);
try self.expectEnd();
break :blk a;
} else @as(f32, 1.0);
try colors.append(tvg.Color{ .r = r, .g = g, .b = b, .a = a });
}
return colors.toOwnedSlice();
}
fn parsePoint(self: *Parser) !tvg.Point {
try self.expectBegin();
const x = try self.parseNumber();
const y = try self.parseNumber();
try self.expectEnd();
return tvg.point(x, y);
}
fn parseStyle(self: *Parser) !tvg.Style {
try self.expectBegin();
const style_type = try self.parseEnum(tvg.StyleType);
const style = switch (style_type) {
.flat => tvg.Style{
.flat = try self.parseInteger(u32),
},
.linear => tvg.Style{
.linear = tvg.Gradient{
.point_0 = try self.parsePoint(),
.point_1 = try self.parsePoint(),
.color_0 = try self.parseInteger(u32),
.color_1 = try self.parseInteger(u32),
},
},
.radial => tvg.Style{
.radial = tvg.Gradient{
.point_0 = try self.parsePoint(),
.point_1 = try self.parsePoint(),
.color_0 = try self.parseInteger(u32),
.color_1 = try self.parseInteger(u32),
},
},
};
try self.expectEnd();
return style;
}
fn readRectangles(self: *Parser) !std.ArrayList(tvg.Rectangle) {
var items = std.ArrayList(tvg.Rectangle).init(self.allocator);
errdefer items.deinit();
try self.expectBegin();
while (true) {
const item = try self.expectAny();
if (item == .atom)
return error.SyntaxError;
if (item == .end)
break;
var x = try self.parseNumber();
var y = try self.parseNumber();
var width = try self.parseNumber();
var height = try self.parseNumber();
try self.expectEnd();
try items.append(tvg.rectangle(x, y, width, height));
}
return items;
}
fn readLines(self: *Parser) !std.ArrayList(tvg.Line) {
var items = std.ArrayList(tvg.Line).init(self.allocator);
errdefer items.deinit();
try self.expectBegin();
while (true) {
const item = try self.expectAny();
if (item == .atom)
return error.SyntaxError;
if (item == .end)
break;
var p0 = try self.parsePoint();
var p1 = try self.parsePoint();
try self.expectEnd();
try items.append(tvg.line(p0, p1));
}
return items;
}
fn readPoints(self: *Parser) !std.ArrayList(tvg.Point) {
var items = std.ArrayList(tvg.Point).init(self.allocator);
errdefer items.deinit();
try self.expectBegin();
while (true) {
const item = try self.expectAny();
if (item == .atom)
return error.SyntaxError;
if (item == .end)
break;
var x = try self.parseNumber();
var y = try self.parseNumber();
try self.expectEnd();
try items.append(tvg.point(x, y));
}
return items;
}
const Path = struct {
arena: std.heap.ArenaAllocator,
segments: []tvg.Path.Segment,
fn deinit(self: *Path) void {
self.arena.deinit();
self.* = undefined;
}
};
fn readPath(self: *Parser) !Path {
var arena = std.heap.ArenaAllocator.init(self.allocator);
errdefer arena.deinit();
var segments = std.ArrayList(tvg.Path.Segment).init(arena.allocator());
try self.expectBegin();
while (true) {
const head = try self.expectAny();
switch (head) {
.end => break,
.atom => return error.SyntaxError,
.begin => {
const segment = try segments.addOne();
const x = try self.parseNumber();
const y = try self.parseNumber();
segment.start = tvg.point(x, y);
try self.expectEnd();
try self.expectBegin();
var elements = std.ArrayList(tvg.Path.Node).init(arena.allocator());
while (true) {
const cmd_start = try self.expectAny();
switch (cmd_start) {
.end => break,
.atom => return error.SyntaxError,
.begin => {
const command = try self.parseEnum(tvg.Path.Type);
const node: tvg.Path.Node = switch (command) {
.line => tvg.Path.Node{ .line = .{ .line_width = try self.parseOptionalNumber(), .data = tvg.point(
try self.parseNumber(),
try self.parseNumber(),
) } },
.horiz => tvg.Path.Node{ .horiz = .{ .line_width = try self.parseOptionalNumber(), .data = try self.parseNumber() } },
.vert => tvg.Path.Node{ .vert = .{ .line_width = try self.parseOptionalNumber(), .data = try self.parseNumber() } },
.bezier => tvg.Path.Node{ .bezier = .{ .line_width = try self.parseOptionalNumber(), .data = .{
.c0 = try self.parsePoint(),
.c1 = try self.parsePoint(),
.p1 = try self.parsePoint(),
} } },
.quadratic_bezier => tvg.Path.Node{ .quadratic_bezier = .{ .line_width = try self.parseOptionalNumber(), .data = .{
.c = try self.parsePoint(),
.p1 = try self.parsePoint(),
} } },
.arc_circle => tvg.Path.Node{ .arc_circle = .{ .line_width = try self.parseOptionalNumber(), .data = .{
.radius = try self.parseNumber(),
.large_arc = try self.parseBoolean(),
.sweep = try self.parseBoolean(),
.target = try self.parsePoint(),
} } },
.arc_ellipse => tvg.Path.Node{
.arc_ellipse = .{
.line_width = try self.parseOptionalNumber(),
.data = .{
.radius_x = try self.parseNumber(),
.radius_y = try self.parseNumber(),
.rotation = try self.parseNumber(),
.large_arc = try self.parseBoolean(),
.sweep = try self.parseBoolean(),
.target = try self.parsePoint(),
},
},
},
.close => tvg.Path.Node{ .close = .{ .line_width = try self.parseOptionalNumber(), .data = {} } },
};
try self.expectEnd();
try elements.append(node);
},
}
}
segment.commands = elements.toOwnedSlice();
},
}
}
return Path{
.arena = arena,
.segments = segments.toOwnedSlice(),
};
}
fn parse(self: *Parser) !void {
try self.expectBegin();
if (!std.mem.eql(u8, "tvg", try self.expectAtom()))
return error.SyntaxError;
if ((try self.parseInteger(u8)) != 1)
return error.UnsupportedVersion;
var header = try self.parseHeader();
try self.builder.writeHeader(header.width, header.height, header.scale, header.color_encoding, header.coordinate_range);
var color_table = try self.parseColorTable();
defer self.allocator.free(color_table);
try self.builder.writeColorTable(color_table);
try self.expectBegin();
while (true) {
const start_token = try self.expectAny();
switch (start_token) {
.atom => return error.SyntaxError,
.end => break,
.begin => {
const command = try self.parseEnum(tvg.Command);
switch (command) {
.fill_polygon => {
var style = try self.parseStyle();
var points = try self.readPoints();
defer points.deinit();
try self.builder.writeFillPolygon(style, points.items);
},
.fill_rectangles => {
var style = try self.parseStyle();
var rects = try self.readRectangles();
defer rects.deinit();
try self.builder.writeFillRectangles(style, rects.items);
},
.fill_path => {
var style = try self.parseStyle();
var path = try self.readPath();
defer path.deinit();
try self.builder.writeFillPath(style, path.segments);
},
.draw_lines => {
var style = try self.parseStyle();
var line_width = try self.parseNumber();
var lines = try self.readLines();
defer lines.deinit();
try self.builder.writeDrawLines(style, line_width, lines.items);
},
.draw_line_loop => {
var style = try self.parseStyle();
var line_width = try self.parseNumber();
var points = try self.readPoints();
defer points.deinit();
try self.builder.writeDrawLineLoop(style, line_width, points.items);
},
.draw_line_strip => {
var style = try self.parseStyle();
var line_width = try self.parseNumber();
var points = try self.readPoints();
defer points.deinit();
try self.builder.writeDrawLineStrip(style, line_width, points.items);
},
.draw_line_path => {
var style = try self.parseStyle();
var line_width = try self.parseNumber();
var path = try self.readPath();
try self.builder.writeDrawPath(style, line_width, path.segments);
},
.outline_fill_polygon => {
var fill_style = try self.parseStyle();
var line_style = try self.parseStyle();
var line_width = try self.parseNumber();
var points = try self.readPoints();
defer points.deinit();
try self.builder.writeOutlineFillPolygon(fill_style, line_style, line_width, points.items);
},
.outline_fill_rectangles => {
var fill_style = try self.parseStyle();
var line_style = try self.parseStyle();
var line_width = try self.parseNumber();
var rects = try self.readRectangles();
defer rects.deinit();
try self.builder.writeOutlineFillRectangles(fill_style, line_style, line_width, rects.items);
},
.outline_fill_path => {
var fill_style = try self.parseStyle();
var line_style = try self.parseStyle();
var line_width = try self.parseNumber();
var path = try self.readPath();
try self.builder.writeOutlineFillPath(fill_style, line_style, line_width, path.segments);
},
.end_of_document => return error.SyntaxError,
_ => return error.SyntaxError,
}
try self.expectEnd();
},
}
}
try self.builder.writeEndOfFile();
}
};
var parser = Parser{ .builder = &builder, .tokenizer = Parser.Tokenizer.init(source), .allocator = allocator };
try parser.parse();
} | src/lib/text.zig |
const std = @import("std");
const os = std.os;
const IO_Uring = linux.IO_Uring;
const io_uring_sqe = linux.io_uring_sqe;
pub fn recvmsg(
self: *IO_Uring,
user_data: u64,
fd: os.fd_t,
msg: *os.msghdr,
flags: u32,
) !*io_uring_sqe {
const sqe = try self.get_sqe();
io_uring_prep_recvmsg(sqe, fd, msg, flags);
sqe.user_data = user_data;
return sqe;
}
pub fn sendmsg(
self: *IO_Uring,
user_data: u64,
fd: os.fd_t,
msg: *const os.msghdr_const,
flags: u32,
) !*io_uring_sqe {
const sqe = try self.get_sqe();
io_uring_prep_sendmsg(sqe, fd, msg, flags);
sqe.user_data = user_data;
return sqe;
}
pub fn io_uring_prep_recvmsg(
sqe: *io_uring_sqe,
fd: os.fd_t,
msg: *os.msghdr,
flags: u32,
) void {
linux.io_uring_prep_rw(.RECVMSG, sqe, fd, @ptrToInt(msg), 1, 0);
sqe.rw_flags = flags;
}
pub fn io_uring_prep_sendmsg(
sqe: *io_uring_sqe,
fd: os.fd_t,
msg: *const os.msghdr_const,
flags: u32,
) void {
linux.io_uring_prep_rw(.SENDMSG, sqe, fd, @ptrToInt(msg), 1, 0);
sqe.rw_flags = flags;
}
const testing = std.testing;
const builtin = std.builtin;
const linux = os.linux;
const mem = std.mem;
const net = std.net;
test "sendmsg/recvmsg" {
if (builtin.os.tag != .linux) return error.SkipZigTest;
var ring = IO_Uring.init(2, 0) catch |err| switch (err) {
error.SystemOutdated => return error.SkipZigTest,
error.PermissionDenied => return error.SkipZigTest,
else => return err,
};
defer ring.deinit();
const address_server = try net.Address.parseIp4("127.0.0.1", 3131);
const server = try os.socket(address_server.any.family, os.SOCK_DGRAM, 0);
defer os.close(server);
try os.setsockopt(server, os.SOL_SOCKET, os.SO_REUSEPORT, &mem.toBytes(@as(c_int, 1)));
try os.setsockopt(server, os.SOL_SOCKET, os.SO_REUSEADDR, &mem.toBytes(@as(c_int, 1)));
try os.bind(server, &address_server.any, address_server.getOsSockLen());
const client = try os.socket(address_server.any.family, os.SOCK_DGRAM, 0);
defer os.close(client);
const buffer_send = [_]u8{42} ** 128;
var iovecs_send = [_]os.iovec_const{
os.iovec_const{ .iov_base = &buffer_send, .iov_len = buffer_send.len },
};
const msg_send = os.msghdr_const{
.msg_name = &address_server.any,
.msg_namelen = address_server.getOsSockLen(),
.msg_iov = &iovecs_send,
.msg_iovlen = 1,
.msg_control = null,
.msg_controllen = 0,
.msg_flags = 0,
};
const sqe_sendmsg = try sendmsg(&ring, 0x11111111, client, &msg_send, 0);
sqe_sendmsg.flags |= linux.IOSQE_IO_LINK;
try testing.expectEqual(linux.IORING_OP.SENDMSG, sqe_sendmsg.opcode);
try testing.expectEqual(client, sqe_sendmsg.fd);
var buffer_recv = [_]u8{0} ** 128;
var iovecs_recv = [_]os.iovec{
os.iovec{ .iov_base = &buffer_recv, .iov_len = buffer_recv.len },
};
var addr = [_]u8{0} ** 4;
var address_recv = net.Address.initIp4(addr, 0);
var msg_recv: os.msghdr = os.msghdr{
.msg_name = &address_recv.any,
.msg_namelen = address_recv.getOsSockLen(),
.msg_iov = &iovecs_recv,
.msg_iovlen = 1,
.msg_control = null,
.msg_controllen = 0,
.msg_flags = 0,
};
const sqe_recvmsg = try recvmsg(&ring, 0x22222222, server, &msg_recv, 0);
try testing.expectEqual(linux.IORING_OP.RECVMSG, sqe_recvmsg.opcode);
try testing.expectEqual(server, sqe_recvmsg.fd);
try testing.expectEqual(@as(u32, 2), ring.sq_ready());
try testing.expectEqual(@as(u32, 2), try ring.submit_and_wait(2));
try testing.expectEqual(@as(u32, 0), ring.sq_ready());
try testing.expectEqual(@as(u32, 2), ring.cq_ready());
const cqe_sendmsg = try ring.copy_cqe();
if (cqe_sendmsg.res == -linux.EINVAL) return error.SkipZigTest;
try testing.expectEqual(linux.io_uring_cqe{
.user_data = 0x11111111,
.res = buffer_send.len,
.flags = 0,
}, cqe_sendmsg);
const cqe_recvmsg = try ring.copy_cqe();
if (cqe_recvmsg.res == -linux.EINVAL) return error.SkipZigTest;
try testing.expectEqual(linux.io_uring_cqe{
.user_data = 0x22222222,
.res = buffer_recv.len,
.flags = 0,
}, cqe_recvmsg);
try testing.expectEqualSlices(u8, buffer_send[0..buffer_recv.len], buffer_recv[0..]);
} | src/sendmsg.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 int = i64;
const util = @import("util.zig");
const gpa = util.gpa;
const data = @embedFile("../data/day22.txt");
const Command = struct {
op: enum{ on, off },
bounds: Bounds,
};
const Bounds = struct {
v: [3][2]int,
fn size(self: @This()) usize {
return @intCast(usize,
(self.v[0][1] - self.v[0][0] + 1) *
(self.v[1][1] - self.v[1][0] + 1) *
(self.v[2][1] - self.v[2][0] + 1));
}
fn intersects(a: @This(), b: @This()) bool {
return (a.v[0][0] <= b.v[0][1] and a.v[0][1] >= b.v[0][0]) and
(a.v[1][0] <= b.v[1][1] and a.v[1][1] >= b.v[1][0]) and
(a.v[2][0] <= b.v[2][1] and a.v[2][1] >= b.v[2][0]);
}
fn contains(a: @This(), b: @This()) bool {
return (a.v[0][0] <= b.v[0][0] and a.v[0][1] >= b.v[0][1]) and
(a.v[1][0] <= b.v[1][0] and a.v[1][1] >= b.v[1][1]) and
(a.v[2][0] <= b.v[2][0] and a.v[2][1] >= b.v[2][1]);
}
};
pub fn main() !void {
var timer = try std.time.Timer.start();
const items = util.parseLinesDelim(Command, data, " ,xyz=.");
const parse_time = timer.lap();
const part1_region = Bounds{ .v = [_][2]int{ .{-50, 50} } ** 3 };
var part1_regions = std.ArrayList(Bounds).init(gpa);
const part1_end_index = for (items) |it, i| {
if (!part1_region.contains(it.bounds)) break i;
try processCommand(it, &part1_regions);
} else unreachable;
var part1: usize = 0;
for (part1_regions.items) |r| {
part1 += r.size();
}
const part1_time = timer.lap();
var part2_regions = std.ArrayList(Bounds).init(gpa);
for (items[part1_end_index..]) |it| {
try processCommand(it, &part2_regions);
}
var part2: usize = part1;
for (part2_regions.items) |r| {
part2 += r.size();
}
const part2_time = timer.lap();
print("part1={}, part2={}\n", .{part1, part2});
print("Timing: parse={}, part1={}, part2={}, total={}\n", .{parse_time, part1_time, part2_time, parse_time + part1_time + part2_time});
}
fn processCommand(cmd: Command, regions: *std.ArrayList(Bounds)) !void {
switch (cmd.op) {
.on => {
var i: usize = 0;
next_region: while (i < regions.items.len) {
const item = regions.items[i];
if (item.intersects(cmd.bounds)) {
if (item.contains(cmd.bounds)) {
return; // all pixels already on
}
if (cmd.bounds.contains(item)) {
_ = regions.swapRemove(i);
continue :next_region;
}
var carved = CarvedList.init(0) catch unreachable;
carve(&carved, item, cmd.bounds);
try regions.replaceRange(i, 1, carved.slice());
i += carved.len;
} else {
i += 1;
}
}
try regions.append(cmd.bounds);
},
.off => {
var i: usize = 0;
next_region: while (i < regions.items.len) {
const item = regions.items[i];
if (item.intersects(cmd.bounds)) {
if (cmd.bounds.contains(item)) {
_ = regions.swapRemove(i);
continue :next_region;
}
var carved = CarvedList.init(0) catch unreachable;
carve(&carved, item, cmd.bounds);
try regions.replaceRange(i, 1, carved.slice());
i += carved.len;
} else {
i += 1;
}
}
},
}
}
const CarvedList = std.BoundedArray(Bounds, 6);
fn carve(result: *CarvedList, carved: Bounds, carver: Bounds) void {
var remain = carved;
var axis: usize = 0;
while (axis < 3) : (axis += 1) {
if (remain.v[axis][0] < carver.v[axis][0]) {
var chunk = remain;
chunk.v[axis][1] = carver.v[axis][0] - 1;
result.appendAssumeCapacity(chunk);
remain.v[axis][0] = carver.v[axis][0];
}
if (remain.v[axis][1] > carver.v[axis][1]) {
var chunk = remain;
chunk.v[axis][0] = carver.v[axis][1] + 1;
result.appendAssumeCapacity(chunk);
remain.v[axis][1] = carver.v[axis][1];
}
}
}
// 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/day22.zig |
const std = @import("std");
usingnamespace (@import("../machine.zig"));
usingnamespace (@import("../util.zig"));
const imm = Operand.immediate;
const imm8 = Operand.immediate8;
const imm16 = Operand.immediate16;
const imm32 = Operand.immediate32;
const imm64 = Operand.immediate64;
const immSign = Operand.immediateSigned;
const immSign8 = Operand.immediateSigned8;
const immSign16 = Operand.immediateSigned16;
const immSign32 = Operand.immediateSigned32;
const immSign64 = Operand.immediateSigned64;
const reg = Operand.register;
const regRm = Operand.registerRm;
test "cmp" {
const m32 = Machine.init(.x86_32);
const m64 = Machine.init(.x64);
debugPrint(false);
{
testOp2(m32, .CMP, reg(.RAX), imm(0), AsmError.InvalidOperand);
testOp2(m64, .CMP, reg(.RAX), imm(0), "48 83 f8 00");
//
testOp2(m32, .CMP, reg(.RAX), imm(0xff), AsmError.InvalidOperand);
testOp2(m64, .CMP, reg(.RAX), imm(0xff), "48 3d ff 00 00 00");
//
testOp2(m32, .CMP, reg(.RAX), immSign(-1), AsmError.InvalidOperand);
testOp2(m64, .CMP, reg(.RAX), immSign(-1), "48 83 f8 ff");
//
testOp2(m32, .CMP, reg(.AL), immSign(-1), "3C ff");
testOp2(m64, .CMP, reg(.AL), immSign(-1), "3C ff");
//
testOp2(m32, .CMP, reg(.AX), imm16(0xff), "66 3D ff 00");
testOp2(m64, .CMP, reg(.AX), imm16(0xff), "66 3D ff 00");
//
testOp2(m32, .CMP, reg(.EAX), imm32(0xff), "3D ff 00 00 00");
testOp2(m64, .CMP, reg(.EAX), imm32(0xff), "3D ff 00 00 00");
//
testOp2(m32, .CMP, reg(.RAX), immSign64(0xff), AsmError.InvalidOperand);
testOp2(m64, .CMP, reg(.RAX), immSign64(0xff), AsmError.InvalidOperand);
//
testOp2(m32, .CMP, reg(.RAX), immSign32(0xff), AsmError.InvalidOperand);
testOp2(m64, .CMP, reg(.RAX), immSign32(0xff), "48 3D ff 00 00 00");
//
testOp2(m32, .CMP, reg(.AX), immSign(-1), "66 83 f8 ff");
testOp2(m64, .CMP, reg(.AX), immSign(-1), "66 83 f8 ff");
//
testOp2(m32, .CMP, reg(.EAX), immSign(-1), "83 f8 ff");
testOp2(m64, .CMP, reg(.EAX), immSign(-1), "83 f8 ff");
//
testOp2(m32, .CMP, reg(.EAX), immSign(-1), "83 f8 ff");
testOp2(m64, .CMP, reg(.EAX), immSign(-1), "83 f8 ff");
//
testOp2(m32, .CMP, reg(.EAX), immSign32(-1), "3d ff ff ff ff");
testOp2(m64, .CMP, reg(.EAX), immSign32(-1), "3d ff ff ff ff");
}
{
testOp2(m32, .CMP, reg(.EAX), reg(.EAX), "39 c0");
testOp2(m64, .CMP, reg(.EAX), reg(.EAX), "39 c0");
//
testOp2(m32, .CMP, reg(.EAX), regRm(.EAX), "3b c0");
testOp2(m64, .CMP, reg(.EAX), regRm(.EAX), "3b c0");
//
testOp2(m32, .CMP, regRm(.EAX), reg(.EAX), "39 c0");
testOp2(m64, .CMP, regRm(.EAX), reg(.EAX), "39 c0");
}
{
testOp2(m32, .CMP, reg(.AL), regRm(.AL), "3a c0");
testOp2(m64, .CMP, reg(.AL), regRm(.AL), "3a c0");
//
testOp2(m32, .CMP, regRm(.AL), reg(.AL), "38 c0");
testOp2(m64, .CMP, regRm(.AL), reg(.AL), "38 c0");
}
{
testOp2(m32, .CMP, regRm(.EAX), imm32(0x33221100), "81 f8 00 11 22 33");
testOp2(m64, .CMP, regRm(.EAX), imm32(0x33221100), "81 f8 00 11 22 33");
//
testOp2(m32, .CMP, regRm(.AL), imm8(0), "80 f8 00");
testOp2(m64, .CMP, regRm(.AL), imm8(0), "80 f8 00");
}
} | src/x86/tests/cmp.zig |
const std = @import("std");
const lib = @import("lib");
const io = std.io;
const fs = std.fs;
const mem = std.mem;
const ArrayList = std.ArrayListUnmanaged;
const Allocator = std.mem.Allocator;
const Interpreter = lib.Interpreter;
const FindContext = @This();
stream: Stream,
line: u32 = 1,
column: u32 = 1,
stack: Stack = .{},
filename: []const u8,
tag: []const u8,
gpa: Allocator,
const log = std.log.scoped(.find_context);
pub const Error = error{OutOfMemory} || std.os.WriteError;
pub const Stream = io.BufferedWriter(1024, std.fs.File.Writer);
pub const Stack = ArrayList(Location);
pub const Location = struct {
line: u32,
column: u32,
};
pub fn init(gpa: Allocator, file: []const u8, tag: []const u8, writer: fs.File.Writer) FindContext {
return .{
.stream = .{ .unbuffered_writer = writer },
.filename = file,
.tag = tag,
.gpa = gpa,
};
}
pub fn write(self: *FindContext, vm: *Interpreter, text: []const u8, nl: u16) !void {
_ = vm;
if (nl == 0) {
self.column += @intCast(u32, text.len);
} else {
self.line += @intCast(u32, nl);
self.column = @intCast(u32, text.len + 1);
}
}
pub fn call(self: *FindContext, vm: *Interpreter) !void {
_ = vm;
try self.stack.append(self.gpa, .{
.line = self.line,
.column = self.column,
});
}
pub fn ret(self: *FindContext, vm: *Interpreter, name: []const u8) !void {
_ = name;
const writer = self.stream.writer();
const location = self.stack.pop();
const procedure = vm.linker.procedures.get(name).?;
const obj = vm.linker.objects.items[procedure.module - 1];
if (mem.eql(u8, self.tag, name)) try writer.print(
\\{s}: line {d} column {d} '{s}' -> line {d} column {d} '{s}' ({d} lines)
\\
, .{
self.tag,
procedure.location.line,
procedure.location.column,
obj.name,
location.line,
location.column,
self.filename,
self.line - location.line,
});
} | src/FindContext.zig |
pub const PspKernelErrorCodes = extern enum(c_int) {
Ok = 0,
Error = 2147614721,
Notimp = 2147614722,
IllegalExpcode = 2147614770,
ExpHandlerNoUse = 2147614771,
ExpHandlerUsed = 2147614772,
SycallTableNoUsed = 2147614773,
SycallTableUsed = 2147614774,
IllegalSyscalltable = 2147614775,
IllegalPrimarySyscallNumber = 2147614776,
PrimarySyscallNumberInUse = 2147614777,
IllegalContext = 2147614820,
IllegalIntrCode = 2147614821,
Cpudi = 2147614822,
FoundHandler = 2147614823,
NotFoundHandler = 2147614824,
IllegalIntrLevel = 2147614825,
IllegalAddress = 2147614826,
IllegalIntrParam = 2147614827,
IllegalStackAddress = 2147614828,
AlreadyStackSet = 2147614829,
NoTimer = 2147614870,
IllegalTimerid = 2147614871,
IllegalSource = 2147614872,
IllegalPrescale = 2147614873,
TimeBusy = 2147614874,
TimerNotSetup = 2147614875,
TimerNotInUse = 2147614876,
UnitUsed = 2147614880,
UnitNoUse = 2147614881,
NoRomDir = 2147614882,
IdTypeXxist = 2147614920,
IdTypeNotExist = 2147614921,
IdTypeNotEmpty = 2147614922,
UnknownUid = 2147614923,
UnmatchUidType = 2147614924,
IdNotExist = 2147614925,
NotFoundUidFunc = 2147614926,
UidAlreadyHolder = 2147614927,
UidNotHolder = 2147614928,
IllegalPerm = 2147614929,
IllegalArgument = 2147614930,
IllegalAddr = 2147614931,
OutOfRange = 2147614932,
MemRangeOverlap = 2147614933,
IllegalPartition = 2147614934,
PartitionInUse = 2147614935,
IllegalMemblockType = 2147614936,
MemblockAllocFailed = 2147614937,
MemblockResizeLocked = 2147614938,
MemblockResizeFailed = 2147614939,
HeapblockAllocFailed = 2147614940,
HeapAllocFailed = 2147614941,
IllegalChunkId = 2147614942,
Nochunk = 2147614943,
NoFreechunk = 2147614944,
Linkerr = 2147615020,
IllegalObject = 2147615021,
UnknownModule = 2147615022,
Nofile = 2147615023,
Fileerr = 2147615024,
Meminuse = 2147615025,
PartitionMismatch = 2147615026,
AlreadyStarted = 2147615027,
NotStarted = 2147615028,
AlreadyStopped = 2147615029,
CanNotStop = 2147615030,
NotStopped = 2147615031,
NotRemovable = 2147615032,
ExclusiveLoad = 2147615033,
LibraryNotYetLinked = 2147615034,
LibraryFound = 2147615035,
LibraryNotFound = 2147615036,
IllegalLibrary = 2147615037,
LibraryInUse = 2147615038,
AlreadyStopping = 2147615039,
IllegalOffset = 2147615040,
IllegalPosition = 2147615041,
IllegalAccess = 2147615042,
ModuleMgrBusy = 2147615043,
IllegalFlag = 2147615044,
CannotGetModulelist = 2147615045,
ProhibitLoadmoduleDevice = 2147615046,
ProhibitLoadexecDevice = 2147615047,
UnsupportedPrxType = 2147615048,
IllegalPermCall = 2147615049,
CannotGetModuleInformation = 2147615050,
IllegalLoadexecBuffer = 2147615051,
IllegalLoadexecFilename = 2147615052,
NoExitCallback = 2147615053,
NoMemory = 2147615120,
IllegalAttr = 2147615121,
IllegalEntry = 2147615122,
IllegalPriority = 2147615123,
IllegalStackSize = 2147615124,
IllegalMode = 2147615125,
IllegalMask = 2147615126,
IllegalThid = 2147615127,
UnknownThid = 2147615128,
UnknownSemid = 2147615129,
UnknownEvfid = 2147615130,
UnknownMbxid = 2147615131,
UnknownVplid = 2147615132,
UnknownFplid = 2147615133,
UnknownMppid = 2147615134,
UnknownAlmid = 2147615135,
UnknownTeid = 2147615136,
UnknownCbid = 2147615137,
Dormant = 2147615138,
Suspend = 2147615139,
NotDormant = 2147615140,
NotSuspend = 2147615141,
NotWait = 2147615142,
CanNotWait = 2147615143,
WaitTimeout = 2147615144,
WaitCancel = 2147615145,
ReleaseWait = 2147615146,
NotifyCallback = 2147615147,
ThreadTerminated = 2147615148,
SemaZero = 2147615149,
SemaOvf = 2147615150,
EvfCond = 2147615151,
EvfMulti = 2147615152,
EvfIlpat = 2147615153,
MboxNomsg = 2147615154,
MppFull = 2147615155,
MppEmpty = 2147615156,
WaitDelete = 2147615157,
IllegalMemblock = 2147615158,
IllegalMemsize = 2147615159,
IllegalSpadaddr = 2147615160,
SpadInUse = 2147615161,
SpadNotInUse = 2147615162,
IllegalType = 2147615163,
IllegalSize = 2147615164,
IllegalCount = 2147615165,
UnknownVtid = 2147615166,
IllegalVtid = 2147615167,
IllegalKtlsid = 2147615168,
KtlsFull = 2147615169,
KtlsBusy = 2147615170,
PmInvalidPriority = 2147615320,
PmInvalidDevname = 2147615321,
PmUnknownDevname = 2147615322,
PmPminfoRegistered = 2147615323,
PmPminfoUnregistered = 2147615324,
PmInvalidMajorState = 2147615325,
PmInvalidRequest = 2147615326,
PmUnknownRequest = 2147615327,
PmInvalidUnit = 2147615328,
PmCannotCancel = 2147615329,
PmInvalidPminfo = 2147615330,
PmInvalidArgument = 2147615331,
PmAlreadyTargetPwrstate = 2147615332,
PmChangePwrstateFailed = 2147615333,
PmCannotChangeDevpwrState = 2147615334,
PmNoSupportDevpwrState = 2147615335,
DmacRequestFailed = 2147615420,
DmacRequestDenied = 2147615421,
DmacOpQueued = 2147615422,
DmacOpNotQueued = 2147615423,
DmacOpRunning = 2147615424,
DmacOpNotAssigned = 2147615425,
DmacOpTimeout = 2147615426,
DmacOpFreed = 2147615427,
DmacOpUsed = 2147615428,
DmacOpEmpty = 2147615429,
DmacOpAborted = 2147615430,
DmacOpError = 2147615431,
DmacChannelReserved = 2147615432,
DmacChannelExcluded = 2147615433,
DmacPrivilegeAddress = 2147615434,
DmacNotEnoughspace = 2147615435,
DmacChannelNotAssigned = 2147615436,
DmacChildOperation = 2147615437,
DmacTooMuchSize = 2147615438,
DmacInvalidArgument = 2147615439,
Mfile = 2147615520,
Nodev = 2147615521,
Xdev = 2147615522,
Badf = 2147615523,
Inval = 2147615524,
Unsup = 2147615525,
AliasUsed = 2147615526,
CannotMount = 2147615527,
DriverDeleted = 2147615528,
AsyncBusy = 2147615529,
Noasync = 2147615530,
Regdev = 2147615531,
Nocwd = 2147615532,
Nametoolong = 2147615533,
Nxio = 2147615720,
Io = 2147615721,
Nomem = 2147615722,
StdioNotOpened = 2147615723,
CacheAlignment = 2147615820,
Errormax = 2147615821,
}; | src/psp/sdk/pspkerror.zig |
pub const MAX_REASON_NAME_LEN = @as(u32, 64);
pub const MAX_REASON_DESC_LEN = @as(u32, 256);
pub const MAX_REASON_BUGID_LEN = @as(u32, 32);
pub const MAX_REASON_COMMENT_LEN = @as(u32, 512);
pub const SHUTDOWN_TYPE_LEN = @as(u32, 32);
pub const POLICY_SHOWREASONUI_NEVER = @as(u32, 0);
pub const POLICY_SHOWREASONUI_ALWAYS = @as(u32, 1);
pub const POLICY_SHOWREASONUI_WORKSTATIONONLY = @as(u32, 2);
pub const POLICY_SHOWREASONUI_SERVERONLY = @as(u32, 3);
pub const SNAPSHOT_POLICY_NEVER = @as(u32, 0);
pub const SNAPSHOT_POLICY_ALWAYS = @as(u32, 1);
pub const SNAPSHOT_POLICY_UNPLANNED = @as(u32, 2);
pub const MAX_NUM_REASONS = @as(u32, 256);
//--------------------------------------------------------------------------------
// Section: Types (3)
//--------------------------------------------------------------------------------
pub const SHUTDOWN_REASON = enum(u32) {
NONE = 0,
FLAG_COMMENT_REQUIRED = 16777216,
FLAG_DIRTY_PROBLEM_ID_REQUIRED = 33554432,
FLAG_CLEAN_UI = 67108864,
FLAG_DIRTY_UI = 134217728,
FLAG_MOBILE_UI_RESERVED = 268435456,
FLAG_USER_DEFINED = 1073741824,
FLAG_PLANNED = 2147483648,
// MAJOR_OTHER = 0, this enum value conflicts with NONE
// MAJOR_NONE = 0, this enum value conflicts with NONE
MAJOR_HARDWARE = 65536,
MAJOR_OPERATINGSYSTEM = 131072,
MAJOR_SOFTWARE = 196608,
MAJOR_APPLICATION = 262144,
MAJOR_SYSTEM = 327680,
MAJOR_POWER = 393216,
MAJOR_LEGACY_API = 458752,
// MINOR_OTHER = 0, this enum value conflicts with NONE
MINOR_NONE = 255,
MINOR_MAINTENANCE = 1,
MINOR_INSTALLATION = 2,
MINOR_UPGRADE = 3,
MINOR_RECONFIG = 4,
MINOR_HUNG = 5,
MINOR_UNSTABLE = 6,
MINOR_DISK = 7,
MINOR_PROCESSOR = 8,
MINOR_NETWORKCARD = 9,
MINOR_POWER_SUPPLY = 10,
MINOR_CORDUNPLUGGED = 11,
MINOR_ENVIRONMENT = 12,
MINOR_HARDWARE_DRIVER = 13,
MINOR_OTHERDRIVER = 14,
MINOR_BLUESCREEN = 15,
MINOR_SERVICEPACK = 16,
MINOR_HOTFIX = 17,
MINOR_SECURITYFIX = 18,
MINOR_SECURITY = 19,
MINOR_NETWORK_CONNECTIVITY = 20,
MINOR_WMI = 21,
MINOR_SERVICEPACK_UNINSTALL = 22,
MINOR_HOTFIX_UNINSTALL = 23,
MINOR_SECURITYFIX_UNINSTALL = 24,
MINOR_MMC = 25,
MINOR_SYSTEMRESTORE = 26,
MINOR_TERMSRV = 32,
MINOR_DC_PROMOTION = 33,
MINOR_DC_DEMOTION = 34,
// UNKNOWN = 255, this enum value conflicts with MINOR_NONE
LEGACY_API = 2147942400,
VALID_BIT_MASK = 3238002687,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
FLAG_COMMENT_REQUIRED: u1 = 0,
FLAG_DIRTY_PROBLEM_ID_REQUIRED: u1 = 0,
FLAG_CLEAN_UI: u1 = 0,
FLAG_DIRTY_UI: u1 = 0,
FLAG_MOBILE_UI_RESERVED: u1 = 0,
FLAG_USER_DEFINED: u1 = 0,
FLAG_PLANNED: u1 = 0,
MAJOR_HARDWARE: u1 = 0,
MAJOR_OPERATINGSYSTEM: u1 = 0,
MAJOR_SOFTWARE: u1 = 0,
MAJOR_APPLICATION: u1 = 0,
MAJOR_SYSTEM: u1 = 0,
MAJOR_POWER: u1 = 0,
MAJOR_LEGACY_API: u1 = 0,
MINOR_NONE: u1 = 0,
MINOR_MAINTENANCE: u1 = 0,
MINOR_INSTALLATION: u1 = 0,
MINOR_UPGRADE: u1 = 0,
MINOR_RECONFIG: u1 = 0,
MINOR_HUNG: u1 = 0,
MINOR_UNSTABLE: u1 = 0,
MINOR_DISK: u1 = 0,
MINOR_PROCESSOR: u1 = 0,
MINOR_NETWORKCARD: u1 = 0,
MINOR_POWER_SUPPLY: u1 = 0,
MINOR_CORDUNPLUGGED: u1 = 0,
MINOR_ENVIRONMENT: u1 = 0,
MINOR_HARDWARE_DRIVER: u1 = 0,
MINOR_OTHERDRIVER: u1 = 0,
MINOR_BLUESCREEN: u1 = 0,
MINOR_SERVICEPACK: u1 = 0,
MINOR_HOTFIX: u1 = 0,
MINOR_SECURITYFIX: u1 = 0,
MINOR_SECURITY: u1 = 0,
MINOR_NETWORK_CONNECTIVITY: u1 = 0,
MINOR_WMI: u1 = 0,
MINOR_SERVICEPACK_UNINSTALL: u1 = 0,
MINOR_HOTFIX_UNINSTALL: u1 = 0,
MINOR_SECURITYFIX_UNINSTALL: u1 = 0,
MINOR_MMC: u1 = 0,
MINOR_SYSTEMRESTORE: u1 = 0,
MINOR_TERMSRV: u1 = 0,
MINOR_DC_PROMOTION: u1 = 0,
MINOR_DC_DEMOTION: u1 = 0,
LEGACY_API: u1 = 0,
VALID_BIT_MASK: u1 = 0,
}) SHUTDOWN_REASON {
return @intToEnum(SHUTDOWN_REASON,
(if (o.NONE == 1) @enumToInt(SHUTDOWN_REASON.NONE) else 0)
| (if (o.FLAG_COMMENT_REQUIRED == 1) @enumToInt(SHUTDOWN_REASON.FLAG_COMMENT_REQUIRED) else 0)
| (if (o.FLAG_DIRTY_PROBLEM_ID_REQUIRED == 1) @enumToInt(SHUTDOWN_REASON.FLAG_DIRTY_PROBLEM_ID_REQUIRED) else 0)
| (if (o.FLAG_CLEAN_UI == 1) @enumToInt(SHUTDOWN_REASON.FLAG_CLEAN_UI) else 0)
| (if (o.FLAG_DIRTY_UI == 1) @enumToInt(SHUTDOWN_REASON.FLAG_DIRTY_UI) else 0)
| (if (o.FLAG_MOBILE_UI_RESERVED == 1) @enumToInt(SHUTDOWN_REASON.FLAG_MOBILE_UI_RESERVED) else 0)
| (if (o.FLAG_USER_DEFINED == 1) @enumToInt(SHUTDOWN_REASON.FLAG_USER_DEFINED) else 0)
| (if (o.FLAG_PLANNED == 1) @enumToInt(SHUTDOWN_REASON.FLAG_PLANNED) else 0)
| (if (o.MAJOR_HARDWARE == 1) @enumToInt(SHUTDOWN_REASON.MAJOR_HARDWARE) else 0)
| (if (o.MAJOR_OPERATINGSYSTEM == 1) @enumToInt(SHUTDOWN_REASON.MAJOR_OPERATINGSYSTEM) else 0)
| (if (o.MAJOR_SOFTWARE == 1) @enumToInt(SHUTDOWN_REASON.MAJOR_SOFTWARE) else 0)
| (if (o.MAJOR_APPLICATION == 1) @enumToInt(SHUTDOWN_REASON.MAJOR_APPLICATION) else 0)
| (if (o.MAJOR_SYSTEM == 1) @enumToInt(SHUTDOWN_REASON.MAJOR_SYSTEM) else 0)
| (if (o.MAJOR_POWER == 1) @enumToInt(SHUTDOWN_REASON.MAJOR_POWER) else 0)
| (if (o.MAJOR_LEGACY_API == 1) @enumToInt(SHUTDOWN_REASON.MAJOR_LEGACY_API) else 0)
| (if (o.MINOR_NONE == 1) @enumToInt(SHUTDOWN_REASON.MINOR_NONE) else 0)
| (if (o.MINOR_MAINTENANCE == 1) @enumToInt(SHUTDOWN_REASON.MINOR_MAINTENANCE) else 0)
| (if (o.MINOR_INSTALLATION == 1) @enumToInt(SHUTDOWN_REASON.MINOR_INSTALLATION) else 0)
| (if (o.MINOR_UPGRADE == 1) @enumToInt(SHUTDOWN_REASON.MINOR_UPGRADE) else 0)
| (if (o.MINOR_RECONFIG == 1) @enumToInt(SHUTDOWN_REASON.MINOR_RECONFIG) else 0)
| (if (o.MINOR_HUNG == 1) @enumToInt(SHUTDOWN_REASON.MINOR_HUNG) else 0)
| (if (o.MINOR_UNSTABLE == 1) @enumToInt(SHUTDOWN_REASON.MINOR_UNSTABLE) else 0)
| (if (o.MINOR_DISK == 1) @enumToInt(SHUTDOWN_REASON.MINOR_DISK) else 0)
| (if (o.MINOR_PROCESSOR == 1) @enumToInt(SHUTDOWN_REASON.MINOR_PROCESSOR) else 0)
| (if (o.MINOR_NETWORKCARD == 1) @enumToInt(SHUTDOWN_REASON.MINOR_NETWORKCARD) else 0)
| (if (o.MINOR_POWER_SUPPLY == 1) @enumToInt(SHUTDOWN_REASON.MINOR_POWER_SUPPLY) else 0)
| (if (o.MINOR_CORDUNPLUGGED == 1) @enumToInt(SHUTDOWN_REASON.MINOR_CORDUNPLUGGED) else 0)
| (if (o.MINOR_ENVIRONMENT == 1) @enumToInt(SHUTDOWN_REASON.MINOR_ENVIRONMENT) else 0)
| (if (o.MINOR_HARDWARE_DRIVER == 1) @enumToInt(SHUTDOWN_REASON.MINOR_HARDWARE_DRIVER) else 0)
| (if (o.MINOR_OTHERDRIVER == 1) @enumToInt(SHUTDOWN_REASON.MINOR_OTHERDRIVER) else 0)
| (if (o.MINOR_BLUESCREEN == 1) @enumToInt(SHUTDOWN_REASON.MINOR_BLUESCREEN) else 0)
| (if (o.MINOR_SERVICEPACK == 1) @enumToInt(SHUTDOWN_REASON.MINOR_SERVICEPACK) else 0)
| (if (o.MINOR_HOTFIX == 1) @enumToInt(SHUTDOWN_REASON.MINOR_HOTFIX) else 0)
| (if (o.MINOR_SECURITYFIX == 1) @enumToInt(SHUTDOWN_REASON.MINOR_SECURITYFIX) else 0)
| (if (o.MINOR_SECURITY == 1) @enumToInt(SHUTDOWN_REASON.MINOR_SECURITY) else 0)
| (if (o.MINOR_NETWORK_CONNECTIVITY == 1) @enumToInt(SHUTDOWN_REASON.MINOR_NETWORK_CONNECTIVITY) else 0)
| (if (o.MINOR_WMI == 1) @enumToInt(SHUTDOWN_REASON.MINOR_WMI) else 0)
| (if (o.MINOR_SERVICEPACK_UNINSTALL == 1) @enumToInt(SHUTDOWN_REASON.MINOR_SERVICEPACK_UNINSTALL) else 0)
| (if (o.MINOR_HOTFIX_UNINSTALL == 1) @enumToInt(SHUTDOWN_REASON.MINOR_HOTFIX_UNINSTALL) else 0)
| (if (o.MINOR_SECURITYFIX_UNINSTALL == 1) @enumToInt(SHUTDOWN_REASON.MINOR_SECURITYFIX_UNINSTALL) else 0)
| (if (o.MINOR_MMC == 1) @enumToInt(SHUTDOWN_REASON.MINOR_MMC) else 0)
| (if (o.MINOR_SYSTEMRESTORE == 1) @enumToInt(SHUTDOWN_REASON.MINOR_SYSTEMRESTORE) else 0)
| (if (o.MINOR_TERMSRV == 1) @enumToInt(SHUTDOWN_REASON.MINOR_TERMSRV) else 0)
| (if (o.MINOR_DC_PROMOTION == 1) @enumToInt(SHUTDOWN_REASON.MINOR_DC_PROMOTION) else 0)
| (if (o.MINOR_DC_DEMOTION == 1) @enumToInt(SHUTDOWN_REASON.MINOR_DC_DEMOTION) else 0)
| (if (o.LEGACY_API == 1) @enumToInt(SHUTDOWN_REASON.LEGACY_API) else 0)
| (if (o.VALID_BIT_MASK == 1) @enumToInt(SHUTDOWN_REASON.VALID_BIT_MASK) else 0)
);
}
};
pub const SHTDN_REASON_NONE = SHUTDOWN_REASON.NONE;
pub const SHTDN_REASON_FLAG_COMMENT_REQUIRED = SHUTDOWN_REASON.FLAG_COMMENT_REQUIRED;
pub const SHTDN_REASON_FLAG_DIRTY_PROBLEM_ID_REQUIRED = SHUTDOWN_REASON.FLAG_DIRTY_PROBLEM_ID_REQUIRED;
pub const SHTDN_REASON_FLAG_CLEAN_UI = SHUTDOWN_REASON.FLAG_CLEAN_UI;
pub const SHTDN_REASON_FLAG_DIRTY_UI = SHUTDOWN_REASON.FLAG_DIRTY_UI;
pub const SHTDN_REASON_FLAG_MOBILE_UI_RESERVED = SHUTDOWN_REASON.FLAG_MOBILE_UI_RESERVED;
pub const SHTDN_REASON_FLAG_USER_DEFINED = SHUTDOWN_REASON.FLAG_USER_DEFINED;
pub const SHTDN_REASON_FLAG_PLANNED = SHUTDOWN_REASON.FLAG_PLANNED;
pub const SHTDN_REASON_MAJOR_OTHER = SHUTDOWN_REASON.NONE;
pub const SHTDN_REASON_MAJOR_NONE = SHUTDOWN_REASON.NONE;
pub const SHTDN_REASON_MAJOR_HARDWARE = SHUTDOWN_REASON.MAJOR_HARDWARE;
pub const SHTDN_REASON_MAJOR_OPERATINGSYSTEM = SHUTDOWN_REASON.MAJOR_OPERATINGSYSTEM;
pub const SHTDN_REASON_MAJOR_SOFTWARE = SHUTDOWN_REASON.MAJOR_SOFTWARE;
pub const SHTDN_REASON_MAJOR_APPLICATION = SHUTDOWN_REASON.MAJOR_APPLICATION;
pub const SHTDN_REASON_MAJOR_SYSTEM = SHUTDOWN_REASON.MAJOR_SYSTEM;
pub const SHTDN_REASON_MAJOR_POWER = SHUTDOWN_REASON.MAJOR_POWER;
pub const SHTDN_REASON_MAJOR_LEGACY_API = SHUTDOWN_REASON.MAJOR_LEGACY_API;
pub const SHTDN_REASON_MINOR_OTHER = SHUTDOWN_REASON.NONE;
pub const SHTDN_REASON_MINOR_NONE = SHUTDOWN_REASON.MINOR_NONE;
pub const SHTDN_REASON_MINOR_MAINTENANCE = SHUTDOWN_REASON.MINOR_MAINTENANCE;
pub const SHTDN_REASON_MINOR_INSTALLATION = SHUTDOWN_REASON.MINOR_INSTALLATION;
pub const SHTDN_REASON_MINOR_UPGRADE = SHUTDOWN_REASON.MINOR_UPGRADE;
pub const SHTDN_REASON_MINOR_RECONFIG = SHUTDOWN_REASON.MINOR_RECONFIG;
pub const SHTDN_REASON_MINOR_HUNG = SHUTDOWN_REASON.MINOR_HUNG;
pub const SHTDN_REASON_MINOR_UNSTABLE = SHUTDOWN_REASON.MINOR_UNSTABLE;
pub const SHTDN_REASON_MINOR_DISK = SHUTDOWN_REASON.MINOR_DISK;
pub const SHTDN_REASON_MINOR_PROCESSOR = SHUTDOWN_REASON.MINOR_PROCESSOR;
pub const SHTDN_REASON_MINOR_NETWORKCARD = SHUTDOWN_REASON.MINOR_NETWORKCARD;
pub const SHTDN_REASON_MINOR_POWER_SUPPLY = SHUTDOWN_REASON.MINOR_POWER_SUPPLY;
pub const SHTDN_REASON_MINOR_CORDUNPLUGGED = SHUTDOWN_REASON.MINOR_CORDUNPLUGGED;
pub const SHTDN_REASON_MINOR_ENVIRONMENT = SHUTDOWN_REASON.MINOR_ENVIRONMENT;
pub const SHTDN_REASON_MINOR_HARDWARE_DRIVER = SHUTDOWN_REASON.MINOR_HARDWARE_DRIVER;
pub const SHTDN_REASON_MINOR_OTHERDRIVER = SHUTDOWN_REASON.MINOR_OTHERDRIVER;
pub const SHTDN_REASON_MINOR_BLUESCREEN = SHUTDOWN_REASON.MINOR_BLUESCREEN;
pub const SHTDN_REASON_MINOR_SERVICEPACK = SHUTDOWN_REASON.MINOR_SERVICEPACK;
pub const SHTDN_REASON_MINOR_HOTFIX = SHUTDOWN_REASON.MINOR_HOTFIX;
pub const SHTDN_REASON_MINOR_SECURITYFIX = SHUTDOWN_REASON.MINOR_SECURITYFIX;
pub const SHTDN_REASON_MINOR_SECURITY = SHUTDOWN_REASON.MINOR_SECURITY;
pub const SHTDN_REASON_MINOR_NETWORK_CONNECTIVITY = SHUTDOWN_REASON.MINOR_NETWORK_CONNECTIVITY;
pub const SHTDN_REASON_MINOR_WMI = SHUTDOWN_REASON.MINOR_WMI;
pub const SHTDN_REASON_MINOR_SERVICEPACK_UNINSTALL = SHUTDOWN_REASON.MINOR_SERVICEPACK_UNINSTALL;
pub const SHTDN_REASON_MINOR_HOTFIX_UNINSTALL = SHUTDOWN_REASON.MINOR_HOTFIX_UNINSTALL;
pub const SHTDN_REASON_MINOR_SECURITYFIX_UNINSTALL = SHUTDOWN_REASON.MINOR_SECURITYFIX_UNINSTALL;
pub const SHTDN_REASON_MINOR_MMC = SHUTDOWN_REASON.MINOR_MMC;
pub const SHTDN_REASON_MINOR_SYSTEMRESTORE = SHUTDOWN_REASON.MINOR_SYSTEMRESTORE;
pub const SHTDN_REASON_MINOR_TERMSRV = SHUTDOWN_REASON.MINOR_TERMSRV;
pub const SHTDN_REASON_MINOR_DC_PROMOTION = SHUTDOWN_REASON.MINOR_DC_PROMOTION;
pub const SHTDN_REASON_MINOR_DC_DEMOTION = SHUTDOWN_REASON.MINOR_DC_DEMOTION;
pub const SHTDN_REASON_UNKNOWN = SHUTDOWN_REASON.MINOR_NONE;
pub const SHTDN_REASON_LEGACY_API = SHUTDOWN_REASON.LEGACY_API;
pub const SHTDN_REASON_VALID_BIT_MASK = SHUTDOWN_REASON.VALID_BIT_MASK;
pub const SHUTDOWN_FLAGS = enum(u32) {
FORCE_OTHERS = 1,
FORCE_SELF = 2,
RESTART = 4,
POWEROFF = 8,
NOREBOOT = 16,
GRACE_OVERRIDE = 32,
INSTALL_UPDATES = 64,
RESTARTAPPS = 128,
SKIP_SVC_PRESHUTDOWN = 256,
HYBRID = 512,
RESTART_BOOTOPTIONS = 1024,
SOFT_REBOOT = 2048,
MOBILE_UI = 4096,
ARSO = 8192,
_,
pub fn initFlags(o: struct {
FORCE_OTHERS: u1 = 0,
FORCE_SELF: u1 = 0,
RESTART: u1 = 0,
POWEROFF: u1 = 0,
NOREBOOT: u1 = 0,
GRACE_OVERRIDE: u1 = 0,
INSTALL_UPDATES: u1 = 0,
RESTARTAPPS: u1 = 0,
SKIP_SVC_PRESHUTDOWN: u1 = 0,
HYBRID: u1 = 0,
RESTART_BOOTOPTIONS: u1 = 0,
SOFT_REBOOT: u1 = 0,
MOBILE_UI: u1 = 0,
ARSO: u1 = 0,
}) SHUTDOWN_FLAGS {
return @intToEnum(SHUTDOWN_FLAGS,
(if (o.FORCE_OTHERS == 1) @enumToInt(SHUTDOWN_FLAGS.FORCE_OTHERS) else 0)
| (if (o.FORCE_SELF == 1) @enumToInt(SHUTDOWN_FLAGS.FORCE_SELF) else 0)
| (if (o.RESTART == 1) @enumToInt(SHUTDOWN_FLAGS.RESTART) else 0)
| (if (o.POWEROFF == 1) @enumToInt(SHUTDOWN_FLAGS.POWEROFF) else 0)
| (if (o.NOREBOOT == 1) @enumToInt(SHUTDOWN_FLAGS.NOREBOOT) else 0)
| (if (o.GRACE_OVERRIDE == 1) @enumToInt(SHUTDOWN_FLAGS.GRACE_OVERRIDE) else 0)
| (if (o.INSTALL_UPDATES == 1) @enumToInt(SHUTDOWN_FLAGS.INSTALL_UPDATES) else 0)
| (if (o.RESTARTAPPS == 1) @enumToInt(SHUTDOWN_FLAGS.RESTARTAPPS) else 0)
| (if (o.SKIP_SVC_PRESHUTDOWN == 1) @enumToInt(SHUTDOWN_FLAGS.SKIP_SVC_PRESHUTDOWN) else 0)
| (if (o.HYBRID == 1) @enumToInt(SHUTDOWN_FLAGS.HYBRID) else 0)
| (if (o.RESTART_BOOTOPTIONS == 1) @enumToInt(SHUTDOWN_FLAGS.RESTART_BOOTOPTIONS) else 0)
| (if (o.SOFT_REBOOT == 1) @enumToInt(SHUTDOWN_FLAGS.SOFT_REBOOT) else 0)
| (if (o.MOBILE_UI == 1) @enumToInt(SHUTDOWN_FLAGS.MOBILE_UI) else 0)
| (if (o.ARSO == 1) @enumToInt(SHUTDOWN_FLAGS.ARSO) else 0)
);
}
};
pub const SHUTDOWN_FORCE_OTHERS = SHUTDOWN_FLAGS.FORCE_OTHERS;
pub const SHUTDOWN_FORCE_SELF = SHUTDOWN_FLAGS.FORCE_SELF;
pub const SHUTDOWN_RESTART = SHUTDOWN_FLAGS.RESTART;
pub const SHUTDOWN_POWEROFF = SHUTDOWN_FLAGS.POWEROFF;
pub const SHUTDOWN_NOREBOOT = SHUTDOWN_FLAGS.NOREBOOT;
pub const SHUTDOWN_GRACE_OVERRIDE = SHUTDOWN_FLAGS.GRACE_OVERRIDE;
pub const SHUTDOWN_INSTALL_UPDATES = SHUTDOWN_FLAGS.INSTALL_UPDATES;
pub const SHUTDOWN_RESTARTAPPS = SHUTDOWN_FLAGS.RESTARTAPPS;
pub const SHUTDOWN_SKIP_SVC_PRESHUTDOWN = SHUTDOWN_FLAGS.SKIP_SVC_PRESHUTDOWN;
pub const SHUTDOWN_HYBRID = SHUTDOWN_FLAGS.HYBRID;
pub const SHUTDOWN_RESTART_BOOTOPTIONS = SHUTDOWN_FLAGS.RESTART_BOOTOPTIONS;
pub const SHUTDOWN_SOFT_REBOOT = SHUTDOWN_FLAGS.SOFT_REBOOT;
pub const SHUTDOWN_MOBILE_UI = SHUTDOWN_FLAGS.MOBILE_UI;
pub const SHUTDOWN_ARSO = SHUTDOWN_FLAGS.ARSO;
pub const EXIT_WINDOWS_FLAGS = enum(u32) {
HYBRID_SHUTDOWN = 4194304,
LOGOFF = 0,
POWEROFF = 8,
REBOOT = 2,
RESTARTAPPS = 64,
SHUTDOWN = 1,
};
pub const EWX_HYBRID_SHUTDOWN = EXIT_WINDOWS_FLAGS.HYBRID_SHUTDOWN;
pub const EWX_LOGOFF = EXIT_WINDOWS_FLAGS.LOGOFF;
pub const EWX_POWEROFF = EXIT_WINDOWS_FLAGS.POWEROFF;
pub const EWX_REBOOT = EXIT_WINDOWS_FLAGS.REBOOT;
pub const EWX_RESTARTAPPS = EXIT_WINDOWS_FLAGS.RESTARTAPPS;
pub const EWX_SHUTDOWN = EXIT_WINDOWS_FLAGS.SHUTDOWN;
//--------------------------------------------------------------------------------
// Section: Functions (14)
//--------------------------------------------------------------------------------
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "USER32" fn ExitWindowsEx(
uFlags: EXIT_WINDOWS_FLAGS,
dwReason: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "USER32" fn LockWorkStation(
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn ShutdownBlockReasonCreate(
hWnd: ?HWND,
pwszReason: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn ShutdownBlockReasonQuery(
hWnd: ?HWND,
pwszBuff: ?[*:0]u16,
pcchBuff: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn ShutdownBlockReasonDestroy(
hWnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn InitiateSystemShutdownA(
lpMachineName: ?PSTR,
lpMessage: ?PSTR,
dwTimeout: u32,
bForceAppsClosed: BOOL,
bRebootAfterShutdown: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn InitiateSystemShutdownW(
lpMachineName: ?PWSTR,
lpMessage: ?PWSTR,
dwTimeout: u32,
bForceAppsClosed: BOOL,
bRebootAfterShutdown: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn AbortSystemShutdownA(
lpMachineName: ?PSTR,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn AbortSystemShutdownW(
lpMachineName: ?PWSTR,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn InitiateSystemShutdownExA(
lpMachineName: ?PSTR,
lpMessage: ?PSTR,
dwTimeout: u32,
bForceAppsClosed: BOOL,
bRebootAfterShutdown: BOOL,
dwReason: SHUTDOWN_REASON,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ADVAPI32" fn InitiateSystemShutdownExW(
lpMachineName: ?PWSTR,
lpMessage: ?PWSTR,
dwTimeout: u32,
bForceAppsClosed: BOOL,
bRebootAfterShutdown: BOOL,
dwReason: SHUTDOWN_REASON,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "ADVAPI32" fn InitiateShutdownA(
lpMachineName: ?PSTR,
lpMessage: ?PSTR,
dwGracePeriod: u32,
dwShutdownFlags: SHUTDOWN_FLAGS,
dwReason: SHUTDOWN_REASON,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "ADVAPI32" fn InitiateShutdownW(
lpMachineName: ?PWSTR,
lpMessage: ?PWSTR,
dwGracePeriod: u32,
dwShutdownFlags: SHUTDOWN_FLAGS,
dwReason: SHUTDOWN_REASON,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "ADVAPI32" fn CheckForHiberboot(
pHiberboot: ?*BOOLEAN,
bClearFlag: BOOLEAN,
) callconv(@import("std").os.windows.WINAPI) u32;
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (4)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
pub const InitiateSystemShutdown = thismodule.InitiateSystemShutdownA;
pub const AbortSystemShutdown = thismodule.AbortSystemShutdownA;
pub const InitiateSystemShutdownEx = thismodule.InitiateSystemShutdownExA;
pub const InitiateShutdown = thismodule.InitiateShutdownA;
},
.wide => struct {
pub const InitiateSystemShutdown = thismodule.InitiateSystemShutdownW;
pub const AbortSystemShutdown = thismodule.AbortSystemShutdownW;
pub const InitiateSystemShutdownEx = thismodule.InitiateSystemShutdownExW;
pub const InitiateShutdown = thismodule.InitiateShutdownW;
},
.unspecified => if (@import("builtin").is_test) struct {
pub const InitiateSystemShutdown = *opaque{};
pub const AbortSystemShutdown = *opaque{};
pub const InitiateSystemShutdownEx = *opaque{};
pub const InitiateShutdown = *opaque{};
} else struct {
pub const InitiateSystemShutdown = @compileError("'InitiateSystemShutdown' requires that UNICODE be set to true or false in the root module");
pub const AbortSystemShutdown = @compileError("'AbortSystemShutdown' requires that UNICODE be set to true or false in the root module");
pub const InitiateSystemShutdownEx = @compileError("'InitiateSystemShutdownEx' requires that UNICODE be set to true or false in the root module");
pub const InitiateShutdown = @compileError("'InitiateShutdown' requires that UNICODE be set to true or false in the root module");
},
};
//--------------------------------------------------------------------------------
// Section: Imports (5)
//--------------------------------------------------------------------------------
const BOOL = @import("../foundation.zig").BOOL;
const BOOLEAN = @import("../foundation.zig").BOOLEAN;
const HWND = @import("../foundation.zig").HWND;
const PSTR = @import("../foundation.zig").PSTR;
const PWSTR = @import("../foundation.zig").PWSTR;
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;
}
}
} | deps/zigwin32/win32/system/shutdown.zig |
const std = @import("std");
const ascii = std.ascii;
const base64 = std.base64;
const c = std.c;
const debug = std.debug;
const fs = std.fs;
const heap = std.heap;
const io = std.io;
const math = std.math;
const mem = std.mem;
const os = std.os;
const unicode = std.unicode;
const Rune = u32;
const ATTR_NULL = 0;
const ATTR_BOLD = 1 << 0;
const ATTR_FAINT = 1 << 1;
const ATTR_ITALIC = 1 << 2;
const ATTR_UNDERLINE = 1 << 3;
const ATTR_BLINK = 1 << 4;
const ATTR_REVERSE = 1 << 5;
const ATTR_INVISIBLE = 1 << 6;
const ATTR_STRUCK = 1 << 7;
const ATTR_WRAP = 1 << 8;
const ATTR_WIDE = 1 << 9;
const ATTR_WDUMMY = 1 << 10;
const ATTR_BOLD_FAINT = ATTR_BOLD | ATTR_FAINT;
const MODE_WRAP = 1 << 0;
const MODE_INSERT = 1 << 1;
const MODE_ALTSCREEN = 1 << 2;
const MODE_CRLF = 1 << 3;
const MODE_ECHO = 1 << 4;
const MODE_PRINT = 1 << 5;
const MODE_UTF8 = 1 << 6;
const SEL_IDLE = 0;
const SEL_EMPTY = 1;
const SEL_READY = 2;
const SEL_REGULAR = 1;
const SEL_RECTANGULAR = 2;
const SNAP_WORD = 1;
const SNAP_LINE = 2;
const CURSOR_DEFAULT: u8 = 0;
const CURSOR_WRAPNEXT: u8 = 1;
const CURSOR_ORIGIN: u8 = 2;
const CURSOR_SAVE = 0;
const CURSOR_LOAD = 1;
const Selection = extern struct {
mode: c_int = SEL_IDLE,
type: c_int = 0,
snap: c_int = 0,
nb: Var = Var{},
ne: Var = Var{},
ob: Var = Var{ .x = -1 },
oe: Var = Var{},
alt: c_int = 0,
const Var = extern struct { x: c_int = 0, y: c_int = 0 };
};
const Line = [*]Glyph;
const Glyph = extern struct {
u: Rune = 0,
mode: c_ushort = 0,
fg: u32 = 0,
bg: u32 = 0,
};
const TCursor = extern struct {
attr: Glyph = Glyph{},
x: c_int = 0,
y: c_int = 0,
state: u8 = 0,
};
const histsize = 2000;
const Term = extern struct {
row: c_int = 0,
col: c_int = 0,
line: [*]Line = undefined,
alt: [*]Line = undefined,
hist: [histsize]Line = undefined,
histi: c_int = 0,
scr: c_int = 0,
dirty: [*]c_int = undefined,
c: TCursor = TCursor{},
ocx: c_int = 0,
ocy: c_int = 0,
top: c_int = 0,
bot: c_int = 0,
mode: c_int = 0,
esc: c_int = 0,
trantbl: [4]u8 = [_]u8{0} ** 4,
charset: c_int = 0,
icharset: c_int = 0,
tabs: [*]c_int = undefined,
lastc: Rune = 0,
};
export var term: Term = Term{};
export var sel: Selection = Selection{};
export var cmdfd: os.fd_t = 0;
export var iofd: os.fd_t = 1;
export var pid: os.pid_t = 0;
export fn xwrite(fd: os.fd_t, str: [*]const u8, len: usize) isize {
const file = fs.File{ .handle = fd, .io_mode = io.mode };
file.writeAll(str[0..len]) catch return -1;
return @intCast(isize, len);
}
export fn xstrdup(s: [*:0]u8) [*:0]u8 {
const len = mem.lenZ(s);
const res = heap.c_allocator.allocSentinel(u8, len, 0) catch std.debug.panic("strdup failed", .{});
mem.copy(u8, res, s[0..len]);
return res.ptr;
}
export fn utf8decode(bytes: [*]const u8, u: *u32, clen: usize) usize {
const slice = bytes[0..clen];
u.* = 0xFFFD;
if (slice.len == 0)
return 0;
const len = unicode.utf8ByteSequenceLength(slice[0]) catch return 0;
if (clen < len)
return 0;
u.* = unicode.utf8Decode(slice[0..len]) catch return 0;
return len;
}
export fn utf8encode(u: u32, out: [*]u8) usize {
const codepoint = math.cast(u21, u) catch return 0;
return unicode.utf8Encode(codepoint, out[0..4]) catch return 0;
}
export fn base64dec(src: [*:0]const u8) [*:0]u8 {
const len = mem.lenZ(src);
const size = base64.standard_decoder.calcSize(src[0..len]) catch unreachable;
const res = heap.c_allocator.allocSentinel(u8, size, 0) catch std.debug.panic("strdup failed", .{});
base64.standard_decoder.decode(res, src[0..len]) catch unreachable;
return res.ptr;
}
fn tline(y: c_int) Line {
if (y < term.scr)
return term.hist[@intCast(usize, @mod(y + term.histi - term.scr + histsize + 1, histsize))];
return term.line[@intCast(usize, y - term.scr)];
}
export fn tlinelen(y: c_int) c_int {
var i = @intCast(usize, term.col);
if (tline(y)[i - 1].mode & ATTR_WRAP != 0)
return @intCast(c_int, i);
while (i > 0 and tline(y)[i - 1].u == ' ')
i -= 1;
return @intCast(c_int, i);
}
export fn tmoveto(x: c_int, y: c_int) void {
const miny = if (term.c.state & CURSOR_ORIGIN != 0) term.top else 0;
const maxy = if (term.c.state & CURSOR_ORIGIN != 0) term.bot else term.row - 1;
term.c.state &= ~CURSOR_WRAPNEXT;
term.c.x = math.clamp(x, 0, term.col - 1);
term.c.y = math.clamp(y, miny, maxy);
}
export fn tmoveato(x: c_int, y: c_int) void {
tmoveto(x, y + if (term.c.state & CURSOR_ORIGIN != 0) term.top else 0);
}
export fn tsetdirt(_top: c_int, _bot: c_int) void {
const top = math.clamp(_top, 0, term.row - 1);
const bot = math.clamp(_bot, 0, term.row - 1);
var i = @intCast(usize, top);
while (i <= bot) : (i += 1)
term.dirty[i] = 1;
}
export fn tprinter(s: [*]const u8, len: usize) void {
if (iofd == 0)
return;
const file = fs.File{ .handle = iofd, .io_mode = io.mode };
file.writeAll(s[0..len]) catch |err| {
debug.warn("Error writing to output file {}\n", .{err});
file.close();
iofd = 0;
};
}
export fn selclear() void {
if (sel.ob.x == -1)
return;
sel.mode = SEL_IDLE;
sel.ob.x = -1;
tsetdirt(sel.nb.y, sel.ne.y);
}
const word_delimiters = [_]u32{' '};
fn isdelim(u: u32) bool {
return mem.indexOfScalar(u32, &word_delimiters, u) != null;
}
fn between(x: var, a: var, b: var) bool {
return a <= x and x <= b;
}
export fn selsnap(x: *c_int, y: *c_int, direction: c_int) void {
switch (sel.snap) {
// Snap around if the word wraps around at the end or
// beginning of a line.
SNAP_WORD => {
var prevgb = tline(y.*)[@intCast(usize, x.*)];
var prevdelim = isdelim(prevgb.u);
while (true) {
var newx = x.* + direction;
var newy = y.*;
if (!between(newx, 0, term.col - 1)) {
newy += direction;
newx = @mod(newx + term.col, term.col);
if (!between(newy, 0, term.row - 1))
break;
const yt = if (direction > 0) y.* else newy;
const xt = if (direction > 0) x.* else newx;
if (tline(yt)[@intCast(usize, xt)].mode & ATTR_WRAP == 0)
break;
}
if (newx >= tlinelen(newy))
break;
const gb = tline(newy)[@intCast(usize, newx)];
const delim = isdelim(gb.u);
if (gb.mode & ATTR_WDUMMY == 0 and (delim != prevdelim or
(delim and gb.u != prevgb.u)))
{
break;
}
x.* = newx;
y.* = newy;
prevgb = gb;
prevdelim = delim;
}
},
// Snap around if the the previous line or the current one
// has set ATTR_WRAP at its end. Then the whole next or
// previous line will be selected.
SNAP_LINE => {
x.* = if (direction < 0) 0 else term.col - 1;
if (direction < 0) {
while (y.* > 0) : (y.* += direction) {
if (tline(y.* - 1)[@intCast(usize, term.col - 1)].mode & ATTR_WRAP == 0)
break;
}
} else if (direction > 0) {
while (y.* < term.row - 1) : (y.* += direction) {
if (tline(y.*)[@intCast(usize, term.col - 1)].mode & ATTR_WRAP == 0)
break;
}
}
},
else => {},
}
}
export fn selnormalize() void {
if (sel.type == SEL_REGULAR and sel.ob.y != sel.oe.y) {
sel.nb.x = if (sel.ob.y < sel.oe.y) sel.ob.x else sel.oe.x;
sel.ne.x = if (sel.ob.y < sel.oe.y) sel.oe.x else sel.ob.x;
} else {
sel.nb.x = math.min(sel.ob.x, sel.oe.x);
sel.ne.x = math.max(sel.ob.x, sel.oe.x);
}
sel.nb.y = math.min(sel.ob.y, sel.oe.y);
sel.ne.y = math.max(sel.ob.y, sel.oe.y);
selsnap(&sel.nb.x, &sel.nb.y, -1);
selsnap(&sel.ne.x, &sel.ne.y, 1);
// expand selection over line breaks
if (sel.type == SEL_RECTANGULAR)
return;
const i = tlinelen(sel.nb.y);
if (i < sel.nb.x)
sel.nb.x = i;
if (tlinelen(sel.ne.y) <= sel.ne.x)
sel.ne.x = term.col - 1;
}
export fn selscroll(orig: c_int, n: c_int) void {
if (sel.ob.x == -1)
return;
if (between(sel.nb.y, orig, term.bot) != between(sel.ne.y, orig, term.bot)) {
selclear();
} else if (between(sel.nb.y, orig, term.bot)) {
sel.ob.y += n;
sel.oe.y += n;
if (sel.ob.y < term.top or sel.ob.y > term.bot or
sel.oe.y < term.top or sel.oe.y > term.bot)
{
selclear();
} else {
selnormalize();
}
}
}
fn is_set(flag: var) bool {
return term.mode & flag != 0;
}
export fn selstart(col: c_int, row: c_int, snap: c_int) void {
selclear();
sel.mode = SEL_EMPTY;
sel.type = SEL_REGULAR;
sel.alt = @boolToInt(is_set(MODE_ALTSCREEN));
sel.snap = snap;
sel.oe.x = col;
sel.ob.x = col;
sel.oe.y = row;
sel.ob.y = row;
selnormalize();
if (sel.snap != 0)
sel.mode = SEL_READY;
tsetdirt(sel.nb.y, sel.ne.y);
}
export fn selextend(col: c_int, row: c_int, _type: c_int, done: c_int) void {
if (sel.mode == SEL_IDLE)
return;
if (done != 0 and sel.mode == SEL_EMPTY) {
selclear();
return;
}
const oldey = sel.oe.y;
const oldex = sel.oe.x;
const oldsby = sel.nb.y;
const oldsey = sel.ne.y;
const oldtype = sel.type;
sel.oe.x = col;
sel.oe.y = row;
selnormalize();
sel.type = _type;
if (oldey != sel.oe.y or oldex != sel.oe.x or oldtype != sel.type or sel.mode == SEL_EMPTY)
tsetdirt(math.min(sel.nb.y, oldsby), math.max(sel.ne.y, oldsey));
sel.mode = if (done != 0) SEL_IDLE else SEL_READY;
}
export fn selected(x: c_int, y: c_int) c_int {
if (sel.mode == SEL_EMPTY or sel.ob.x == -1 or
sel.alt != @boolToInt(is_set(MODE_ALTSCREEN)))
return 0;
if (sel.type == SEL_RECTANGULAR)
return @boolToInt(between(y, sel.nb.y, sel.ne.y) and
between(x, sel.nb.x, sel.ne.x));
return @boolToInt(between(y, sel.nb.y, sel.ne.y) and
(y != sel.nb.y or x >= sel.nb.x) and
(y != sel.ne.y or x <= sel.ne.x));
}
export fn tputtab(_n: c_int) void {
var n = _n;
var x: usize = @intCast(usize, term.c.x);
if (n > 0) {
while (x < term.col and n != 0) : (n -= 1) {
x += 1;
while (x < term.col and term.tabs[x] == 0) : (x += 1) {}
}
} else if (n < 0) {
while (x > 0 and n != 0) : (n += 1) {
x -= 1;
while (x > 0 and term.tabs[x] == 0) : (x -= 1) {}
}
}
term.c.x = math.clamp(@intCast(c_int, x), 0, term.col - 1);
}
export fn tclearregion(_x1: c_int, _y1: c_int, _x2: c_int, _y2: c_int) void {
const x1 = math.clamp(math.min(_x1, _x2), 0, term.col - 1);
const x2 = math.clamp(math.max(_x1, _x2), 0, term.col - 1);
const y1 = math.clamp(math.min(_y1, _y2), 0, term.row - 1);
const y2 = math.clamp(math.max(_y1, _y2), 0, term.row - 1);
var y = @intCast(usize, y1);
while (y <= @intCast(usize, y2)) : (y += 1) {
term.dirty[y] = 1;
var x = @intCast(usize, x1);
while (x <= @intCast(usize, x2)) : (x += 1) {
const gp = &term.line[y][x];
if (selected(@intCast(c_int, x), @intCast(c_int, y)) != 0)
selclear();
gp.fg = term.c.attr.fg;
gp.bg = term.c.attr.bg;
gp.mode = 0;
gp.u = ' ';
}
}
}
export fn tscrolldown(orig: c_int, _n: c_int, copyhist: c_int) void {
const n = math.clamp(_n, 0, term.bot - orig + 1);
if (copyhist != 0) {
term.histi = @mod(term.histi - 1 + histsize, histsize);
mem.swap(
Line,
&term.hist[@intCast(usize, term.histi)],
&term.line[@intCast(usize, term.bot)],
);
}
tsetdirt(orig, term.bot - n);
tclearregion(0, term.bot - n + 1, term.col - 1, term.bot);
var i = term.bot;
while (i >= orig + n) : (i -= 1) {
mem.swap(
Line,
&term.line[@intCast(usize, i)],
&term.line[@intCast(usize, i - n)],
);
}
if (term.scr == 0)
selscroll(orig, n);
}
export fn tscrollup(orig: c_int, _n: c_int, copyhist: c_int) void {
const n = math.clamp(_n, 0, term.bot - orig + 1);
if (copyhist != 0) {
term.histi = @mod(term.histi + 1, histsize);
mem.swap(
Line,
&term.hist[@intCast(usize, term.histi)],
&term.line[@intCast(usize, orig)],
);
}
if (term.scr > 0 and term.scr < histsize)
term.scr = math.min(term.scr + n, histsize - 1);
tclearregion(0, orig, term.col - 1, orig + n - 1);
tsetdirt(orig + n, term.bot);
var i = orig;
while (i <= term.bot - n) : (i += 1) {
mem.swap(
Line,
&term.line[@intCast(usize, i)],
&term.line[@intCast(usize, i + n)],
);
}
if (term.scr == 0)
selscroll(orig, -n);
}
export fn tattrset(attr: c_int) c_int {
var i: usize = 0;
while (i < term.row - 1) : (i += 1) {
var j: usize = 0;
while (j < term.col - 1) : (j += 1) {
if (term.line[i][j].mode & @intCast(c_ushort, attr) != 0)
return 1;
}
}
return 0;
}
export fn tsetdirtattr(attr: c_int) void {
var i: usize = 0;
while (i < term.row - 1) : (i += 1) {
var j: usize = 0;
while (j < term.col - 1) : (j += 1) {
if (term.line[i][j].mode & @intCast(c_ushort, attr) != 0) {
tsetdirt(@intCast(c_int, i), @intCast(c_int, i));
break;
}
}
}
}
export fn tcursor(mode: c_int) void {
const Static = struct {
var cur: [2]TCursor = undefined;
};
const alt = @boolToInt(is_set(MODE_ALTSCREEN));
if (mode == CURSOR_SAVE) {
Static.cur[alt] = term.c;
} else if (mode == CURSOR_LOAD) {
term.c = Static.cur[alt];
tmoveto(Static.cur[alt].x, Static.cur[alt].y);
}
}
export fn ttyhangup() void {
// Send SIGHUP to shell
os.kill(pid, os.SIGHUP) catch unreachable;
}
export fn tfulldirt() void {
tsetdirt(0, term.row - 1);
}
export fn tisaltscr() c_int {
return @boolToInt(is_set(MODE_ALTSCREEN));
}
export fn tswapscreen() void {
mem.swap([*]Line, &term.line, &term.alt);
term.mode ^= MODE_ALTSCREEN;
tfulldirt();
}
export fn tnewline(first_col: c_int) void {
var y = term.c.y;
if (y == term.bot) {
tscrollup(term.top, 1, 1);
} else {
y += 1;
}
tmoveto(if (first_col != 0) 0 else term.c.x, y);
}
export fn tdeletechar(_n: c_int) void {
const n = math.clamp(_n, 0, term.col - term.c.x);
const dst = @intCast(usize, term.c.x);
const src = @intCast(usize, term.c.x + n);
const size = @intCast(usize, term.col) - src;
const line = term.line[@intCast(usize, term.c.y)];
mem.copy(Glyph, (line + dst)[0..size], (line + src)[0..size]);
tclearregion(term.col - n, term.c.y, term.col - 1, term.c.y);
}
export fn tinsertblank(_n: c_int) void {
const n = math.clamp(_n, 0, term.col - term.c.x);
const dst = @intCast(usize, term.c.x + n);
const src = @intCast(usize, term.c.x);
const size = @intCast(usize, term.col) - dst;
const line = term.line[@intCast(usize, term.c.y)];
mem.copyBackwards(Glyph, (line + dst)[0..size], (line + src)[0..size]);
tclearregion(@intCast(c_int, src), term.c.y, @intCast(c_int, dst - 1), term.c.y);
}
export fn tinsertblankline(n: c_int) void {
if (between(term.c.y, term.top, term.bot))
tscrolldown(term.c.y, n, 0);
}
export fn tdeleteline(n: c_int) void {
if (between(term.c.y, term.top, term.bot))
tscrollup(term.c.y, n, 0);
} | st.zig |
const std = @import("std");
const root = @import("root");
const mem = std.mem;
const assert = std.debug.assert;
const Allocator = mem.Allocator;
// const ArrayList = std.ArrayList;
const ByteList = std.ArrayListAlignedUnmanaged([]u8, null);
const GlobalAlloc = std.heap.GeneralPurposeAllocator(.{});
// general purpose global allocator for small allocations
var GlobalAllocator: GlobalAlloc = .{};
pub const Alloc = GlobalAllocator.allocator();
pub const Pages = std.heap.page_allocator;
const BumpState = struct {
const Self = @This();
ranges: ByteList,
next_size: usize,
fn init(initial_size: usize) Self {
return .{
.ranges = ByteList{},
.next_size = initial_size,
};
}
fn allocate(bump: *Self, mark: *Mark, alloc: Allocator, len: usize, ptr_align: u29, ret_addr: usize) Allocator.Error![]u8 {
if (mark.range < bump.ranges.items.len) {
const range = bump.ranges.items[mark.range];
const addr = @ptrToInt(range.ptr) + mark.index_in_range;
const adjusted_addr = mem.alignForward(addr, ptr_align);
const adjusted_index = mark.index_in_range + (adjusted_addr - addr);
const new_end_index = adjusted_index + len;
if (new_end_index <= range.len) {
mark.index_in_range = new_end_index;
return range[adjusted_index..new_end_index];
}
}
const size = @maximum(len, bump.next_size);
// Holy crap if you mess up the alignment, boyo the Zig UB detector
// will come for you with an assertion failure 10 frames deep into
// the standard library.
//
// In this case, since we're returning exactly the requested length every
// time, the len_align parameter is 1, so that we can get extra if
// our parent allocator so deigns it, but we don't care about the alignment
// we get from them. We still require pointer alignment, so we can
// safely return the allocation we're given to the caller.
//
// https://github.com/ziglang/zig/blob/master/lib/std/mem/Allocator.zig
const slice = try alloc.rawAlloc(size, ptr_align, 1, ret_addr);
try bump.ranges.append(alloc, slice);
// grow the next arena, but keep it to at most 1GB please
bump.next_size = size * 3 / 2;
bump.next_size = @minimum(1024 * 1024 * 1024, bump.next_size);
mark.range = bump.ranges.items.len - 1;
mark.index_in_range = len;
return slice[0..len];
}
};
pub const Mark = struct {
range: usize,
index_in_range: usize,
pub const ZERO: @This() = .{ .range = 0, .index_in_range = 0 };
};
pub const Bump = struct {
const Self = @This();
bump: BumpState,
mark: Mark,
alloc: Allocator,
pub fn init(initial_size: usize, alloc: Allocator) Self {
return .{
.bump = BumpState.init(initial_size),
.mark = Mark.ZERO,
.alloc = alloc,
};
}
pub fn deinit(self: *Self) void {
for (self.ranges.items) |range| {
self.alloc.free(range);
}
self.ranges.deinit(self.alloc);
}
fn compareLessThan(context: void, left: []u8, right: []u8) bool {
_ = context;
return left.len > right.len;
}
pub fn resetAndKeepLargestArena(self: *Self) void {
const items = self.bump.ranges.items;
if (items.len == 0) {
return;
}
std.sort.insertionSort([]u8, items, {}, compareLessThan);
for (items[1..]) |*range| {
self.alloc.free(range.*);
range.* = &.{};
}
self.bump.ranges.items.len = 1;
self.mark = Mark.ZERO;
}
pub fn allocator(self: *Self) Allocator {
const resize = Allocator.NoResize(Self).noResize;
const free = Allocator.NoOpFree(Self).noOpFree;
return Allocator.init(self, Self.allocate, resize, free);
}
fn allocate(
self: *Self,
len: usize,
ptr_align: u29,
len_align: u29,
ret_addr: usize,
) Allocator.Error![]u8 {
_ = len_align;
return self.bump.allocate(
&self.mark,
self.alloc,
len,
ptr_align,
ret_addr,
);
}
};
pub const Temp = TempAlloc.allocator;
pub threadlocal var TempMark: Mark = Mark.ZERO;
const TempAlloc = struct {
const InitialSize = if (@hasDecl(root, "liu_TempAlloc_InitialSize"))
root.liu_TempAlloc_InitialSize
else
256 * 1024;
threadlocal var bump = BumpState.init(InitialSize);
const allocator = Allocator.init(@intToPtr(*anyopaque, 1), alloc, resize, free);
const resize = Allocator.NoResize(anyopaque).noResize;
const free = Allocator.NoOpFree(anyopaque).noOpFree;
fn alloc(
_: *anyopaque,
len: usize,
ptr_align: u29,
len_align: u29,
ret_addr: usize,
) Allocator.Error![]u8 {
_ = len_align;
return bump.allocate(&TempMark, Pages, len, ptr_align, ret_addr);
}
};
pub const Slab = SlabAlloc.allocator;
pub fn slabFrameBoundary() void {
if (!std.debug.runtime_safety) return;
const value = @atomicLoad(u64, &SlabAlloc.next, .SeqCst);
SlabAlloc.frame_begin = value;
}
const SlabAlloc = struct {
// Naughty dog-inspired allocator, takes 2MB chunks from a pool, and its
// ownership of chunks does not outlive the frame boundary.
const SlabCount = if (@hasDecl(root, "liu_SlabAlloc_SlabCount"))
root.liu_SlabAlloc_SlabCount
else
1024;
const page = [4096]u8;
var frame_begin: if (std.debug.runtime_safety) ?u64 else void = if (std.debug.runtime_safety)
null
else {};
var next: usize = 0;
var slab_begin: [*]align(1024) page = undefined;
pub fn globalInit() !void {
assert(next == 0);
if (std.debug.runtime_safety) {
assert(frame_begin == null);
}
const slabs = try Pages.alignedAlloc(page, SlabCount, 1024);
slab_begin = slabs.ptr;
}
pub fn getMem() *[4096]u8 {
const out = @atomicRmw(u64, &SlabAlloc.next, .Add, 1, .SeqCst);
if (std.debug.runtime_safety) {
if (frame_begin) |begin| {
assert(begin - out < SlabCount);
}
}
return &slab_begin[out % SlabCount];
}
};
test "Slab" {
try SlabAlloc.globalInit();
slabFrameBoundary();
} | src/liu/allocators.zig |
const std = @import("std");
const Edge = @import("edge.zig").Edge;
pub const Rect = struct {
x: f32 = 0,
y: f32 = 0,
w: f32 = 0,
h: f32 = 0,
};
pub const RectI = struct {
x: i32 = 0,
y: i32 = 0,
w: i32 = 0,
h: i32 = 0,
pub fn right(self: RectI) i32 {
return self.x + self.w;
}
pub fn left(self: RectI) i32 {
return self.x;
}
pub fn top(self: RectI) i32 {
return self.y;
}
pub fn bottom(self: RectI) i32 {
return self.y + self.h;
}
pub fn centerX(self: RectI) i32 {
return self.x + @divTrunc(self.w, 2);
}
pub fn centerY(self: RectI) i32 {
return self.y + @divTrunc(self.h, 2);
}
pub fn halfRect(self: RectI, edge: Edge) RectI {
return switch (edge) {
.top => RectI{ .x = self.x, .y = self.y, .w = self.w, .h = @divTrunc(self.h, 2) },
.bottom => RectI{ .x = self.x, .y = self.y + @divTrunc(self.h, 2), .w = self.w, .h = @divTrunc(self.h, 2) },
.left => RectI{ .x = self.x, .y = self.y, .w = @divTrunc(self.w, 2), .h = self.h },
.right => RectI{ .x = self.x + @divTrunc(self.w, 2), .y = self.y, .w = @divTrunc(self.w, 2), .h = self.h },
};
}
pub fn contract(self: *RectI, horiz: i32, vert: i32) void {
self.x += horiz;
self.y += vert;
self.w -= horiz * 2;
self.h -= vert * 2;
}
pub fn expandEdge(self: *RectI, edge: Edge, move_x: i32) void {
const amt = std.math.absInt(move_x) catch unreachable;
switch (edge) {
.top => {
self.y -= amt;
self.h += amt;
},
.bottom => {
self.h += amt;
},
.left => {
self.x -= amt;
self.w += amt;
},
.right => {
self.w += amt;
},
}
}
pub fn side(self: RectI, edge: Edge) i32 {
return switch (edge) {
.left => self.x,
.right => self.x + self.w,
.top => self.y,
.bottom => self.y + self.h,
};
}
pub fn contains(x: i32, y: i32) bool {
return r.x <= x and x < r.right() and r.y <= y and y < r.bottom();
}
}; | src/math/rect.zig |
const std = @import("std");
const fs = std.fs;
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = &gpa.allocator;
const input = try fs.cwd().readFileAlloc(allocator, "data/input_05_1.txt", std.math.maxInt(usize));
{ // Solution 1
var lines = std.mem.tokenize(input, "\n");
var max_id: i32 = 0;
while (lines.next()) |line| {
const trimmed = std.mem.trim(u8, line, " \r\n");
if (trimmed.len == 0)
break;
var cmin: i32 = 0;
var cmax: i32 = 128;
{var i: usize = 0; while (i < 7) : (i += 1) {
const mid = cmin + @divFloor(cmax - cmin, 2);
if (trimmed[i] == 'F') {
cmax = mid;
} else if (trimmed[i] == 'B') {
cmin = mid;
} else unreachable;
}}
std.debug.assert(cmin == cmax - 1);
var rmin: i32 = 0;
var rmax: i32 = 8;
{var i: usize = 7; while (i < 10) : (i += 1) {
const mid = rmin + @divFloor(rmax - rmin, 2);
if (trimmed[i] == 'L') {
rmax = mid;
} else if (trimmed[i] == 'R') {
rmin = mid;
} else unreachable;
}}
std.debug.assert(rmin == rmax - 1);
const id = cmin * 8 + rmin;
max_id = std.math.max(id, max_id);
}
std.debug.print("Day 05 - Solution 1: {}\n", .{max_id});
}
{ // Solution 2
var bitmap = [_]u64 {0} ** (128 * 8 / 64);
var lines = std.mem.tokenize(input, "\n");
var min_id: i32 = 128 * 8;
while (lines.next()) |line| {
const trimmed = std.mem.trim(u8, line, " \r\n");
if (trimmed.len == 0)
break;
var cmin: i32 = 0;
var cmax: i32 = 128;
{var i: usize = 0; while (i < 7) : (i += 1) {
const mid = cmin + @divFloor(cmax - cmin, 2);
if (trimmed[i] == 'F') {
cmax = mid;
} else if (trimmed[i] == 'B') {
cmin = mid;
} else unreachable;
}}
std.debug.assert(cmin == cmax - 1);
var rmin: i32 = 0;
var rmax: i32 = 8;
{var i: usize = 7; while (i < 10) : (i += 1) {
const mid = rmin + @divFloor(rmax - rmin, 2);
if (trimmed[i] == 'L') {
rmax = mid;
} else if (trimmed[i] == 'R') {
rmin = mid;
} else unreachable;
}}
std.debug.assert(rmin == rmax - 1);
const id = cmin * 8 + rmin;
const index = @intCast(usize, @divFloor(id, 64));
const shift = @intCast(u6, @mod(id, 64));
bitmap[index] |= @as(u64, 1) << shift;
min_id = std.math.min(id, min_id);
}
{ var id = min_id + 1; while (id < (128 * 8) - 1) : (id += 1) {
if (!isOccupied(bitmap[0..], id)) {
if (isOccupied(bitmap[0..], id + 1) and isOccupied(bitmap[0..], id - 1)) {
std.debug.print("Day 05 - Solution 2: {}\n", .{id});
break;
}
}
}}
}
}
fn isOccupied(bitmap: []u64, id: i32) bool {
const index = @intCast(usize, @divFloor(id, 64));
const shift = @intCast(u6, @mod(id, 64));
return (bitmap[index] & (@as(u64, 1) << shift)) != 0;
} | 2020/src/day_05.zig |
const std = @import("std");
const gfx = @import("gfx.zig");
const renderkit = @import("renderkit");
const gk = @import("gamekit.zig");
const math = gk.math;
const Texture = gfx.Texture;
pub const draw = struct {
pub var batcher: gfx.Batcher = undefined;
pub var fontbook: *gfx.FontBook = undefined;
var quad: math.Quad = math.Quad.init(0, 0, 1, 1, 1, 1);
var white_tex: Texture = undefined;
pub fn init() void {
white_tex = Texture.initSingleColor(0xFFFFFFFF);
batcher = gfx.Batcher.init(std.heap.c_allocator, 1000);
fontbook = gfx.FontBook.init(std.heap.c_allocator, 128, 128, .nearest) catch unreachable;
_ = fontbook.addFontMem("ProggyTiny", @embedFile("assets/ProggyTiny.ttf"), false);
fontbook.setSize(10);
}
pub fn deinit() void {
batcher.deinit();
white_tex.deinit();
fontbook.deinit();
}
/// binds a Texture to the Bindings in the Batchers DynamicMesh
pub fn bindTexture(texture: Texture, slot: c_uint) void {
batcher.mesh.bindImage(texture.img, slot);
}
/// unbinds a previously bound texture. All texture slots > 0 must be unbound manually!
pub fn unbindTexture(slot: c_uint) void {
batcher.mesh.bindImage(0, slot);
}
// Drawing
pub fn tex(texture: Texture, position: math.Vec2) void {
quad.setFill(texture.width, texture.height);
var mat = math.Mat32.initTransform(.{ .x = position.x, .y = position.y });
batcher.draw(texture, quad, mat, math.Color.white);
}
pub fn texScale(texture: Texture, position: math.Vec2, scale: f32) void {
quad.setFill(texture.width, texture.height);
var mat = math.Mat32.initTransform(.{ .x = position.x, .y = position.y, .sx = scale, .sy = scale });
batcher.draw(texture, quad, mat, math.Color.white);
}
pub fn texScaleOrigin(texture: Texture, x: f32, y: f32, scale: f32, ox: f32, oy: f32) void {
quad.setFill(texture.width, texture.height);
var mat = math.Mat32.initTransform(.{ .x = x, .y = y, .sx = scale, .sy = scale, .ox = ox, .oy = oy });
batcher.draw(texture, quad, mat, math.Color.white);
}
pub fn texScaleOriginRotation(texture: Texture, x: f32, y: f32, scale: f32, ox: f32, oy: f32, angle: f32) void {
quad.setFill(texture.width, texture.height);
var mat = math.Mat32.initTransform(.{ .x = x, .y = y, .sx = scale, .sy = scale, .ox = ox, .oy = oy, .angle = angle });
batcher.draw(texture, quad, mat, math.Color.white);
}
pub fn texMatrix(texture: Texture, mat: math.Mat32) void {
quad.setFill(texture.width, texture.height);
batcher.draw(texture, quad, mat, math.Color.white);
}
pub fn texViewport(texture: Texture, viewport: math.RectI, transform: math.Mat32) void {
quad.setImageDimensions(texture.width, texture.height);
quad.setViewportRectI(viewport);
batcher.draw(texture, quad, transform, math.Color.white);
}
pub fn text(str: []const u8, x: f32, y: f32, fb: ?*gfx.FontBook) void {
var book = fb orelse fontbook;
// TODO: dont hardcode scale as 4
var matrix = math.Mat32.initTransform(.{ .x = x, .y = y, .sx = 2, .sy = 2 });
var fons_quad = book.getQuad();
var iter = book.getTextIterator(str);
while (book.textIterNext(&iter, &fons_quad)) {
quad.positions[0] = .{ .x = fons_quad.x0, .y = fons_quad.y0 };
quad.positions[1] = .{ .x = fons_quad.x1, .y = fons_quad.y0 };
quad.positions[2] = .{ .x = fons_quad.x1, .y = fons_quad.y1 };
quad.positions[3] = .{ .x = fons_quad.x0, .y = fons_quad.y1 };
quad.uvs[0] = .{ .x = fons_quad.s0, .y = fons_quad.t0 };
quad.uvs[1] = .{ .x = fons_quad.s1, .y = fons_quad.t0 };
quad.uvs[2] = .{ .x = fons_quad.s1, .y = fons_quad.t1 };
quad.uvs[3] = .{ .x = fons_quad.s0, .y = fons_quad.t1 };
batcher.draw(book.texture.?, quad, matrix, math.Color{ .value = iter.color });
}
}
pub fn textOptions(str: []const u8, fb: ?*gfx.FontBook, options: struct { x: f32, y: f32, rot: f32 = 0, sx: f32 = 1, sy: f32 = 1, alignment: gfx.FontBook.Align = .default, color: math.Color = math.Color.White }) void {
var book = fb orelse fontbook;
var matrix = math.Mat32.initTransform(.{ .x = options.x, .y = options.y, .angle = options.rot, .sx = options.sx, .sy = options.sy });
book.setAlign(options.alignment);
var fons_quad = book.getQuad();
var iter = book.getTextIterator(str);
while (book.textIterNext(&iter, &fons_quad)) {
quad.positions[0] = .{ .x = fons_quad.x0, .y = fons_quad.y0 };
quad.positions[1] = .{ .x = fons_quad.x1, .y = fons_quad.y0 };
quad.positions[2] = .{ .x = fons_quad.x1, .y = fons_quad.y1 };
quad.positions[3] = .{ .x = fons_quad.x0, .y = fons_quad.y1 };
quad.uvs[0] = .{ .x = fons_quad.s0, .y = fons_quad.t0 };
quad.uvs[1] = .{ .x = fons_quad.s1, .y = fons_quad.t0 };
quad.uvs[2] = .{ .x = fons_quad.s1, .y = fons_quad.t1 };
quad.uvs[3] = .{ .x = fons_quad.s0, .y = fons_quad.t1 };
batcher.draw(book.texture.?, quad, matrix, options.color);
}
}
pub fn point(position: math.Vec2, size: f32, color: math.Color) void {
quad.setFill(size, size);
const offset = if (size == 1) 0 else size * 0.5;
var mat = math.Mat32.initTransform(.{ .x = position.x, .y = position.y, .ox = offset, .oy = offset });
batcher.draw(white_tex, quad, mat, color);
}
pub fn line(start: math.Vec2, end: math.Vec2, thickness: f32, color: math.Color) void {
quad.setFill(1, 1);
const angle = start.angleBetween(end);
const length = start.distance(end);
var mat = math.Mat32.initTransform(.{ .x = start.x, .y = start.y, .angle = angle, .sx = length, .sy = thickness });
batcher.draw(white_tex, quad, mat, color);
}
pub fn rect(position: math.Vec2, width: f32, height: f32, color: math.Color) void {
quad.setFill(width, height);
var mat = math.Mat32.initTransform(.{ .x = position.x, .y = position.y });
batcher.draw(white_tex, quad, mat, color);
}
pub fn hollowRect(position: math.Vec2, width: f32, height: f32, thickness: f32, color: math.Color) void {
const tr = math.Vec2{ .x = position.x + width, .y = position.y };
const br = math.Vec2{ .x = position.x + width, .y = position.y + height };
const bl = math.Vec2{ .x = position.x, .y = position.y + height };
line(position, tr, thickness, color);
line(tr, br, thickness, color);
line(br, bl, thickness, color);
line(bl, position, thickness, color);
}
pub fn circle(center: math.Vec2, radius: f32, thickness: f32, resolution: i32, color: math.Color) void {
quad.setFill(white_tex.width, white_tex.height);
var last = math.Vec2.init(1, 0).scale(radius);
var last_p = last.orthogonal();
var i: usize = 0;
while (i <= resolution) : (i += 1) {
const at = math.Vec2.angleToVec(@intToFloat(f32, i) * std.math.pi * 0.5 / @intToFloat(f32, resolution), radius);
const at_p = at.orthogonal();
line(center.addv(last), center.addv(at), thickness, color);
line(center.subv(last), center.subv(at), thickness, color);
line(center.addv(last_p), center.addv(at_p), thickness, color);
line(center.subv(last_p), center.subv(at_p), thickness, color);
last = at;
last_p = at_p;
}
}
pub fn hollowPolygon(verts: []const math.Vec2, thickness: f32, color: math.Color) void {
var i: usize = 0;
while (i < verts.len - 1) : (i += 1) {
line(verts[i], verts[i + 1], thickness, color);
}
line(verts[verts.len - 1], verts[0], thickness, color);
}
}; | gamekit/draw.zig |
const std = @import("std");
const assert = debug.assert;
fn escape(comptime literal: []const u8) -> []const u8 {
"\x1b[" ++ literal
}
pub const ResetAll = escape("c");
pub const Color = enum {
Simple: u8,
Ansi: u8,
TrueColor: struct { r: u8, g: u8, b: u8 },
};
pub const Black = Color.Simple { 30 };
pub const Red = Color.Simple { 31 };
pub const Green = Color.Simple { 32 };
pub const Yellow = Color.Simple { 33 };
pub const Blue = Color.Simple { 34 };
pub const Magenta = Color.Simple { 35 };
pub const Cyan = Color.Simple { 36 };
pub const LightGray = Color.Simple { 37 };
pub const Default = Color.Simple { 39 };
pub const DarkGray = Color.Simple { 90 };
pub const LightRed = Color.Simple { 91 };
pub const LightGreen = Color.Simple { 92 };
pub const LightYellow = Color.Simple { 93 };
pub const LightBlue = Color.Simple { 94 };
pub const LightMagenta = Color.Simple { 95 };
pub const LightCyan = Color.Simple { 96 };
pub const White = Color.Simple { 97 };
pub fn Color216(r: u8, g: u8, b: u8) -> Color {
assert(r <= 5 and g <= 5 and b <= 5);
Color.Ansi { 16 + 36 * r + 6 * g + b }
}
pub fn GrayScale24(shade: u8) -> Color {
assert(shade < 24);
Color.Ansi { 0xe8 + shade }
}
pub fn Color256(code: u8) -> Color {
Color.Ansi { code }
}
pub fn TrueColor(r: u8, g: u8, b: u8) -> Color {
Color.TrueColor { .r = r, .g = g, .b = b }
}
// If we had a @stringify operator we could do most everything we need to.
// The only slightly annoying thing would runtime Color's but we could utilize buffers and
// the like somehow. This case less common in my mind.
//
// var buffer: [3]u8 = undefined;
fn u8ToLit(comptime x: u8) -> []const u8 {
// if (x < 10) {
// buffer[0] = x + '0';
// buffer[0..1]
// } else if (x < 100) {
// buffer[0] = (x % 10) + '0';
// buffer[1] = (x / 10) + '0';
// buffer[0..2]
// } else {
// buffer[0] = (x % 10) + '0';
// buffer[1] = ((x / 10) % 10) + '0';
// buffer[2] = (x / 100) + '0';
// buffer[0..3]
// }
"_"
}
pub fn Fg(comptime color: Color) -> []const u8 {
comptime switch (color) {
Color.Simple => |v| escape(u8ToLit(v) ++ "m"),
Color.Ansi => |v| escape("38;5;" ++ u8ToLit(v) ++ "m"),
Color.TrueColor => |v| escape("38;2;" ++ u8ToLit(v.r) ++ ";" ++ u8ToLit(v.g) ++
";" ++ u8ToLit(v.b) ++ "m"),
}
}
pub fn Bg(comptime color: Color) -> []const u8 {
comptime switch (color) {
Color.Simple => |v| escape(u8ToLit(v + 10) ++ "m"),
Color.Ansi => |v| escape("48;5;" ++ u8ToLit(v) ++ "m"),
Color.TrueColor => |v| escape("48;2;" ++ u8ToLit(v.r) ++ ";" ++ u8ToLit(v.g) ++
";" ++ u8ToLit(v.b) ++ "m"),
}
}
pub const Attr = struct {
pub const Reset = escape("m");
pub const Bright = escape("1m");
pub const Dim = escape("2m");
pub const Italic = escape("3m");
pub const Underline = escape("4m");
pub const Blink = escape("5m");
pub const Invert = escape("7m");
pub const Crossed = escape("9m");
pub const NoBright = escape("21m");
pub const NoDim = escape("22m");
pub const NoItalic = escape("23m");
pub const NoUnderline = escape("24m");
pub const NoBlink = escape("25m");
pub const NoInvert = escape("27m");
pub const NoCrossed = escape("29m");
pub const Framed = escape("51m");
};
pub const Erase = struct {
pub const Down = escape("J");
pub const Up = escape("1J");
pub const Screen = escape("2J");
pub const EndOfLine = escape("K");
pub const StartOfLine = escape("1K");
pub const Line = escape("2K");
};
pub const Cursor = struct {
pub const Hide = escape("?25hl");
pub const Show = escape("?25h");
pub const Save = escape("s");
pub const Restore = escape("u");
// The following are not-compile-time known and should be used via a standard println.
//
// This requires a buffer or a separate call (not using printf).
pub fn Goto(x: u8, y: u8) -> []const u8 {
assert(x != 0 and y != 0);
escape("{};{}H", x, y)
}
pub fn Up(amount: u8) -> []const u8 {
escape("{}A", amount);
}
pub fn Down(amount: u8) -> []const u8 {
escape("{}B", amount)
}
pub fn Right(amount: u8) -> []const u8 {
escape("{}C", amount)
}
pub fn Left(amount: u8) -> []const u8 {
escape("{}D", amount)
}
};
pub const Screen = struct {
pub const Save = escape("?47h");
pub const Restore = escape("?47l");
};
// Add a closest match function to the standard 256 color mappings.
//
// Allow specifying either the 16-color standard, 216-color, or True-Color as the
// parameter space output. | ansiz.zig |
const std = @import("std");
const print = std.debug.print;
const input_file = @embedFile("input.txt");
const Passport = std.StringHashMap([]const u8);
fn parseInput(allocator: *std.mem.Allocator) ![]Passport {
var passports = std.ArrayList(Passport).init(allocator);
errdefer passports.deinit();
var input = std.mem.split(input_file, "\n\n");
while (input.next()) |data| {
var passport = Passport.init(allocator);
errdefer passport.deinit();
var key_value_pairs = std.mem.tokenize(data, " \n");
while (key_value_pairs.next()) |key_value| {
const index = std.mem.indexOfScalar(u8, key_value, ':').?;
const key = key_value[0..index];
const value = key_value[(index + 1)..];
try passport.put(key, value);
}
try passports.append(passport);
}
return passports.toOwnedSlice();
}
const required_fields = [_][]const u8{ "byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid" };
fn hasRequiredFields(passport: Passport) bool {
for (required_fields) |field| {
if (!passport.contains(field)) return false;
}
return true;
}
fn inRange(value: []const u8, min: i32, max: i32) bool {
const int_value = std.fmt.parseInt(i32, value, 10) catch return false;
return int_value >= min and int_value <= max;
}
const validators = struct {
fn byr(value: []const u8) bool {
return inRange(value, 1920, 2002);
}
fn iyr(value: []const u8) bool {
return inRange(value, 2010, 2020);
}
fn eyr(value: []const u8) bool {
return inRange(value, 2020, 2030);
}
fn hgt(value: []const u8) bool {
if (std.mem.endsWith(u8, value, "cm")) {
return inRange(value[0 .. value.len - 2], 150, 193);
}
if (std.mem.endsWith(u8, value, "in")) {
return inRange(value[0 .. value.len - 2], 59, 76);
}
return false;
}
fn hcl(value: []const u8) bool {
if ((value[0] == '#') and (value.len == 7)) {
_ = std.fmt.parseInt(u32, value[1..], 16) catch return false;
return true;
}
return false;
}
fn ecl(value: []const u8) bool {
const colors = [_][]const u8{ "amb", "blu", "brn", "gry", "grn", "hzl", "oth" };
for (colors) |color| {
if (std.mem.eql(u8, color, value)) return true;
}
return false;
}
fn pid(value: []const u8) bool {
if (value.len == 9) {
_ = std.fmt.parseInt(u32, value, 10) catch return false;
return true;
}
return false;
}
};
fn validate(passport: Passport) bool {
inline for (required_fields) |field| {
const value = passport.get(field) orelse return false;
const valid = @field(validators, field)(value);
if (!valid) return false;
}
return true;
}
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
var arena = std.heap.ArenaAllocator.init(&gpa.allocator);
defer arena.deinit();
var passports = try parseInput(&arena.allocator);
var answer1: i32 = 0;
var answer2: i32 = 0;
for (passports) |passport| {
if (hasRequiredFields(passport)) answer1 += 1;
if (validate(passport)) answer2 += 1;
}
print("part 1: {}\n", .{answer1});
print("part 2: {}\n", .{answer2});
} | 2020/04/main.zig |
const std = @import("std");
const debug = std.debug;
const mem = std.mem;
const net = std.net;
const os = std.os;
const IO_Uring = std.os.linux.IO_Uring;
const logger = std.log.scoped(.io_helpers);
// TODO(vincent): make this dynamic
const max_connections = 128;
/// Manages a set of registered file descriptors.
/// The set size is fixed at compile time.
///
/// A client must acquire a file descriptor to use it, and release it when it disconnects.
pub const RegisteredFileDescriptors = struct {
const Self = @This();
const State = enum {
used,
free,
};
fds: [max_connections]os.fd_t = [_]os.fd_t{-1} ** max_connections,
states: [max_connections]State = [_]State{.free} ** max_connections,
pub fn register(self: *Self, ring: *IO_Uring) !void {
logger.debug("REGISTERED FILE DESCRIPTORS, fds={d}", .{
self.fds,
});
try ring.register_files(self.fds[0..]);
}
pub fn update(self: *Self, ring: *IO_Uring) !void {
logger.debug("UPDATE FILE DESCRIPTORS, fds={d}", .{
self.fds,
});
try ring.register_files_update(0, self.fds[0..]);
}
pub fn acquire(self: *Self, fd: os.fd_t) ?i32 {
// Find a free slot in the states array
for (self.states) |*state, i| {
if (state.* == .free) {
// Slot is free, change its state and set the file descriptor.
state.* = .used;
self.fds[i] = fd;
return @intCast(i32, i);
}
} else {
return null;
}
}
pub fn release(self: *Self, index: i32) void {
const idx = @intCast(usize, index);
debug.assert(self.states[idx] == .used);
debug.assert(self.fds[idx] != -1);
self.states[idx] = .free;
self.fds[idx] = -1;
}
};
/// Creates a server socket, bind it and listen on it.
///
/// This enables SO_REUSEADDR so that we can have multiple listeners
/// on the same port, that way the kernel load balances connections to our workers.
pub fn createSocket(port: u16) !os.socket_t {
const sockfd = try os.socket(os.AF.INET6, os.SOCK.STREAM, 0);
errdefer os.close(sockfd);
// Enable reuseaddr if possible
os.setsockopt(
sockfd,
os.SOL.SOCKET,
os.SO.REUSEPORT,
&mem.toBytes(@as(c_int, 1)),
) catch {};
// Disable IPv6 only
try os.setsockopt(
sockfd,
os.IPPROTO.IPV6,
os.linux.IPV6.V6ONLY,
&mem.toBytes(@as(c_int, 0)),
);
const addr = try net.Address.parseIp6("::0", port);
try os.bind(sockfd, &addr.any, @sizeOf(os.sockaddr.in6));
try os.listen(sockfd, std.math.maxInt(u31));
return sockfd;
} | src/io.zig |
const ctz = @import("count0bits.zig");
const testing = @import("std").testing;
fn test__ctzdi2(a: u64, expected: i32) !void {
var x = @bitCast(i64, a);
var result = ctz.__ctzdi2(x);
try testing.expectEqual(expected, result);
}
test "ctzdi2" {
try test__ctzdi2(0x00000000_00000001, 0);
try test__ctzdi2(0x00000000_00000002, 1);
try test__ctzdi2(0x00000000_00000003, 0);
try test__ctzdi2(0x00000000_00000004, 2);
try test__ctzdi2(0x00000000_00000005, 0);
try test__ctzdi2(0x00000000_00000006, 1);
try test__ctzdi2(0x00000000_00000007, 0);
try test__ctzdi2(0x00000000_00000008, 3);
try test__ctzdi2(0x00000000_00000009, 0);
try test__ctzdi2(0x00000000_0000000A, 1);
try test__ctzdi2(0x00000000_0000000B, 0);
try test__ctzdi2(0x00000000_0000000C, 2);
try test__ctzdi2(0x00000000_0000000D, 0);
try test__ctzdi2(0x00000000_0000000E, 1);
try test__ctzdi2(0x00000000_0000000F, 0);
try test__ctzdi2(0x00000000_00000010, 4);
try test__ctzdi2(0x00000000_00000011, 0);
try test__ctzdi2(0x00000000_00000012, 1);
try test__ctzdi2(0x00000000_00000013, 0);
try test__ctzdi2(0x00000000_00000014, 2);
try test__ctzdi2(0x00000000_00000015, 0);
try test__ctzdi2(0x00000000_00000016, 1);
try test__ctzdi2(0x00000000_00000017, 0);
try test__ctzdi2(0x00000000_00000018, 3);
try test__ctzdi2(0x00000000_00000019, 0);
try test__ctzdi2(0x00000000_0000001A, 1);
try test__ctzdi2(0x00000000_0000001B, 0);
try test__ctzdi2(0x00000000_0000001C, 2);
try test__ctzdi2(0x00000000_0000001D, 0);
try test__ctzdi2(0x00000000_0000001E, 1);
try test__ctzdi2(0x00000000_0000001F, 0);
try test__ctzdi2(0x00000000_00000020, 5);
try test__ctzdi2(0x00000000_00000021, 0);
try test__ctzdi2(0x00000000_00000022, 1);
try test__ctzdi2(0x00000000_00000023, 0);
try test__ctzdi2(0x00000000_00000024, 2);
try test__ctzdi2(0x00000000_00000025, 0);
try test__ctzdi2(0x00000000_00000026, 1);
try test__ctzdi2(0x00000000_00000027, 0);
try test__ctzdi2(0x00000000_00000028, 3);
try test__ctzdi2(0x00000000_00000029, 0);
try test__ctzdi2(0x00000000_0000002A, 1);
try test__ctzdi2(0x00000000_0000002B, 0);
try test__ctzdi2(0x00000000_0000002C, 2);
try test__ctzdi2(0x00000000_0000002D, 0);
try test__ctzdi2(0x00000000_0000002E, 1);
try test__ctzdi2(0x00000000_0000002F, 0);
try test__ctzdi2(0x00000000_00000030, 4);
try test__ctzdi2(0x00000000_00000031, 0);
try test__ctzdi2(0x00000000_00000032, 1);
try test__ctzdi2(0x00000000_00000033, 0);
try test__ctzdi2(0x00000000_00000034, 2);
try test__ctzdi2(0x00000000_00000035, 0);
try test__ctzdi2(0x00000000_00000036, 1);
try test__ctzdi2(0x00000000_00000037, 0);
try test__ctzdi2(0x00000000_00000038, 3);
try test__ctzdi2(0x00000000_00000039, 0);
try test__ctzdi2(0x00000000_0000003A, 1);
try test__ctzdi2(0x00000000_0000003B, 0);
try test__ctzdi2(0x00000000_0000003C, 2);
try test__ctzdi2(0x00000000_0000003D, 0);
try test__ctzdi2(0x00000000_0000003E, 1);
try test__ctzdi2(0x00000000_0000003F, 0);
try test__ctzdi2(0x00000000_00000040, 6);
try test__ctzdi2(0x00000000_00000041, 0);
try test__ctzdi2(0x00000000_00000042, 1);
try test__ctzdi2(0x00000000_00000043, 0);
try test__ctzdi2(0x00000000_00000044, 2);
try test__ctzdi2(0x00000000_00000045, 0);
try test__ctzdi2(0x00000000_00000046, 1);
try test__ctzdi2(0x00000000_00000047, 0);
try test__ctzdi2(0x00000000_00000048, 3);
try test__ctzdi2(0x00000000_00000049, 0);
try test__ctzdi2(0x00000000_0000004A, 1);
try test__ctzdi2(0x00000000_0000004B, 0);
try test__ctzdi2(0x00000000_0000004C, 2);
try test__ctzdi2(0x00000000_0000004D, 0);
try test__ctzdi2(0x00000000_0000004E, 1);
try test__ctzdi2(0x00000000_0000004F, 0);
try test__ctzdi2(0x00000000_00000050, 4);
try test__ctzdi2(0x00000000_00000051, 0);
try test__ctzdi2(0x00000000_00000052, 1);
try test__ctzdi2(0x00000000_00000053, 0);
try test__ctzdi2(0x00000000_00000054, 2);
try test__ctzdi2(0x00000000_00000055, 0);
try test__ctzdi2(0x00000000_00000056, 1);
try test__ctzdi2(0x00000000_00000057, 0);
try test__ctzdi2(0x00000000_00000058, 3);
try test__ctzdi2(0x00000000_00000059, 0);
try test__ctzdi2(0x00000000_0000005A, 1);
try test__ctzdi2(0x00000000_0000005B, 0);
try test__ctzdi2(0x00000000_0000005C, 2);
try test__ctzdi2(0x00000000_0000005D, 0);
try test__ctzdi2(0x00000000_0000005E, 1);
try test__ctzdi2(0x00000000_0000005F, 0);
try test__ctzdi2(0x00000000_00000060, 5);
try test__ctzdi2(0x00000000_00000061, 0);
try test__ctzdi2(0x00000000_00000062, 1);
try test__ctzdi2(0x00000000_00000063, 0);
try test__ctzdi2(0x00000000_00000064, 2);
try test__ctzdi2(0x00000000_00000065, 0);
try test__ctzdi2(0x00000000_00000066, 1);
try test__ctzdi2(0x00000000_00000067, 0);
try test__ctzdi2(0x00000000_00000068, 3);
try test__ctzdi2(0x00000000_00000069, 0);
try test__ctzdi2(0x00000000_0000006A, 1);
try test__ctzdi2(0x00000000_0000006B, 0);
try test__ctzdi2(0x00000000_0000006C, 2);
try test__ctzdi2(0x00000000_0000006D, 0);
try test__ctzdi2(0x00000000_0000006E, 1);
try test__ctzdi2(0x00000000_0000006F, 0);
try test__ctzdi2(0x00000000_00000070, 4);
try test__ctzdi2(0x00000000_00000071, 0);
try test__ctzdi2(0x00000000_00000072, 1);
try test__ctzdi2(0x00000000_00000073, 0);
try test__ctzdi2(0x00000000_00000074, 2);
try test__ctzdi2(0x00000000_00000075, 0);
try test__ctzdi2(0x00000000_00000076, 1);
try test__ctzdi2(0x00000000_00000077, 0);
try test__ctzdi2(0x00000000_00000078, 3);
try test__ctzdi2(0x00000000_00000079, 0);
try test__ctzdi2(0x00000000_0000007A, 1);
try test__ctzdi2(0x00000000_0000007B, 0);
try test__ctzdi2(0x00000000_0000007C, 2);
try test__ctzdi2(0x00000000_0000007D, 0);
try test__ctzdi2(0x00000000_0000007E, 1);
try test__ctzdi2(0x00000000_0000007F, 0);
try test__ctzdi2(0x00000000_00000080, 7);
try test__ctzdi2(0x00000000_00000081, 0);
try test__ctzdi2(0x00000000_00000082, 1);
try test__ctzdi2(0x00000000_00000083, 0);
try test__ctzdi2(0x00000000_00000084, 2);
try test__ctzdi2(0x00000000_00000085, 0);
try test__ctzdi2(0x00000000_00000086, 1);
try test__ctzdi2(0x00000000_00000087, 0);
try test__ctzdi2(0x00000000_00000088, 3);
try test__ctzdi2(0x00000000_00000089, 0);
try test__ctzdi2(0x00000000_0000008A, 1);
try test__ctzdi2(0x00000000_0000008B, 0);
try test__ctzdi2(0x00000000_0000008C, 2);
try test__ctzdi2(0x00000000_0000008D, 0);
try test__ctzdi2(0x00000000_0000008E, 1);
try test__ctzdi2(0x00000000_0000008F, 0);
try test__ctzdi2(0x00000000_00000090, 4);
try test__ctzdi2(0x00000000_00000091, 0);
try test__ctzdi2(0x00000000_00000092, 1);
try test__ctzdi2(0x00000000_00000093, 0);
try test__ctzdi2(0x00000000_00000094, 2);
try test__ctzdi2(0x00000000_00000095, 0);
try test__ctzdi2(0x00000000_00000096, 1);
try test__ctzdi2(0x00000000_00000097, 0);
try test__ctzdi2(0x00000000_00000098, 3);
try test__ctzdi2(0x00000000_00000099, 0);
try test__ctzdi2(0x00000000_0000009A, 1);
try test__ctzdi2(0x00000000_0000009B, 0);
try test__ctzdi2(0x00000000_0000009C, 2);
try test__ctzdi2(0x00000000_0000009D, 0);
try test__ctzdi2(0x00000000_0000009E, 1);
try test__ctzdi2(0x00000000_0000009F, 0);
try test__ctzdi2(0x00000000_000000A0, 5);
try test__ctzdi2(0x00000000_000000A1, 0);
try test__ctzdi2(0x00000000_000000A2, 1);
try test__ctzdi2(0x00000000_000000A3, 0);
try test__ctzdi2(0x00000000_000000A4, 2);
try test__ctzdi2(0x00000000_000000A5, 0);
try test__ctzdi2(0x00000000_000000A6, 1);
try test__ctzdi2(0x00000000_000000A7, 0);
try test__ctzdi2(0x00000000_000000A8, 3);
try test__ctzdi2(0x00000000_000000A9, 0);
try test__ctzdi2(0x00000000_000000AA, 1);
try test__ctzdi2(0x00000000_000000AB, 0);
try test__ctzdi2(0x00000000_000000AC, 2);
try test__ctzdi2(0x00000000_000000AD, 0);
try test__ctzdi2(0x00000000_000000AE, 1);
try test__ctzdi2(0x00000000_000000AF, 0);
try test__ctzdi2(0x00000000_000000B0, 4);
try test__ctzdi2(0x00000000_000000B1, 0);
try test__ctzdi2(0x00000000_000000B2, 1);
try test__ctzdi2(0x00000000_000000B3, 0);
try test__ctzdi2(0x00000000_000000B4, 2);
try test__ctzdi2(0x00000000_000000B5, 0);
try test__ctzdi2(0x00000000_000000B6, 1);
try test__ctzdi2(0x00000000_000000B7, 0);
try test__ctzdi2(0x00000000_000000B8, 3);
try test__ctzdi2(0x00000000_000000B9, 0);
try test__ctzdi2(0x00000000_000000BA, 1);
try test__ctzdi2(0x00000000_000000BB, 0);
try test__ctzdi2(0x00000000_000000BC, 2);
try test__ctzdi2(0x00000000_000000BD, 0);
try test__ctzdi2(0x00000000_000000BE, 1);
try test__ctzdi2(0x00000000_000000BF, 0);
try test__ctzdi2(0x00000000_000000C0, 6);
try test__ctzdi2(0x00000000_000000C1, 0);
try test__ctzdi2(0x00000000_000000C2, 1);
try test__ctzdi2(0x00000000_000000C3, 0);
try test__ctzdi2(0x00000000_000000C4, 2);
try test__ctzdi2(0x00000000_000000C5, 0);
try test__ctzdi2(0x00000000_000000C6, 1);
try test__ctzdi2(0x00000000_000000C7, 0);
try test__ctzdi2(0x00000000_000000C8, 3);
try test__ctzdi2(0x00000000_000000C9, 0);
try test__ctzdi2(0x00000000_000000CA, 1);
try test__ctzdi2(0x00000000_000000CB, 0);
try test__ctzdi2(0x00000000_000000CC, 2);
try test__ctzdi2(0x00000000_000000CD, 0);
try test__ctzdi2(0x00000000_000000CE, 1);
try test__ctzdi2(0x00000000_000000CF, 0);
try test__ctzdi2(0x00000000_000000D0, 4);
try test__ctzdi2(0x00000000_000000D1, 0);
try test__ctzdi2(0x00000000_000000D2, 1);
try test__ctzdi2(0x00000000_000000D3, 0);
try test__ctzdi2(0x00000000_000000D4, 2);
try test__ctzdi2(0x00000000_000000D5, 0);
try test__ctzdi2(0x00000000_000000D6, 1);
try test__ctzdi2(0x00000000_000000D7, 0);
try test__ctzdi2(0x00000000_000000D8, 3);
try test__ctzdi2(0x00000000_000000D9, 0);
try test__ctzdi2(0x00000000_000000DA, 1);
try test__ctzdi2(0x00000000_000000DB, 0);
try test__ctzdi2(0x00000000_000000DC, 2);
try test__ctzdi2(0x00000000_000000DD, 0);
try test__ctzdi2(0x00000000_000000DE, 1);
try test__ctzdi2(0x00000000_000000DF, 0);
try test__ctzdi2(0x00000000_000000E0, 5);
try test__ctzdi2(0x00000000_000000E1, 0);
try test__ctzdi2(0x00000000_000000E2, 1);
try test__ctzdi2(0x00000000_000000E3, 0);
try test__ctzdi2(0x00000000_000000E4, 2);
try test__ctzdi2(0x00000000_000000E5, 0);
try test__ctzdi2(0x00000000_000000E6, 1);
try test__ctzdi2(0x00000000_000000E7, 0);
try test__ctzdi2(0x00000000_000000E8, 3);
try test__ctzdi2(0x00000000_000000E9, 0);
try test__ctzdi2(0x00000000_000000EA, 1);
try test__ctzdi2(0x00000000_000000EB, 0);
try test__ctzdi2(0x00000000_000000EC, 2);
try test__ctzdi2(0x00000000_000000ED, 0);
try test__ctzdi2(0x00000000_000000EE, 1);
try test__ctzdi2(0x00000000_000000EF, 0);
try test__ctzdi2(0x00000000_000000F0, 4);
try test__ctzdi2(0x00000000_000000F1, 0);
try test__ctzdi2(0x00000000_000000F2, 1);
try test__ctzdi2(0x00000000_000000F3, 0);
try test__ctzdi2(0x00000000_000000F4, 2);
try test__ctzdi2(0x00000000_000000F5, 0);
try test__ctzdi2(0x00000000_000000F6, 1);
try test__ctzdi2(0x00000000_000000F7, 0);
try test__ctzdi2(0x00000000_000000F8, 3);
try test__ctzdi2(0x00000000_000000F9, 0);
try test__ctzdi2(0x00000000_000000FA, 1);
try test__ctzdi2(0x00000000_000000FB, 0);
try test__ctzdi2(0x00000000_000000FC, 2);
try test__ctzdi2(0x00000000_000000FD, 0);
try test__ctzdi2(0x00000000_000000FE, 1);
try test__ctzdi2(0x00000000_000000FF, 0);
try test__ctzdi2(0x00000000_00000000, 64);
try test__ctzdi2(0x80000000_00000000, 63);
try test__ctzdi2(0x40000000_00000000, 62);
try test__ctzdi2(0x20000000_00000000, 61);
try test__ctzdi2(0x10000000_00000000, 60);
try test__ctzdi2(0x08000000_00000000, 59);
try test__ctzdi2(0x04000000_00000000, 58);
try test__ctzdi2(0x02000000_00000000, 57);
try test__ctzdi2(0x01000000_00000000, 56);
try test__ctzdi2(0x00800000_00000000, 55);
try test__ctzdi2(0x00400000_00000000, 54);
try test__ctzdi2(0x00200000_00000000, 53);
try test__ctzdi2(0x00100000_00000000, 52);
try test__ctzdi2(0x00080000_00000000, 51);
try test__ctzdi2(0x00040000_00000000, 50);
try test__ctzdi2(0x00020000_00000000, 49);
try test__ctzdi2(0x00010000_00000000, 48);
try test__ctzdi2(0x00008000_00000000, 47);
try test__ctzdi2(0x00004000_00000000, 46);
try test__ctzdi2(0x00002000_00000000, 45);
try test__ctzdi2(0x00001000_00000000, 44);
try test__ctzdi2(0x00000800_00000000, 43);
try test__ctzdi2(0x00000400_00000000, 42);
try test__ctzdi2(0x00000200_00000000, 41);
try test__ctzdi2(0x00000100_00000000, 40);
try test__ctzdi2(0x00000080_00000000, 39);
try test__ctzdi2(0x00000040_00000000, 38);
try test__ctzdi2(0x00000020_00000000, 37);
try test__ctzdi2(0x00000010_00000000, 36);
try test__ctzdi2(0x00000008_00000000, 35);
try test__ctzdi2(0x00000004_00000000, 34);
try test__ctzdi2(0x00000002_00000000, 33);
try test__ctzdi2(0x00000001_00000000, 32);
try test__ctzdi2(0x00000000_80000000, 31);
try test__ctzdi2(0x00000000_40000000, 30);
try test__ctzdi2(0x00000000_20000000, 29);
try test__ctzdi2(0x00000000_10000000, 28);
try test__ctzdi2(0x00000000_08000000, 27);
try test__ctzdi2(0x00000000_04000000, 26);
try test__ctzdi2(0x00000000_02000000, 25);
try test__ctzdi2(0x00000000_01000000, 24);
try test__ctzdi2(0x00000000_00800000, 23);
try test__ctzdi2(0x00000000_00400000, 22);
try test__ctzdi2(0x00000000_00200000, 21);
try test__ctzdi2(0x00000000_00100000, 20);
try test__ctzdi2(0x00000000_00080000, 19);
try test__ctzdi2(0x00000000_00040000, 18);
try test__ctzdi2(0x00000000_00020000, 17);
try test__ctzdi2(0x00000000_00010000, 16);
try test__ctzdi2(0x00000000_00008000, 15);
try test__ctzdi2(0x00000000_00004000, 14);
try test__ctzdi2(0x00000000_00002000, 13);
try test__ctzdi2(0x00000000_00001000, 12);
try test__ctzdi2(0x00000000_00000800, 11);
try test__ctzdi2(0x00000000_00000400, 10);
try test__ctzdi2(0x00000000_00000200, 9);
try test__ctzdi2(0x00000000_00000100, 8);
} | lib/std/special/compiler_rt/ctzdi2_test.zig |
const builtin = @import("builtin");
const std = @import("../std.zig");
const mem = std.mem;
const assert = std.debug.assert;
const math = std.math;
const maxInt = std.math.maxInt;
pub const advapi32 = @import("windows/advapi32.zig");
pub const kernel32 = @import("windows/kernel32.zig");
pub const ntdll = @import("windows/ntdll.zig");
pub const ole32 = @import("windows/ole32.zig");
pub const psapi = @import("windows/psapi.zig");
pub const shell32 = @import("windows/shell32.zig");
pub const user32 = @import("windows/user32.zig");
pub const ws2_32 = @import("windows/ws2_32.zig");
pub const gdi32 = @import("windows/gdi32.zig");
pub const winmm = @import("windows/winmm.zig");
pub usingnamespace @import("windows/bits.zig");
pub const self_process_handle = @intToPtr(HANDLE, maxInt(usize));
pub const OpenError = error{
IsDir,
NotDir,
FileNotFound,
NoDevice,
AccessDenied,
PipeBusy,
PathAlreadyExists,
Unexpected,
NameTooLong,
WouldBlock,
};
pub const OpenFileOptions = struct {
access_mask: ACCESS_MASK,
dir: ?HANDLE = null,
sa: ?*SECURITY_ATTRIBUTES = null,
share_access: ULONG = FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE,
creation: ULONG,
io_mode: std.io.ModeOverride,
/// If true, tries to open path as a directory.
/// Defaults to false.
open_dir: bool = false,
/// If false, tries to open path as a reparse point without dereferencing it.
/// Defaults to true.
follow_symlinks: bool = true,
};
pub fn OpenFile(sub_path_w: []const u16, options: OpenFileOptions) OpenError!HANDLE {
if (mem.eql(u16, sub_path_w, &[_]u16{'.'}) and !options.open_dir) {
return error.IsDir;
}
if (mem.eql(u16, sub_path_w, &[_]u16{ '.', '.' }) and !options.open_dir) {
return error.IsDir;
}
var result: HANDLE = undefined;
const path_len_bytes = math.cast(u16, sub_path_w.len * 2) catch |err| switch (err) {
error.Overflow => return error.NameTooLong,
};
var nt_name = UNICODE_STRING{
.Length = path_len_bytes,
.MaximumLength = path_len_bytes,
.Buffer = @intToPtr([*]u16, @ptrToInt(sub_path_w.ptr)),
};
var attr = OBJECT_ATTRIBUTES{
.Length = @sizeOf(OBJECT_ATTRIBUTES),
.RootDirectory = if (std.fs.path.isAbsoluteWindowsWTF16(sub_path_w)) null else options.dir,
.Attributes = 0, // Note we do not use OBJ_CASE_INSENSITIVE here.
.ObjectName = &nt_name,
.SecurityDescriptor = if (options.sa) |ptr| ptr.lpSecurityDescriptor else null,
.SecurityQualityOfService = null,
};
var io: IO_STATUS_BLOCK = undefined;
const blocking_flag: ULONG = if (options.io_mode == .blocking) FILE_SYNCHRONOUS_IO_NONALERT else 0;
const file_or_dir_flag: ULONG = if (options.open_dir) FILE_DIRECTORY_FILE else FILE_NON_DIRECTORY_FILE;
// If we're not following symlinks, we need to ensure we don't pass in any synchronization flags such as FILE_SYNCHRONOUS_IO_NONALERT.
const flags: ULONG = if (options.follow_symlinks) file_or_dir_flag | blocking_flag else file_or_dir_flag | FILE_OPEN_REPARSE_POINT;
const rc = ntdll.NtCreateFile(
&result,
options.access_mask,
&attr,
&io,
null,
FILE_ATTRIBUTE_NORMAL,
options.share_access,
options.creation,
flags,
null,
0,
);
switch (rc) {
.SUCCESS => {
if (std.io.is_async and options.io_mode == .evented) {
_ = CreateIoCompletionPort(result, std.event.Loop.instance.?.os_data.io_port, undefined, undefined) catch undefined;
}
return result;
},
.OBJECT_NAME_INVALID => unreachable,
.OBJECT_NAME_NOT_FOUND => return error.FileNotFound,
.OBJECT_PATH_NOT_FOUND => return error.FileNotFound,
.NO_MEDIA_IN_DEVICE => return error.NoDevice,
.INVALID_PARAMETER => unreachable,
.SHARING_VIOLATION => return error.AccessDenied,
.ACCESS_DENIED => return error.AccessDenied,
.PIPE_BUSY => return error.PipeBusy,
.OBJECT_PATH_SYNTAX_BAD => unreachable,
.OBJECT_NAME_COLLISION => return error.PathAlreadyExists,
.FILE_IS_A_DIRECTORY => return error.IsDir,
.NOT_A_DIRECTORY => return error.NotDir,
else => return unexpectedStatus(rc),
}
}
pub const CreatePipeError = error{Unexpected};
pub fn CreatePipe(rd: *HANDLE, wr: *HANDLE, sattr: *const SECURITY_ATTRIBUTES) CreatePipeError!void {
if (kernel32.CreatePipe(rd, wr, sattr, 0) == 0) {
switch (kernel32.GetLastError()) {
else => |err| return unexpectedError(err),
}
}
}
pub fn CreateEventEx(attributes: ?*SECURITY_ATTRIBUTES, name: []const u8, flags: DWORD, desired_access: DWORD) !HANDLE {
const nameW = try sliceToPrefixedFileW(name);
return CreateEventExW(attributes, nameW.span().ptr, flags, desired_access);
}
pub fn CreateEventExW(attributes: ?*SECURITY_ATTRIBUTES, nameW: [*:0]const u16, flags: DWORD, desired_access: DWORD) !HANDLE {
const handle = kernel32.CreateEventExW(attributes, nameW, flags, desired_access);
if (handle) |h| {
return h;
} else {
switch (kernel32.GetLastError()) {
else => |err| return unexpectedError(err),
}
}
}
pub const DeviceIoControlError = error{ AccessDenied, Unexpected };
/// A Zig wrapper around `NtDeviceIoControlFile` and `NtFsControlFile` syscalls.
/// It implements similar behavior to `DeviceIoControl` and is meant to serve
/// as a direct substitute for that call.
/// TODO work out if we need to expose other arguments to the underlying syscalls.
pub fn DeviceIoControl(
h: HANDLE,
ioControlCode: ULONG,
in: ?[]const u8,
out: ?[]u8,
) DeviceIoControlError!void {
// Logic from: https://doxygen.reactos.org/d3/d74/deviceio_8c.html
const is_fsctl = (ioControlCode >> 16) == FILE_DEVICE_FILE_SYSTEM;
var io: IO_STATUS_BLOCK = undefined;
const in_ptr = if (in) |i| i.ptr else null;
const in_len = if (in) |i| @intCast(ULONG, i.len) else 0;
const out_ptr = if (out) |o| o.ptr else null;
const out_len = if (out) |o| @intCast(ULONG, o.len) else 0;
const rc = blk: {
if (is_fsctl) {
break :blk ntdll.NtFsControlFile(
h,
null,
null,
null,
&io,
ioControlCode,
in_ptr,
in_len,
out_ptr,
out_len,
);
} else {
break :blk ntdll.NtDeviceIoControlFile(
h,
null,
null,
null,
&io,
ioControlCode,
in_ptr,
in_len,
out_ptr,
out_len,
);
}
};
switch (rc) {
.SUCCESS => {},
.PRIVILEGE_NOT_HELD => return error.AccessDenied,
.ACCESS_DENIED => return error.AccessDenied,
.INVALID_PARAMETER => unreachable,
else => return unexpectedStatus(rc),
}
}
pub fn GetOverlappedResult(h: HANDLE, overlapped: *OVERLAPPED, wait: bool) !DWORD {
var bytes: DWORD = undefined;
if (kernel32.GetOverlappedResult(h, overlapped, &bytes, @boolToInt(wait)) == 0) {
switch (kernel32.GetLastError()) {
.IO_INCOMPLETE => if (!wait) return error.WouldBlock else unreachable,
else => |err| return unexpectedError(err),
}
}
return bytes;
}
pub const SetHandleInformationError = error{Unexpected};
pub fn SetHandleInformation(h: HANDLE, mask: DWORD, flags: DWORD) SetHandleInformationError!void {
if (kernel32.SetHandleInformation(h, mask, flags) == 0) {
switch (kernel32.GetLastError()) {
else => |err| return unexpectedError(err),
}
}
}
pub const RtlGenRandomError = error{Unexpected};
/// Call RtlGenRandom() instead of CryptGetRandom() on Windows
/// https://github.com/rust-lang-nursery/rand/issues/111
/// https://bugzilla.mozilla.org/show_bug.cgi?id=504270
pub fn RtlGenRandom(output: []u8) RtlGenRandomError!void {
var total_read: usize = 0;
var buff: []u8 = output[0..];
const max_read_size: ULONG = maxInt(ULONG);
while (total_read < output.len) {
const to_read: ULONG = math.min(buff.len, max_read_size);
if (advapi32.RtlGenRandom(buff.ptr, to_read) == 0) {
return unexpectedError(kernel32.GetLastError());
}
total_read += to_read;
buff = buff[to_read..];
}
}
pub const WaitForSingleObjectError = error{
WaitAbandoned,
WaitTimeOut,
Unexpected,
};
pub fn WaitForSingleObject(handle: HANDLE, milliseconds: DWORD) WaitForSingleObjectError!void {
return WaitForSingleObjectEx(handle, milliseconds, false);
}
pub fn WaitForSingleObjectEx(handle: HANDLE, milliseconds: DWORD, alertable: bool) WaitForSingleObjectError!void {
switch (kernel32.WaitForSingleObjectEx(handle, milliseconds, @boolToInt(alertable))) {
WAIT_ABANDONED => return error.WaitAbandoned,
WAIT_OBJECT_0 => return,
WAIT_TIMEOUT => return error.WaitTimeOut,
WAIT_FAILED => switch (kernel32.GetLastError()) {
else => |err| return unexpectedError(err),
},
else => return error.Unexpected,
}
}
pub fn WaitForMultipleObjectsEx(handles: []const HANDLE, waitAll: bool, milliseconds: DWORD, alertable: bool) !u32 {
assert(handles.len < MAXIMUM_WAIT_OBJECTS);
const nCount: DWORD = @intCast(DWORD, handles.len);
switch (kernel32.WaitForMultipleObjectsEx(
nCount,
handles.ptr,
@boolToInt(waitAll),
milliseconds,
@boolToInt(alertable),
)) {
WAIT_OBJECT_0...WAIT_OBJECT_0 + MAXIMUM_WAIT_OBJECTS => |n| {
const handle_index = n - WAIT_OBJECT_0;
assert(handle_index < nCount);
return handle_index;
},
WAIT_ABANDONED_0...WAIT_ABANDONED_0 + MAXIMUM_WAIT_OBJECTS => |n| {
const handle_index = n - WAIT_ABANDONED_0;
assert(handle_index < nCount);
return error.WaitAbandoned;
},
WAIT_TIMEOUT => return error.WaitTimeOut,
WAIT_FAILED => switch (kernel32.GetLastError()) {
else => |err| return unexpectedError(err),
},
else => return error.Unexpected,
}
}
pub const CreateIoCompletionPortError = error{Unexpected};
pub fn CreateIoCompletionPort(
file_handle: HANDLE,
existing_completion_port: ?HANDLE,
completion_key: usize,
concurrent_thread_count: DWORD,
) CreateIoCompletionPortError!HANDLE {
const handle = kernel32.CreateIoCompletionPort(file_handle, existing_completion_port, completion_key, concurrent_thread_count) orelse {
switch (kernel32.GetLastError()) {
.INVALID_PARAMETER => unreachable,
else => |err| return unexpectedError(err),
}
};
return handle;
}
pub const PostQueuedCompletionStatusError = error{Unexpected};
pub fn PostQueuedCompletionStatus(
completion_port: HANDLE,
bytes_transferred_count: DWORD,
completion_key: usize,
lpOverlapped: ?*OVERLAPPED,
) PostQueuedCompletionStatusError!void {
if (kernel32.PostQueuedCompletionStatus(completion_port, bytes_transferred_count, completion_key, lpOverlapped) == 0) {
switch (kernel32.GetLastError()) {
else => |err| return unexpectedError(err),
}
}
}
pub const GetQueuedCompletionStatusResult = enum {
Normal,
Aborted,
Cancelled,
EOF,
};
pub fn GetQueuedCompletionStatus(
completion_port: HANDLE,
bytes_transferred_count: *DWORD,
lpCompletionKey: *usize,
lpOverlapped: *?*OVERLAPPED,
dwMilliseconds: DWORD,
) GetQueuedCompletionStatusResult {
if (kernel32.GetQueuedCompletionStatus(
completion_port,
bytes_transferred_count,
lpCompletionKey,
lpOverlapped,
dwMilliseconds,
) == FALSE) {
switch (kernel32.GetLastError()) {
.ABANDONED_WAIT_0 => return GetQueuedCompletionStatusResult.Aborted,
.OPERATION_ABORTED => return GetQueuedCompletionStatusResult.Cancelled,
.HANDLE_EOF => return GetQueuedCompletionStatusResult.EOF,
else => |err| {
if (std.debug.runtime_safety) {
@setEvalBranchQuota(2500);
std.debug.panic("unexpected error: {}\n", .{err});
}
},
}
}
return GetQueuedCompletionStatusResult.Normal;
}
pub const GetQueuedCompletionStatusError = error{
Aborted,
Cancelled,
EOF,
Timeout,
} || std.os.UnexpectedError;
pub fn GetQueuedCompletionStatusEx(
completion_port: HANDLE,
completion_port_entries: []OVERLAPPED_ENTRY,
timeout_ms: ?DWORD,
alertable: bool,
) GetQueuedCompletionStatusError!u32 {
var num_entries_removed: u32 = 0;
const success = kernel32.GetQueuedCompletionStatusEx(
completion_port,
completion_port_entries.ptr,
@intCast(ULONG, completion_port_entries.len),
&num_entries_removed,
timeout_ms orelse INFINITE,
@boolToInt(alertable),
);
if (success == FALSE) {
return switch (kernel32.GetLastError()) {
.ABANDONED_WAIT_0 => error.Aborted,
.OPERATION_ABORTED => error.Cancelled,
.HANDLE_EOF => error.EOF,
.IMEOUT => error.Timeout,
else => |err| unexpectedError(err),
};
}
return num_entries_removed;
}
pub fn CloseHandle(hObject: HANDLE) void {
assert(ntdll.NtClose(hObject) == .SUCCESS);
}
pub fn FindClose(hFindFile: HANDLE) void {
assert(kernel32.FindClose(hFindFile) != 0);
}
pub const ReadFileError = error{
OperationAborted,
BrokenPipe,
Unexpected,
};
/// If buffer's length exceeds what a Windows DWORD integer can hold, it will be broken into
/// multiple non-atomic reads.
pub fn ReadFile(in_hFile: HANDLE, buffer: []u8, offset: ?u64, io_mode: std.io.ModeOverride) ReadFileError!usize {
if (io_mode != .blocking) {
const loop = std.event.Loop.instance.?;
// TODO make getting the file position non-blocking
const off = if (offset) |o| o else try SetFilePointerEx_CURRENT_get(in_hFile);
var resume_node = std.event.Loop.ResumeNode.Basic{
.base = .{
.id = .Basic,
.handle = @frame(),
.overlapped = OVERLAPPED{
.Internal = 0,
.InternalHigh = 0,
.DUMMYUNIONNAME = .{
.DUMMYSTRUCTNAME = .{
.Offset = @truncate(u32, off),
.OffsetHigh = @truncate(u32, off >> 32),
},
},
.hEvent = null,
},
},
};
loop.beginOneEvent();
suspend {
// TODO handle buffer bigger than DWORD can hold
_ = kernel32.ReadFile(in_hFile, buffer.ptr, @intCast(DWORD, buffer.len), null, &resume_node.base.overlapped);
}
var bytes_transferred: DWORD = undefined;
if (kernel32.GetOverlappedResult(in_hFile, &resume_node.base.overlapped, &bytes_transferred, FALSE) == 0) {
switch (kernel32.GetLastError()) {
.IO_PENDING => unreachable,
.OPERATION_ABORTED => return error.OperationAborted,
.BROKEN_PIPE => return error.BrokenPipe,
.HANDLE_EOF => return @as(usize, bytes_transferred),
else => |err| return unexpectedError(err),
}
}
if (offset == null) {
// TODO make setting the file position non-blocking
const new_off = off + bytes_transferred;
try SetFilePointerEx_CURRENT(in_hFile, @bitCast(i64, new_off));
}
return @as(usize, bytes_transferred);
} else {
while (true) {
const want_read_count = @intCast(DWORD, math.min(@as(DWORD, maxInt(DWORD)), buffer.len));
var amt_read: DWORD = undefined;
var overlapped_data: OVERLAPPED = undefined;
const overlapped: ?*OVERLAPPED = if (offset) |off| blk: {
overlapped_data = .{
.Internal = 0,
.InternalHigh = 0,
.DUMMYUNIONNAME = .{
.DUMMYSTRUCTNAME = .{
.Offset = @truncate(u32, off),
.OffsetHigh = @truncate(u32, off >> 32),
},
},
.hEvent = null,
};
break :blk &overlapped_data;
} else null;
if (kernel32.ReadFile(in_hFile, buffer.ptr, want_read_count, &amt_read, overlapped) == 0) {
switch (kernel32.GetLastError()) {
.OPERATION_ABORTED => continue,
.BROKEN_PIPE => return 0,
.HANDLE_EOF => return 0,
else => |err| return unexpectedError(err),
}
}
return amt_read;
}
}
}
pub const WriteFileError = error{
SystemResources,
OperationAborted,
BrokenPipe,
NotOpenForWriting,
Unexpected,
};
pub fn WriteFile(
handle: HANDLE,
bytes: []const u8,
offset: ?u64,
io_mode: std.io.ModeOverride,
) WriteFileError!usize {
if (std.event.Loop.instance != null and io_mode != .blocking) {
const loop = std.event.Loop.instance.?;
// TODO make getting the file position non-blocking
const off = if (offset) |o| o else try SetFilePointerEx_CURRENT_get(handle);
var resume_node = std.event.Loop.ResumeNode.Basic{
.base = .{
.id = .Basic,
.handle = @frame(),
.overlapped = OVERLAPPED{
.Internal = 0,
.InternalHigh = 0,
.DUMMYUNIONNAME = .{
.DUMMYSTRUCTNAME = .{
.Offset = @truncate(u32, off),
.OffsetHigh = @truncate(u32, off >> 32),
},
},
.hEvent = null,
},
},
};
loop.beginOneEvent();
suspend {
const adjusted_len = math.cast(DWORD, bytes.len) catch maxInt(DWORD);
_ = kernel32.WriteFile(handle, bytes.ptr, adjusted_len, null, &resume_node.base.overlapped);
}
var bytes_transferred: DWORD = undefined;
if (kernel32.GetOverlappedResult(handle, &resume_node.base.overlapped, &bytes_transferred, FALSE) == 0) {
switch (kernel32.GetLastError()) {
.IO_PENDING => unreachable,
.INVALID_USER_BUFFER => return error.SystemResources,
.NOT_ENOUGH_MEMORY => return error.SystemResources,
.OPERATION_ABORTED => return error.OperationAborted,
.NOT_ENOUGH_QUOTA => return error.SystemResources,
.BROKEN_PIPE => return error.BrokenPipe,
else => |err| return unexpectedError(err),
}
}
if (offset == null) {
// TODO make setting the file position non-blocking
const new_off = off + bytes_transferred;
try SetFilePointerEx_CURRENT(handle, @bitCast(i64, new_off));
}
return bytes_transferred;
} else {
var bytes_written: DWORD = undefined;
var overlapped_data: OVERLAPPED = undefined;
const overlapped: ?*OVERLAPPED = if (offset) |off| blk: {
overlapped_data = .{
.Internal = 0,
.InternalHigh = 0,
.DUMMYUNIONNAME = .{
.DUMMYSTRUCTNAME = .{
.Offset = @truncate(u32, off),
.OffsetHigh = @truncate(u32, off >> 32),
},
},
.hEvent = null,
};
break :blk &overlapped_data;
} else null;
const adjusted_len = math.cast(u32, bytes.len) catch maxInt(u32);
if (kernel32.WriteFile(handle, bytes.ptr, adjusted_len, &bytes_written, overlapped) == 0) {
switch (kernel32.GetLastError()) {
.INVALID_USER_BUFFER => return error.SystemResources,
.NOT_ENOUGH_MEMORY => return error.SystemResources,
.OPERATION_ABORTED => return error.OperationAborted,
.NOT_ENOUGH_QUOTA => return error.SystemResources,
.IO_PENDING => unreachable,
.BROKEN_PIPE => return error.BrokenPipe,
.INVALID_HANDLE => return error.NotOpenForWriting,
else => |err| return unexpectedError(err),
}
}
return bytes_written;
}
}
pub const SetCurrentDirectoryError = error{
NameTooLong,
InvalidUtf8,
FileNotFound,
NotDir,
AccessDenied,
NoDevice,
BadPathName,
Unexpected,
};
pub fn SetCurrentDirectory(path_name: []const u16) SetCurrentDirectoryError!void {
const path_len_bytes = math.cast(u16, path_name.len * 2) catch |err| switch (err) {
error.Overflow => return error.NameTooLong,
};
var nt_name = UNICODE_STRING{
.Length = path_len_bytes,
.MaximumLength = path_len_bytes,
.Buffer = @intToPtr([*]u16, @ptrToInt(path_name.ptr)),
};
const rc = ntdll.RtlSetCurrentDirectory_U(&nt_name);
switch (rc) {
.SUCCESS => {},
.OBJECT_NAME_INVALID => return error.BadPathName,
.OBJECT_NAME_NOT_FOUND => return error.FileNotFound,
.OBJECT_PATH_NOT_FOUND => return error.FileNotFound,
.NO_MEDIA_IN_DEVICE => return error.NoDevice,
.INVALID_PARAMETER => unreachable,
.ACCESS_DENIED => return error.AccessDenied,
.OBJECT_PATH_SYNTAX_BAD => unreachable,
.NOT_A_DIRECTORY => return error.NotDir,
else => return unexpectedStatus(rc),
}
}
pub const GetCurrentDirectoryError = error{
NameTooLong,
Unexpected,
};
/// The result is a slice of `buffer`, indexed from 0.
pub fn GetCurrentDirectory(buffer: []u8) GetCurrentDirectoryError![]u8 {
var utf16le_buf: [PATH_MAX_WIDE]u16 = undefined;
const result = kernel32.GetCurrentDirectoryW(utf16le_buf.len, &utf16le_buf);
if (result == 0) {
switch (kernel32.GetLastError()) {
else => |err| return unexpectedError(err),
}
}
assert(result <= utf16le_buf.len);
const utf16le_slice = utf16le_buf[0..result];
// Trust that Windows gives us valid UTF-16LE.
var end_index: usize = 0;
var it = std.unicode.Utf16LeIterator.init(utf16le_slice);
while (it.nextCodepoint() catch unreachable) |codepoint| {
const seq_len = std.unicode.utf8CodepointSequenceLength(codepoint) catch unreachable;
if (end_index + seq_len >= buffer.len)
return error.NameTooLong;
end_index += std.unicode.utf8Encode(codepoint, buffer[end_index..]) catch unreachable;
}
return buffer[0..end_index];
}
pub const CreateSymbolicLinkError = error{
AccessDenied,
PathAlreadyExists,
FileNotFound,
NameTooLong,
NoDevice,
Unexpected,
};
/// Needs either:
/// - `SeCreateSymbolicLinkPrivilege` privilege
/// or
/// - Developper mode on Windows 10
/// otherwise fails with `error.AccessDenied`. In which case `sym_link_path` may still
/// be created on the file system but will lack reparse processing data applied to it.
pub fn CreateSymbolicLink(
dir: ?HANDLE,
sym_link_path: []const u16,
target_path: []const u16,
is_directory: bool,
) CreateSymbolicLinkError!void {
const SYMLINK_DATA = extern struct {
ReparseTag: ULONG,
ReparseDataLength: USHORT,
Reserved: USHORT,
SubstituteNameOffset: USHORT,
SubstituteNameLength: USHORT,
PrintNameOffset: USHORT,
PrintNameLength: USHORT,
Flags: ULONG,
};
const symlink_handle = OpenFile(sym_link_path, .{
.access_mask = SYNCHRONIZE | GENERIC_READ | GENERIC_WRITE,
.dir = dir,
.creation = FILE_CREATE,
.io_mode = .blocking,
.open_dir = is_directory,
}) catch |err| switch (err) {
error.IsDir => return error.PathAlreadyExists,
error.NotDir => unreachable,
error.WouldBlock => unreachable,
error.PipeBusy => unreachable,
else => |e| return e,
};
defer CloseHandle(symlink_handle);
// prepare reparse data buffer
var buffer: [MAXIMUM_REPARSE_DATA_BUFFER_SIZE]u8 = undefined;
const buf_len = @sizeOf(SYMLINK_DATA) + target_path.len * 4;
const header_len = @sizeOf(ULONG) + @sizeOf(USHORT) * 2;
const symlink_data = SYMLINK_DATA{
.ReparseTag = IO_REPARSE_TAG_SYMLINK,
.ReparseDataLength = @intCast(u16, buf_len - header_len),
.Reserved = 0,
.SubstituteNameOffset = @intCast(u16, target_path.len * 2),
.SubstituteNameLength = @intCast(u16, target_path.len * 2),
.PrintNameOffset = 0,
.PrintNameLength = @intCast(u16, target_path.len * 2),
.Flags = if (dir) |_| SYMLINK_FLAG_RELATIVE else 0,
};
std.mem.copy(u8, buffer[0..], std.mem.asBytes(&symlink_data));
@memcpy(buffer[@sizeOf(SYMLINK_DATA)..], @ptrCast([*]const u8, target_path), target_path.len * 2);
const paths_start = @sizeOf(SYMLINK_DATA) + target_path.len * 2;
@memcpy(buffer[paths_start..].ptr, @ptrCast([*]const u8, target_path), target_path.len * 2);
_ = try DeviceIoControl(symlink_handle, FSCTL_SET_REPARSE_POINT, buffer[0..buf_len], null);
}
pub const ReadLinkError = error{
FileNotFound,
AccessDenied,
Unexpected,
NameTooLong,
UnsupportedReparsePointType,
};
pub fn ReadLink(dir: ?HANDLE, sub_path_w: []const u16, out_buffer: []u8) ReadLinkError![]u8 {
// Here, we use `NtCreateFile` to shave off one syscall if we were to use `OpenFile` wrapper.
// With the latter, we'd need to call `NtCreateFile` twice, once for file symlink, and if that
// failed, again for dir symlink. Omitting any mention of file/dir flags makes it possible
// to open the symlink there and then.
const path_len_bytes = math.cast(u16, sub_path_w.len * 2) catch |err| switch (err) {
error.Overflow => return error.NameTooLong,
};
var nt_name = UNICODE_STRING{
.Length = path_len_bytes,
.MaximumLength = path_len_bytes,
.Buffer = @intToPtr([*]u16, @ptrToInt(sub_path_w.ptr)),
};
var attr = OBJECT_ATTRIBUTES{
.Length = @sizeOf(OBJECT_ATTRIBUTES),
.RootDirectory = if (std.fs.path.isAbsoluteWindowsWTF16(sub_path_w)) null else dir,
.Attributes = 0, // Note we do not use OBJ_CASE_INSENSITIVE here.
.ObjectName = &nt_name,
.SecurityDescriptor = null,
.SecurityQualityOfService = null,
};
var result_handle: HANDLE = undefined;
var io: IO_STATUS_BLOCK = undefined;
const rc = ntdll.NtCreateFile(
&result_handle,
FILE_READ_ATTRIBUTES,
&attr,
&io,
null,
FILE_ATTRIBUTE_NORMAL,
FILE_SHARE_READ,
FILE_OPEN,
FILE_OPEN_REPARSE_POINT,
null,
0,
);
switch (rc) {
.SUCCESS => {},
.OBJECT_NAME_INVALID => unreachable,
.OBJECT_NAME_NOT_FOUND => return error.FileNotFound,
.OBJECT_PATH_NOT_FOUND => return error.FileNotFound,
.NO_MEDIA_IN_DEVICE => return error.FileNotFound,
.INVALID_PARAMETER => unreachable,
.SHARING_VIOLATION => return error.AccessDenied,
.ACCESS_DENIED => return error.AccessDenied,
.PIPE_BUSY => return error.AccessDenied,
.OBJECT_PATH_SYNTAX_BAD => unreachable,
.OBJECT_NAME_COLLISION => unreachable,
.FILE_IS_A_DIRECTORY => unreachable,
else => return unexpectedStatus(rc),
}
defer CloseHandle(result_handle);
var reparse_buf: [MAXIMUM_REPARSE_DATA_BUFFER_SIZE]u8 = undefined;
_ = DeviceIoControl(result_handle, FSCTL_GET_REPARSE_POINT, null, reparse_buf[0..]) catch |err| switch (err) {
error.AccessDenied => unreachable,
else => |e| return e,
};
const reparse_struct = @ptrCast(*const REPARSE_DATA_BUFFER, @alignCast(@alignOf(REPARSE_DATA_BUFFER), &reparse_buf[0]));
switch (reparse_struct.ReparseTag) {
IO_REPARSE_TAG_SYMLINK => {
const buf = @ptrCast(*const SYMBOLIC_LINK_REPARSE_BUFFER, @alignCast(@alignOf(SYMBOLIC_LINK_REPARSE_BUFFER), &reparse_struct.DataBuffer[0]));
const offset = buf.SubstituteNameOffset >> 1;
const len = buf.SubstituteNameLength >> 1;
const path_buf = @as([*]const u16, &buf.PathBuffer);
const is_relative = buf.Flags & SYMLINK_FLAG_RELATIVE != 0;
return parseReadlinkPath(path_buf[offset .. offset + len], is_relative, out_buffer);
},
IO_REPARSE_TAG_MOUNT_POINT => {
const buf = @ptrCast(*const MOUNT_POINT_REPARSE_BUFFER, @alignCast(@alignOf(MOUNT_POINT_REPARSE_BUFFER), &reparse_struct.DataBuffer[0]));
const offset = buf.SubstituteNameOffset >> 1;
const len = buf.SubstituteNameLength >> 1;
const path_buf = @as([*]const u16, &buf.PathBuffer);
return parseReadlinkPath(path_buf[offset .. offset + len], false, out_buffer);
},
else => |value| {
std.debug.warn("unsupported symlink type: {}", .{value});
return error.UnsupportedReparsePointType;
},
}
}
fn parseReadlinkPath(path: []const u16, is_relative: bool, out_buffer: []u8) []u8 {
const prefix = [_]u16{ '\\', '?', '?', '\\' };
var start_index: usize = 0;
if (!is_relative and std.mem.startsWith(u16, path, &prefix)) {
start_index = prefix.len;
}
const out_len = std.unicode.utf16leToUtf8(out_buffer, path[start_index..]) catch unreachable;
return out_buffer[0..out_len];
}
pub const DeleteFileError = error{
FileNotFound,
AccessDenied,
NameTooLong,
/// Also known as sharing violation.
FileBusy,
Unexpected,
NotDir,
IsDir,
};
pub const DeleteFileOptions = struct {
dir: ?HANDLE,
remove_dir: bool = false,
};
pub fn DeleteFile(sub_path_w: []const u16, options: DeleteFileOptions) DeleteFileError!void {
const create_options_flags: ULONG = if (options.remove_dir)
FILE_DELETE_ON_CLOSE | FILE_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT
else
FILE_DELETE_ON_CLOSE | FILE_NON_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT; // would we ever want to delete the target instead?
const path_len_bytes = @intCast(u16, sub_path_w.len * 2);
var nt_name = UNICODE_STRING{
.Length = path_len_bytes,
.MaximumLength = path_len_bytes,
// The Windows API makes this mutable, but it will not mutate here.
.Buffer = @intToPtr([*]u16, @ptrToInt(sub_path_w.ptr)),
};
if (sub_path_w[0] == '.' and sub_path_w[1] == 0) {
// Windows does not recognize this, but it does work with empty string.
nt_name.Length = 0;
}
if (sub_path_w[0] == '.' and sub_path_w[1] == '.' and sub_path_w[2] == 0) {
// Can't remove the parent directory with an open handle.
return error.FileBusy;
}
var attr = OBJECT_ATTRIBUTES{
.Length = @sizeOf(OBJECT_ATTRIBUTES),
.RootDirectory = if (std.fs.path.isAbsoluteWindowsWTF16(sub_path_w)) null else options.dir,
.Attributes = 0, // Note we do not use OBJ_CASE_INSENSITIVE here.
.ObjectName = &nt_name,
.SecurityDescriptor = null,
.SecurityQualityOfService = null,
};
var io: IO_STATUS_BLOCK = undefined;
var tmp_handle: HANDLE = undefined;
var rc = ntdll.NtCreateFile(
&tmp_handle,
SYNCHRONIZE | DELETE,
&attr,
&io,
null,
0,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
FILE_OPEN,
create_options_flags,
null,
0,
);
switch (rc) {
.SUCCESS => return CloseHandle(tmp_handle),
.OBJECT_NAME_INVALID => unreachable,
.OBJECT_NAME_NOT_FOUND => return error.FileNotFound,
.OBJECT_PATH_NOT_FOUND => return error.FileNotFound,
.INVALID_PARAMETER => unreachable,
.FILE_IS_A_DIRECTORY => return error.IsDir,
.NOT_A_DIRECTORY => return error.NotDir,
.SHARING_VIOLATION => return error.FileBusy,
else => return unexpectedStatus(rc),
}
}
pub const MoveFileError = error{ FileNotFound, AccessDenied, Unexpected };
pub fn MoveFileEx(old_path: []const u8, new_path: []const u8, flags: DWORD) MoveFileError!void {
const old_path_w = try sliceToPrefixedFileW(old_path);
const new_path_w = try sliceToPrefixedFileW(new_path);
return MoveFileExW(old_path_w.span().ptr, new_path_w.span().ptr, flags);
}
pub fn MoveFileExW(old_path: [*:0]const u16, new_path: [*:0]const u16, flags: DWORD) MoveFileError!void {
if (kernel32.MoveFileExW(old_path, new_path, flags) == 0) {
switch (kernel32.GetLastError()) {
.FILE_NOT_FOUND => return error.FileNotFound,
.ACCESS_DENIED => return error.AccessDenied,
else => |err| return unexpectedError(err),
}
}
}
pub const GetStdHandleError = error{
NoStandardHandleAttached,
Unexpected,
};
pub fn GetStdHandle(handle_id: DWORD) GetStdHandleError!HANDLE {
const handle = kernel32.GetStdHandle(handle_id) orelse return error.NoStandardHandleAttached;
if (handle == INVALID_HANDLE_VALUE) {
switch (kernel32.GetLastError()) {
else => |err| return unexpectedError(err),
}
}
return handle;
}
pub const SetFilePointerError = error{Unexpected};
/// The SetFilePointerEx function with the `dwMoveMethod` parameter set to `FILE_BEGIN`.
pub fn SetFilePointerEx_BEGIN(handle: HANDLE, offset: u64) SetFilePointerError!void {
// "The starting point is zero or the beginning of the file. If [FILE_BEGIN]
// is specified, then the liDistanceToMove parameter is interpreted as an unsigned value."
// https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-setfilepointerex
const ipos = @bitCast(LARGE_INTEGER, offset);
if (kernel32.SetFilePointerEx(handle, ipos, null, FILE_BEGIN) == 0) {
switch (kernel32.GetLastError()) {
.INVALID_PARAMETER => unreachable,
.INVALID_HANDLE => unreachable,
else => |err| return unexpectedError(err),
}
}
}
/// The SetFilePointerEx function with the `dwMoveMethod` parameter set to `FILE_CURRENT`.
pub fn SetFilePointerEx_CURRENT(handle: HANDLE, offset: i64) SetFilePointerError!void {
if (kernel32.SetFilePointerEx(handle, offset, null, FILE_CURRENT) == 0) {
switch (kernel32.GetLastError()) {
.INVALID_PARAMETER => unreachable,
.INVALID_HANDLE => unreachable,
else => |err| return unexpectedError(err),
}
}
}
/// The SetFilePointerEx function with the `dwMoveMethod` parameter set to `FILE_END`.
pub fn SetFilePointerEx_END(handle: HANDLE, offset: i64) SetFilePointerError!void {
if (kernel32.SetFilePointerEx(handle, offset, null, FILE_END) == 0) {
switch (kernel32.GetLastError()) {
.INVALID_PARAMETER => unreachable,
.INVALID_HANDLE => unreachable,
else => |err| return unexpectedError(err),
}
}
}
/// The SetFilePointerEx function with parameters to get the current offset.
pub fn SetFilePointerEx_CURRENT_get(handle: HANDLE) SetFilePointerError!u64 {
var result: LARGE_INTEGER = undefined;
if (kernel32.SetFilePointerEx(handle, 0, &result, FILE_CURRENT) == 0) {
switch (kernel32.GetLastError()) {
.INVALID_PARAMETER => unreachable,
.INVALID_HANDLE => unreachable,
else => |err| return unexpectedError(err),
}
}
// Based on the docs for FILE_BEGIN, it seems that the returned signed integer
// should be interpreted as an unsigned integer.
return @bitCast(u64, result);
}
pub fn QueryObjectName(
handle: HANDLE,
out_buffer: []u16,
) ![]u16 {
const out_buffer_aligned = mem.alignInSlice(out_buffer, @alignOf(OBJECT_NAME_INFORMATION)) orelse return error.NameTooLong;
const info = @ptrCast(*OBJECT_NAME_INFORMATION, out_buffer_aligned);
//buffer size is specified in bytes
const out_buffer_len = std.math.cast(ULONG, out_buffer_aligned.len * 2) catch |e| switch (e) {
error.Overflow => std.math.maxInt(ULONG),
};
//last argument would return the length required for full_buffer, not exposed here
const rc = ntdll.NtQueryObject(handle, .ObjectNameInformation, info, out_buffer_len, null);
switch (rc) {
.SUCCESS => {
// info.Name.Buffer from ObQueryNameString is documented to be null (and MaximumLength == 0)
// if the object was "unnamed", not sure if this can happen for file handles
if (info.Name.MaximumLength == 0) return error.Unexpected;
// resulting string length is specified in bytes
const path_length_unterminated = @divExact(info.Name.Length, 2);
return info.Name.Buffer[0..path_length_unterminated];
},
.ACCESS_DENIED => return error.AccessDenied,
.INVALID_HANDLE => return error.InvalidHandle,
// triggered when the buffer is too small for the OBJECT_NAME_INFORMATION object (.INFO_LENGTH_MISMATCH),
// or if the buffer is too small for the file path returned (.BUFFER_OVERFLOW, .BUFFER_TOO_SMALL)
.INFO_LENGTH_MISMATCH, .BUFFER_OVERFLOW, .BUFFER_TOO_SMALL => return error.NameTooLong,
else => |e| return unexpectedStatus(e),
}
}
test "QueryObjectName" {
if (comptime builtin.target.os.tag != .windows)
return;
//any file will do; canonicalization works on NTFS junctions and symlinks, hardlinks remain separate paths.
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const handle = tmp.dir.fd;
var out_buffer: [PATH_MAX_WIDE]u16 = undefined;
var result_path = try QueryObjectName(handle, &out_buffer);
const required_len_in_u16 = result_path.len + @divExact(@ptrToInt(result_path.ptr) - @ptrToInt(&out_buffer), 2) + 1;
//insufficient size
try std.testing.expectError(error.NameTooLong, QueryObjectName(handle, out_buffer[0 .. required_len_in_u16 - 1]));
//exactly-sufficient size
_ = try QueryObjectName(handle, out_buffer[0..required_len_in_u16]);
}
pub const GetFinalPathNameByHandleError = error{
AccessDenied,
BadPathName,
FileNotFound,
NameTooLong,
Unexpected,
};
/// Specifies how to format volume path in the result of `GetFinalPathNameByHandle`.
/// Defaults to DOS volume names.
pub const GetFinalPathNameByHandleFormat = struct {
volume_name: enum {
/// Format as DOS volume name
Dos,
/// Format as NT volume name
Nt,
} = .Dos,
};
/// Returns canonical (normalized) path of handle.
/// Use `GetFinalPathNameByHandleFormat` to specify whether the path is meant to include
/// NT or DOS volume name (e.g., `\Device\HarddiskVolume0\foo.txt` versus `C:\foo.txt`).
/// If DOS volume name format is selected, note that this function does *not* prepend
/// `\\?\` prefix to the resultant path.
pub fn GetFinalPathNameByHandle(
hFile: HANDLE,
fmt: GetFinalPathNameByHandleFormat,
out_buffer: []u16,
) GetFinalPathNameByHandleError![]u16 {
const final_path = QueryObjectName(hFile, out_buffer) catch |err| switch (err) {
// we assume InvalidHandle is close enough to FileNotFound in semantics
// to not further complicate the error set
error.InvalidHandle => return error.FileNotFound,
else => |e| return e,
};
switch (fmt.volume_name) {
.Nt => {
// the returned path is already in .Nt format
return final_path;
},
.Dos => {
// parse the string to separate volume path from file path
const expected_prefix = std.unicode.utf8ToUtf16LeStringLiteral("\\Device\\");
// TODO find out if a path can start with something besides `\Device\<volume name>`,
// and if we need to handle it differently
// (i.e. how to determine the start and end of the volume name in that case)
if (!mem.eql(u16, expected_prefix, final_path[0..expected_prefix.len])) return error.Unexpected;
const file_path_begin_index = mem.indexOfPos(u16, final_path, expected_prefix.len, &[_]u16{'\\'}) orelse unreachable;
const volume_name_u16 = final_path[0..file_path_begin_index];
const file_name_u16 = final_path[file_path_begin_index..];
// Get DOS volume name. DOS volume names are actually symbolic link objects to the
// actual NT volume. For example:
// (NT) \Device\HarddiskVolume4 => (DOS) \DosDevices\C: == (DOS) C:
const MIN_SIZE = @sizeOf(MOUNTMGR_MOUNT_POINT) + MAX_PATH;
// We initialize the input buffer to all zeros for convenience since
// `DeviceIoControl` with `IOCTL_MOUNTMGR_QUERY_POINTS` expects this.
var input_buf: [MIN_SIZE]u8 align(@alignOf(MOUNTMGR_MOUNT_POINT)) = [_]u8{0} ** MIN_SIZE;
var output_buf: [MIN_SIZE * 4]u8 align(@alignOf(MOUNTMGR_MOUNT_POINTS)) = undefined;
// This surprising path is a filesystem path to the mount manager on Windows.
// Source: https://stackoverflow.com/questions/3012828/using-ioctl-mountmgr-query-points
const mgmt_path = "\\MountPointManager";
const mgmt_path_u16 = sliceToPrefixedFileW(mgmt_path) catch unreachable;
const mgmt_handle = OpenFile(mgmt_path_u16.span(), .{
.access_mask = SYNCHRONIZE,
.share_access = FILE_SHARE_READ | FILE_SHARE_WRITE,
.creation = FILE_OPEN,
.io_mode = .blocking,
}) catch |err| switch (err) {
error.IsDir => unreachable,
error.NotDir => unreachable,
error.NoDevice => unreachable,
error.AccessDenied => unreachable,
error.PipeBusy => unreachable,
error.PathAlreadyExists => unreachable,
error.WouldBlock => unreachable,
else => |e| return e,
};
defer CloseHandle(mgmt_handle);
var input_struct = @ptrCast(*MOUNTMGR_MOUNT_POINT, &input_buf[0]);
input_struct.DeviceNameOffset = @sizeOf(MOUNTMGR_MOUNT_POINT);
input_struct.DeviceNameLength = @intCast(USHORT, volume_name_u16.len * 2);
@memcpy(input_buf[@sizeOf(MOUNTMGR_MOUNT_POINT)..], @ptrCast([*]const u8, volume_name_u16.ptr), volume_name_u16.len * 2);
DeviceIoControl(mgmt_handle, IOCTL_MOUNTMGR_QUERY_POINTS, &input_buf, &output_buf) catch |err| switch (err) {
error.AccessDenied => unreachable,
else => |e| return e,
};
const mount_points_struct = @ptrCast(*const MOUNTMGR_MOUNT_POINTS, &output_buf[0]);
const mount_points = @ptrCast(
[*]const MOUNTMGR_MOUNT_POINT,
&mount_points_struct.MountPoints[0],
)[0..mount_points_struct.NumberOfMountPoints];
for (mount_points) |mount_point| {
const symlink = @ptrCast(
[*]const u16,
@alignCast(@alignOf(u16), &output_buf[mount_point.SymbolicLinkNameOffset]),
)[0 .. mount_point.SymbolicLinkNameLength / 2];
// Look for `\DosDevices\` prefix. We don't really care if there are more than one symlinks
// with traditional DOS drive letters, so pick the first one available.
var prefix_buf = std.unicode.utf8ToUtf16LeStringLiteral("\\DosDevices\\");
const prefix = prefix_buf[0..prefix_buf.len];
if (mem.startsWith(u16, symlink, prefix)) {
const drive_letter = symlink[prefix.len..];
if (out_buffer.len < drive_letter.len + file_name_u16.len) return error.NameTooLong;
mem.copy(u16, out_buffer, drive_letter);
mem.copy(u16, out_buffer[drive_letter.len..], file_name_u16);
const total_len = drive_letter.len + file_name_u16.len;
// Validate that DOS does not contain any spurious nul bytes.
if (mem.indexOfScalar(u16, out_buffer[0..total_len], 0)) |_| {
return error.BadPathName;
}
return out_buffer[0..total_len];
}
}
// If we've ended up here, then something went wrong/is corrupted in the OS,
// so error out!
return error.FileNotFound;
},
}
}
test "GetFinalPathNameByHandle" {
if (comptime builtin.target.os.tag != .windows)
return;
//any file will do
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const handle = tmp.dir.fd;
var buffer: [PATH_MAX_WIDE]u16 = undefined;
//check with sufficient size
const nt_path = try GetFinalPathNameByHandle(handle, .{ .volume_name = .Nt }, &buffer);
_ = try GetFinalPathNameByHandle(handle, .{ .volume_name = .Dos }, &buffer);
const required_len_in_u16 = nt_path.len + @divExact(@ptrToInt(nt_path.ptr) - @ptrToInt(&buffer), 2) + 1;
//check with insufficient size
try std.testing.expectError(error.NameTooLong, GetFinalPathNameByHandle(handle, .{ .volume_name = .Nt }, buffer[0 .. required_len_in_u16 - 1]));
try std.testing.expectError(error.NameTooLong, GetFinalPathNameByHandle(handle, .{ .volume_name = .Dos }, buffer[0 .. required_len_in_u16 - 1]));
//check with exactly-sufficient size
_ = try GetFinalPathNameByHandle(handle, .{ .volume_name = .Nt }, buffer[0..required_len_in_u16]);
_ = try GetFinalPathNameByHandle(handle, .{ .volume_name = .Dos }, buffer[0..required_len_in_u16]);
}
pub const QueryInformationFileError = error{Unexpected};
pub fn QueryInformationFile(
handle: HANDLE,
info_class: FILE_INFORMATION_CLASS,
out_buffer: []u8,
) QueryInformationFileError!void {
var io: IO_STATUS_BLOCK = undefined;
const len_bytes = std.math.cast(u32, out_buffer.len) catch unreachable;
const rc = ntdll.NtQueryInformationFile(handle, &io, out_buffer.ptr, len_bytes, info_class);
switch (rc) {
.SUCCESS => {},
.INVALID_PARAMETER => unreachable,
else => return unexpectedStatus(rc),
}
}
pub const GetFileSizeError = error{Unexpected};
pub fn GetFileSizeEx(hFile: HANDLE) GetFileSizeError!u64 {
var file_size: LARGE_INTEGER = undefined;
if (kernel32.GetFileSizeEx(hFile, &file_size) == 0) {
switch (kernel32.GetLastError()) {
else => |err| return unexpectedError(err),
}
}
return @bitCast(u64, file_size);
}
pub const GetFileAttributesError = error{
FileNotFound,
PermissionDenied,
Unexpected,
};
pub fn GetFileAttributes(filename: []const u8) GetFileAttributesError!DWORD {
const filename_w = try sliceToPrefixedFileW(filename);
return GetFileAttributesW(filename_w.span().ptr);
}
pub fn GetFileAttributesW(lpFileName: [*:0]const u16) GetFileAttributesError!DWORD {
const rc = kernel32.GetFileAttributesW(lpFileName);
if (rc == INVALID_FILE_ATTRIBUTES) {
switch (kernel32.GetLastError()) {
.FILE_NOT_FOUND => return error.FileNotFound,
.PATH_NOT_FOUND => return error.FileNotFound,
.ACCESS_DENIED => return error.PermissionDenied,
else => |err| return unexpectedError(err),
}
}
return rc;
}
pub fn WSAStartup(majorVersion: u8, minorVersion: u8) !ws2_32.WSADATA {
var wsadata: ws2_32.WSADATA = undefined;
return switch (ws2_32.WSAStartup((@as(WORD, minorVersion) << 8) | majorVersion, &wsadata)) {
0 => wsadata,
else => |err_int| switch (@intToEnum(ws2_32.WinsockError, @intCast(u16, err_int))) {
.WSASYSNOTREADY => return error.SystemNotAvailable,
.WSAVERNOTSUPPORTED => return error.VersionNotSupported,
.WSAEINPROGRESS => return error.BlockingOperationInProgress,
.WSAEPROCLIM => return error.ProcessFdQuotaExceeded,
else => |err| return unexpectedWSAError(err),
},
};
}
pub fn WSACleanup() !void {
return switch (ws2_32.WSACleanup()) {
0 => {},
ws2_32.SOCKET_ERROR => switch (ws2_32.WSAGetLastError()) {
.WSANOTINITIALISED => return error.NotInitialized,
.WSAENETDOWN => return error.NetworkNotAvailable,
.WSAEINPROGRESS => return error.BlockingOperationInProgress,
else => |err| return unexpectedWSAError(err),
},
else => unreachable,
};
}
var wsa_startup_mutex: std.Thread.Mutex = .{};
/// Microsoft requires WSAStartup to be called to initialize, or else
/// WSASocketW will return WSANOTINITIALISED.
/// Since this is a standard library, we do not have the luxury of
/// putting initialization code anywhere, because we would not want
/// to pay the cost of calling WSAStartup if there ended up being no
/// networking. Also, if Zig code is used as a library, Zig is not in
/// charge of the start code, and we couldn't put in any initialization
/// code even if we wanted to.
/// The documentation for WSAStartup mentions that there must be a
/// matching WSACleanup call. It is not possible for the Zig Standard
/// Library to honor this for the same reason - there is nowhere to put
/// deinitialization code.
/// So, API users of the zig std lib have two options:
/// * (recommended) The simple, cross-platform way: just call `WSASocketW`
/// and don't worry about it. Zig will call WSAStartup() in a thread-safe
/// manner and never deinitialize networking. This is ideal for an
/// application which has the capability to do networking.
/// * The getting-your-hands-dirty way: call `WSAStartup()` before doing
/// networking, so that the error handling code for WSANOTINITIALISED never
/// gets run, which then allows the application or library to call `WSACleanup()`.
/// This could make sense for a library, which has init and deinit
/// functions for the whole library's lifetime.
pub fn WSASocketW(
af: i32,
socket_type: i32,
protocol: i32,
protocolInfo: ?*ws2_32.WSAPROTOCOL_INFOW,
g: ws2_32.GROUP,
dwFlags: DWORD,
) !ws2_32.SOCKET {
var first = true;
while (true) {
const rc = ws2_32.WSASocketW(af, socket_type, protocol, protocolInfo, g, dwFlags);
if (rc == ws2_32.INVALID_SOCKET) {
switch (ws2_32.WSAGetLastError()) {
.WSAEAFNOSUPPORT => return error.AddressFamilyNotSupported,
.WSAEMFILE => return error.ProcessFdQuotaExceeded,
.WSAENOBUFS => return error.SystemResources,
.WSAEPROTONOSUPPORT => return error.ProtocolNotSupported,
.WSANOTINITIALISED => {
if (!first) return error.Unexpected;
first = false;
var held = wsa_startup_mutex.acquire();
defer held.release();
// Here we could use a flag to prevent multiple threads to prevent
// multiple calls to WSAStartup, but it doesn't matter. We're globally
// leaking the resource intentionally, and the mutex already prevents
// data races within the WSAStartup function.
_ = WSAStartup(2, 2) catch |err| switch (err) {
error.SystemNotAvailable => return error.SystemResources,
error.VersionNotSupported => return error.Unexpected,
error.BlockingOperationInProgress => return error.Unexpected,
error.ProcessFdQuotaExceeded => return error.ProcessFdQuotaExceeded,
error.Unexpected => return error.Unexpected,
};
continue;
},
else => |err| return unexpectedWSAError(err),
}
}
return rc;
}
}
pub fn bind(s: ws2_32.SOCKET, name: *const ws2_32.sockaddr, namelen: ws2_32.socklen_t) i32 {
return ws2_32.bind(s, name, @intCast(i32, namelen));
}
pub fn listen(s: ws2_32.SOCKET, backlog: u31) i32 {
return ws2_32.listen(s, backlog);
}
pub fn closesocket(s: ws2_32.SOCKET) !void {
switch (ws2_32.closesocket(s)) {
0 => {},
ws2_32.SOCKET_ERROR => switch (ws2_32.WSAGetLastError()) {
else => |err| return unexpectedWSAError(err),
},
else => unreachable,
}
}
pub fn accept(s: ws2_32.SOCKET, name: ?*ws2_32.sockaddr, namelen: ?*ws2_32.socklen_t) ws2_32.SOCKET {
assert((name == null) == (namelen == null));
return ws2_32.accept(s, name, @ptrCast(?*i32, namelen));
}
pub fn getsockname(s: ws2_32.SOCKET, name: *ws2_32.sockaddr, namelen: *ws2_32.socklen_t) i32 {
return ws2_32.getsockname(s, name, @ptrCast(*i32, namelen));
}
pub fn getpeername(s: ws2_32.SOCKET, name: *ws2_32.sockaddr, namelen: *ws2_32.socklen_t) i32 {
return ws2_32.getpeername(s, name, @ptrCast(*i32, namelen));
}
pub fn sendmsg(
s: ws2_32.SOCKET,
msg: *const ws2_32.WSAMSG,
flags: u32,
) i32 {
var bytes_send: DWORD = undefined;
if (ws2_32.WSASendMsg(s, msg, flags, &bytes_send, null, null) == ws2_32.SOCKET_ERROR) {
return ws2_32.SOCKET_ERROR;
} else {
return @as(i32, @intCast(u31, bytes_send));
}
}
pub fn sendto(s: ws2_32.SOCKET, buf: [*]const u8, len: usize, flags: u32, to: ?*const ws2_32.sockaddr, to_len: ws2_32.socklen_t) i32 {
var buffer = ws2_32.WSABUF{ .len = @truncate(u31, len), .buf = @intToPtr([*]u8, @ptrToInt(buf)) };
var bytes_send: DWORD = undefined;
if (ws2_32.WSASendTo(s, @ptrCast([*]ws2_32.WSABUF, &buffer), 1, &bytes_send, flags, to, @intCast(i32, to_len), null, null) == ws2_32.SOCKET_ERROR) {
return ws2_32.SOCKET_ERROR;
} else {
return @as(i32, @intCast(u31, bytes_send));
}
}
pub fn recvfrom(s: ws2_32.SOCKET, buf: [*]u8, len: usize, flags: u32, from: ?*ws2_32.sockaddr, from_len: ?*ws2_32.socklen_t) i32 {
var buffer = ws2_32.WSABUF{ .len = @truncate(u31, len), .buf = buf };
var bytes_received: DWORD = undefined;
var flags_inout = flags;
if (ws2_32.WSARecvFrom(s, @ptrCast([*]ws2_32.WSABUF, &buffer), 1, &bytes_received, &flags_inout, from, @ptrCast(?*i32, from_len), null, null) == ws2_32.SOCKET_ERROR) {
return ws2_32.SOCKET_ERROR;
} else {
return @as(i32, @intCast(u31, bytes_received));
}
}
pub fn poll(fds: [*]ws2_32.pollfd, n: c_ulong, timeout: i32) i32 {
return ws2_32.WSAPoll(fds, n, timeout);
}
pub fn WSAIoctl(
s: ws2_32.SOCKET,
dwIoControlCode: DWORD,
inBuffer: ?[]const u8,
outBuffer: []u8,
overlapped: ?*ws2_32.WSAOVERLAPPED,
completionRoutine: ?ws2_32.WSAOVERLAPPED_COMPLETION_ROUTINE,
) !DWORD {
var bytes: DWORD = undefined;
switch (ws2_32.WSAIoctl(
s,
dwIoControlCode,
if (inBuffer) |i| i.ptr else null,
if (inBuffer) |i| @intCast(DWORD, i.len) else 0,
outBuffer.ptr,
@intCast(DWORD, outBuffer.len),
&bytes,
overlapped,
completionRoutine,
)) {
0 => {},
ws2_32.SOCKET_ERROR => switch (ws2_32.WSAGetLastError()) {
else => |err| return unexpectedWSAError(err),
},
else => unreachable,
}
return bytes;
}
const GetModuleFileNameError = error{Unexpected};
pub fn GetModuleFileNameW(hModule: ?HMODULE, buf_ptr: [*]u16, buf_len: DWORD) GetModuleFileNameError![:0]u16 {
const rc = kernel32.GetModuleFileNameW(hModule, buf_ptr, buf_len);
if (rc == 0) {
switch (kernel32.GetLastError()) {
else => |err| return unexpectedError(err),
}
}
return buf_ptr[0..rc :0];
}
pub const TerminateProcessError = error{Unexpected};
pub fn TerminateProcess(hProcess: HANDLE, uExitCode: UINT) TerminateProcessError!void {
if (kernel32.TerminateProcess(hProcess, uExitCode) == 0) {
switch (kernel32.GetLastError()) {
else => |err| return unexpectedError(err),
}
}
}
pub const VirtualAllocError = error{Unexpected};
pub fn VirtualAlloc(addr: ?LPVOID, size: usize, alloc_type: DWORD, flProtect: DWORD) VirtualAllocError!LPVOID {
return kernel32.VirtualAlloc(addr, size, alloc_type, flProtect) orelse {
switch (kernel32.GetLastError()) {
else => |err| return unexpectedError(err),
}
};
}
pub fn VirtualFree(lpAddress: ?LPVOID, dwSize: usize, dwFreeType: DWORD) void {
assert(kernel32.VirtualFree(lpAddress, dwSize, dwFreeType) != 0);
}
pub const SetConsoleTextAttributeError = error{Unexpected};
pub fn SetConsoleTextAttribute(hConsoleOutput: HANDLE, wAttributes: WORD) SetConsoleTextAttributeError!void {
if (kernel32.SetConsoleTextAttribute(hConsoleOutput, wAttributes) == 0) {
switch (kernel32.GetLastError()) {
else => |err| return unexpectedError(err),
}
}
}
pub fn SetConsoleCtrlHandler(handler_routine: ?HANDLER_ROUTINE, add: bool) !void {
const success = kernel32.SetConsoleCtrlHandler(
handler_routine,
if (add) TRUE else FALSE,
);
if (success == FALSE) {
return switch (kernel32.GetLastError()) {
else => |err| unexpectedError(err),
};
}
}
pub fn SetFileCompletionNotificationModes(handle: HANDLE, flags: UCHAR) !void {
const success = kernel32.SetFileCompletionNotificationModes(handle, flags);
if (success == FALSE) {
return switch (kernel32.GetLastError()) {
else => |err| unexpectedError(err),
};
}
}
pub const GetEnvironmentStringsError = error{OutOfMemory};
pub fn GetEnvironmentStringsW() GetEnvironmentStringsError![*:0]u16 {
return kernel32.GetEnvironmentStringsW() orelse return error.OutOfMemory;
}
pub fn FreeEnvironmentStringsW(penv: [*:0]u16) void {
assert(kernel32.FreeEnvironmentStringsW(penv) != 0);
}
pub const GetEnvironmentVariableError = error{
EnvironmentVariableNotFound,
Unexpected,
};
pub fn GetEnvironmentVariableW(lpName: LPWSTR, lpBuffer: [*]u16, nSize: DWORD) GetEnvironmentVariableError!DWORD {
const rc = kernel32.GetEnvironmentVariableW(lpName, lpBuffer, nSize);
if (rc == 0) {
switch (kernel32.GetLastError()) {
.ENVVAR_NOT_FOUND => return error.EnvironmentVariableNotFound,
else => |err| return unexpectedError(err),
}
}
return rc;
}
pub const CreateProcessError = error{
FileNotFound,
AccessDenied,
InvalidName,
Unexpected,
};
pub fn CreateProcessW(
lpApplicationName: ?LPWSTR,
lpCommandLine: LPWSTR,
lpProcessAttributes: ?*SECURITY_ATTRIBUTES,
lpThreadAttributes: ?*SECURITY_ATTRIBUTES,
bInheritHandles: BOOL,
dwCreationFlags: DWORD,
lpEnvironment: ?*c_void,
lpCurrentDirectory: ?LPWSTR,
lpStartupInfo: *STARTUPINFOW,
lpProcessInformation: *PROCESS_INFORMATION,
) CreateProcessError!void {
if (kernel32.CreateProcessW(
lpApplicationName,
lpCommandLine,
lpProcessAttributes,
lpThreadAttributes,
bInheritHandles,
dwCreationFlags,
lpEnvironment,
lpCurrentDirectory,
lpStartupInfo,
lpProcessInformation,
) == 0) {
switch (kernel32.GetLastError()) {
.FILE_NOT_FOUND => return error.FileNotFound,
.PATH_NOT_FOUND => return error.FileNotFound,
.ACCESS_DENIED => return error.AccessDenied,
.INVALID_PARAMETER => unreachable,
.INVALID_NAME => return error.InvalidName,
else => |err| return unexpectedError(err),
}
}
}
pub const LoadLibraryError = error{
FileNotFound,
Unexpected,
};
pub fn LoadLibraryW(lpLibFileName: [*:0]const u16) LoadLibraryError!HMODULE {
return kernel32.LoadLibraryW(lpLibFileName) orelse {
switch (kernel32.GetLastError()) {
.FILE_NOT_FOUND => return error.FileNotFound,
.PATH_NOT_FOUND => return error.FileNotFound,
.MOD_NOT_FOUND => return error.FileNotFound,
else => |err| return unexpectedError(err),
}
};
}
pub fn FreeLibrary(hModule: HMODULE) void {
assert(kernel32.FreeLibrary(hModule) != 0);
}
pub fn QueryPerformanceFrequency() u64 {
// "On systems that run Windows XP or later, the function will always succeed"
// https://docs.microsoft.com/en-us/windows/desktop/api/profileapi/nf-profileapi-queryperformancefrequency
var result: LARGE_INTEGER = undefined;
assert(kernel32.QueryPerformanceFrequency(&result) != 0);
// The kernel treats this integer as unsigned.
return @bitCast(u64, result);
}
pub fn QueryPerformanceCounter() u64 {
// "On systems that run Windows XP or later, the function will always succeed"
// https://docs.microsoft.com/en-us/windows/desktop/api/profileapi/nf-profileapi-queryperformancecounter
var result: LARGE_INTEGER = undefined;
assert(kernel32.QueryPerformanceCounter(&result) != 0);
// The kernel treats this integer as unsigned.
return @bitCast(u64, result);
}
pub fn InitOnceExecuteOnce(InitOnce: *INIT_ONCE, InitFn: INIT_ONCE_FN, Parameter: ?*c_void, Context: ?*c_void) void {
assert(kernel32.InitOnceExecuteOnce(InitOnce, InitFn, Parameter, Context) != 0);
}
pub fn HeapFree(hHeap: HANDLE, dwFlags: DWORD, lpMem: *c_void) void {
assert(kernel32.HeapFree(hHeap, dwFlags, lpMem) != 0);
}
pub fn HeapDestroy(hHeap: HANDLE) void {
assert(kernel32.HeapDestroy(hHeap) != 0);
}
pub fn LocalFree(hMem: HLOCAL) void {
assert(kernel32.LocalFree(hMem) == null);
}
pub const GetFileInformationByHandleError = error{Unexpected};
pub fn GetFileInformationByHandle(
hFile: HANDLE,
) GetFileInformationByHandleError!BY_HANDLE_FILE_INFORMATION {
var info: BY_HANDLE_FILE_INFORMATION = undefined;
const rc = ntdll.GetFileInformationByHandle(hFile, &info);
if (rc == 0) {
switch (kernel32.GetLastError()) {
else => |err| return unexpectedError(err),
}
}
return info;
}
pub const SetFileTimeError = error{Unexpected};
pub fn SetFileTime(
hFile: HANDLE,
lpCreationTime: ?*const FILETIME,
lpLastAccessTime: ?*const FILETIME,
lpLastWriteTime: ?*const FILETIME,
) SetFileTimeError!void {
const rc = kernel32.SetFileTime(hFile, lpCreationTime, lpLastAccessTime, lpLastWriteTime);
if (rc == 0) {
switch (kernel32.GetLastError()) {
else => |err| return unexpectedError(err),
}
}
}
pub const LockFileError = error{
SystemResources,
WouldBlock,
} || std.os.UnexpectedError;
pub fn LockFile(
FileHandle: HANDLE,
Event: ?HANDLE,
ApcRoutine: ?*IO_APC_ROUTINE,
ApcContext: ?*c_void,
IoStatusBlock: *IO_STATUS_BLOCK,
ByteOffset: *const LARGE_INTEGER,
Length: *const LARGE_INTEGER,
Key: ?*ULONG,
FailImmediately: BOOLEAN,
ExclusiveLock: BOOLEAN,
) !void {
const rc = ntdll.NtLockFile(
FileHandle,
Event,
ApcRoutine,
ApcContext,
IoStatusBlock,
ByteOffset,
Length,
Key,
FailImmediately,
ExclusiveLock,
);
switch (rc) {
.SUCCESS => return,
.INSUFFICIENT_RESOURCES => return error.SystemResources,
.LOCK_NOT_GRANTED => return error.WouldBlock,
.ACCESS_VIOLATION => unreachable, // bad io_status_block pointer
else => return unexpectedStatus(rc),
}
}
pub const UnlockFileError = error{
RangeNotLocked,
} || std.os.UnexpectedError;
pub fn UnlockFile(
FileHandle: HANDLE,
IoStatusBlock: *IO_STATUS_BLOCK,
ByteOffset: *const LARGE_INTEGER,
Length: *const LARGE_INTEGER,
Key: ?*ULONG,
) !void {
const rc = ntdll.NtUnlockFile(FileHandle, IoStatusBlock, ByteOffset, Length, Key);
switch (rc) {
.SUCCESS => return,
.RANGE_NOT_LOCKED => return error.RangeNotLocked,
.ACCESS_VIOLATION => unreachable, // bad io_status_block pointer
else => return unexpectedStatus(rc),
}
}
pub fn teb() *TEB {
return switch (builtin.target.cpu.arch) {
.i386 => asm volatile (
\\ movl %%fs:0x18, %[ptr]
: [ptr] "=r" (-> *TEB),
),
.x86_64 => asm volatile (
\\ movq %%gs:0x30, %[ptr]
: [ptr] "=r" (-> *TEB),
),
.aarch64 => asm volatile (
\\ mov %[ptr], x18
: [ptr] "=r" (-> *TEB),
),
else => @compileError("unsupported arch"),
};
}
pub fn peb() *PEB {
return teb().ProcessEnvironmentBlock;
}
/// A file time is a 64-bit value that represents the number of 100-nanosecond
/// intervals that have elapsed since 12:00 A.M. January 1, 1601 Coordinated
/// Universal Time (UTC).
/// This function returns the number of nanoseconds since the canonical epoch,
/// which is the POSIX one (Jan 01, 1970 AD).
pub fn fromSysTime(hns: i64) i128 {
const adjusted_epoch: i128 = hns + std.time.epoch.windows * (std.time.ns_per_s / 100);
return adjusted_epoch * 100;
}
pub fn toSysTime(ns: i128) i64 {
const hns = @divFloor(ns, 100);
return @intCast(i64, hns) - std.time.epoch.windows * (std.time.ns_per_s / 100);
}
pub fn fileTimeToNanoSeconds(ft: FILETIME) i128 {
const hns = (@as(i64, ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
return fromSysTime(hns);
}
/// Converts a number of nanoseconds since the POSIX epoch to a Windows FILETIME.
pub fn nanoSecondsToFileTime(ns: i128) FILETIME {
const adjusted = @bitCast(u64, toSysTime(ns));
return FILETIME{
.dwHighDateTime = @truncate(u32, adjusted >> 32),
.dwLowDateTime = @truncate(u32, adjusted),
};
}
pub const PathSpace = struct {
data: [PATH_MAX_WIDE:0]u16,
len: usize,
pub fn span(self: PathSpace) [:0]const u16 {
return self.data[0..self.len :0];
}
};
/// The error type for `removeDotDirsSanitized`
pub const RemoveDotDirsError = error{TooManyParentDirs};
/// Removes '.' and '..' path components from a "sanitized relative path".
/// A "sanitized path" is one where:
/// 1) all forward slashes have been replaced with back slashes
/// 2) all repeating back slashes have been collapsed
/// 3) the path is a relative one (does not start with a back slash)
pub fn removeDotDirsSanitized(comptime T: type, path: []T) RemoveDotDirsError!usize {
std.debug.assert(path.len == 0 or path[0] != '\\');
var write_idx: usize = 0;
var read_idx: usize = 0;
while (read_idx < path.len) {
if (path[read_idx] == '.') {
if (read_idx + 1 == path.len)
return write_idx;
const after_dot = path[read_idx + 1];
if (after_dot == '\\') {
read_idx += 2;
continue;
}
if (after_dot == '.' and (read_idx + 2 == path.len or path[read_idx + 2] == '\\')) {
if (write_idx == 0) return error.TooManyParentDirs;
std.debug.assert(write_idx >= 2);
write_idx -= 1;
while (true) {
write_idx -= 1;
if (write_idx == 0) break;
if (path[write_idx] == '\\') {
write_idx += 1;
break;
}
}
if (read_idx + 2 == path.len)
return write_idx;
read_idx += 3;
continue;
}
}
// skip to the next path separator
while (true) : (read_idx += 1) {
if (read_idx == path.len)
return write_idx;
path[write_idx] = path[read_idx];
write_idx += 1;
if (path[read_idx] == '\\')
break;
}
read_idx += 1;
}
return write_idx;
}
/// Normalizes a Windows path with the following steps:
/// 1) convert all forward slashes to back slashes
/// 2) collapse duplicate back slashes
/// 3) remove '.' and '..' directory parts
/// Returns the length of the new path.
pub fn normalizePath(comptime T: type, path: []T) RemoveDotDirsError!usize {
mem.replaceScalar(T, path, '/', '\\');
const new_len = mem.collapseRepeatsLen(T, path, '\\');
const prefix_len: usize = init: {
if (new_len >= 1 and path[0] == '\\') break :init 1;
if (new_len >= 2 and path[1] == ':')
break :init if (new_len >= 3 and path[2] == '\\') @as(usize, 3) else @as(usize, 2);
break :init 0;
};
return prefix_len + try removeDotDirsSanitized(T, path[prefix_len..new_len]);
}
/// Same as `sliceToPrefixedFileW` but accepts a pointer
/// to a null-terminated path.
pub fn cStrToPrefixedFileW(s: [*:0]const u8) !PathSpace {
return sliceToPrefixedFileW(mem.spanZ(s));
}
/// Converts the path `s` to WTF16, null-terminated. If the path is absolute,
/// it will get NT-style prefix `\??\` prepended automatically.
pub fn sliceToPrefixedFileW(s: []const u8) !PathSpace {
// TODO https://github.com/ziglang/zig/issues/2765
var path_space: PathSpace = undefined;
const prefix = "\\??\\";
const prefix_index: usize = if (mem.startsWith(u8, s, prefix)) prefix.len else 0;
for (s[prefix_index..]) |byte| {
switch (byte) {
'*', '?', '"', '<', '>', '|' => return error.BadPathName,
else => {},
}
}
const prefix_u16 = [_]u16{ '\\', '?', '?', '\\' };
const start_index = if (prefix_index > 0 or !std.fs.path.isAbsolute(s)) 0 else blk: {
mem.copy(u16, path_space.data[0..], prefix_u16[0..]);
break :blk prefix_u16.len;
};
path_space.len = start_index + try std.unicode.utf8ToUtf16Le(path_space.data[start_index..], s);
if (path_space.len > path_space.data.len) return error.NameTooLong;
path_space.len = start_index + (normalizePath(u16, path_space.data[start_index..path_space.len]) catch |err| switch (err) {
error.TooManyParentDirs => {
if (!std.fs.path.isAbsolute(s)) {
var temp_path: PathSpace = undefined;
temp_path.len = try std.unicode.utf8ToUtf16Le(&temp_path.data, s);
std.debug.assert(temp_path.len == path_space.len);
temp_path.data[path_space.len] = 0;
path_space.len = prefix_u16.len + try getFullPathNameW(&temp_path.data, path_space.data[prefix_u16.len..]);
mem.copy(u16, &path_space.data, &prefix_u16);
std.debug.assert(path_space.data[path_space.len] == 0);
return path_space;
}
return error.BadPathName;
},
});
path_space.data[path_space.len] = 0;
return path_space;
}
fn getFullPathNameW(path: [*:0]const u16, out: []u16) !usize {
const result = kernel32.GetFullPathNameW(path, @intCast(u32, out.len), std.meta.assumeSentinel(out.ptr, 0), null);
if (result == 0) {
switch (kernel32.GetLastError()) {
else => |err| return unexpectedError(err),
}
}
return result;
}
/// Assumes an absolute path.
pub fn wToPrefixedFileW(s: []const u16) !PathSpace {
// TODO https://github.com/ziglang/zig/issues/2765
var path_space: PathSpace = undefined;
const start_index = if (mem.startsWith(u16, s, &[_]u16{ '\\', '?' })) 0 else blk: {
const prefix = [_]u16{ '\\', '?', '?', '\\' };
mem.copy(u16, path_space.data[0..], &prefix);
break :blk prefix.len;
};
path_space.len = start_index + s.len;
if (path_space.len > path_space.data.len) return error.NameTooLong;
mem.copy(u16, path_space.data[start_index..], s);
// > File I/O functions in the Windows API convert "/" to "\" as part of
// > converting the name to an NT-style name, except when using the "\\?\"
// > prefix as detailed in the following sections.
// from https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#maximum-path-length-limitation
// Because we want the larger maximum path length for absolute paths, we
// convert forward slashes to backward slashes here.
for (path_space.data[0..path_space.len]) |*elem| {
if (elem.* == '/') {
elem.* = '\\';
}
}
path_space.data[path_space.len] = 0;
return path_space;
}
inline fn MAKELANGID(p: c_ushort, s: c_ushort) LANGID {
return (s << 10) | p;
}
/// Loads a Winsock extension function in runtime specified by a GUID.
pub fn loadWinsockExtensionFunction(comptime T: type, sock: ws2_32.SOCKET, guid: GUID) !T {
var function: T = undefined;
var num_bytes: DWORD = undefined;
const rc = ws2_32.WSAIoctl(
sock,
ws2_32.SIO_GET_EXTENSION_FUNCTION_POINTER,
@ptrCast(*const c_void, &guid),
@sizeOf(GUID),
&function,
@sizeOf(T),
&num_bytes,
null,
null,
);
if (rc == ws2_32.SOCKET_ERROR) {
return switch (ws2_32.WSAGetLastError()) {
.WSAEOPNOTSUPP => error.OperationNotSupported,
.WSAENOTSOCK => error.FileDescriptorNotASocket,
else => |err| unexpectedWSAError(err),
};
}
if (num_bytes != @sizeOf(T)) {
return error.ShortRead;
}
return function;
}
/// Call this when you made a windows DLL call or something that does SetLastError
/// and you get an unexpected error.
pub fn unexpectedError(err: Win32Error) std.os.UnexpectedError {
if (std.os.unexpected_error_tracing) {
// 614 is the length of the longest windows error desciption
var buf_wstr: [614]WCHAR = undefined;
var buf_utf8: [614]u8 = undefined;
const len = kernel32.FormatMessageW(
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
null,
err,
MAKELANGID(LANG.NEUTRAL, SUBLANG.DEFAULT),
&buf_wstr,
buf_wstr.len,
null,
);
_ = std.unicode.utf16leToUtf8(&buf_utf8, buf_wstr[0..len]) catch unreachable;
std.debug.warn("error.Unexpected: GetLastError({}): {s}\n", .{ @enumToInt(err), buf_utf8[0..len] });
std.debug.dumpCurrentStackTrace(null);
}
return error.Unexpected;
}
pub fn unexpectedWSAError(err: ws2_32.WinsockError) std.os.UnexpectedError {
return unexpectedError(@intToEnum(Win32Error, @enumToInt(err)));
}
/// Call this when you made a windows NtDll call
/// and you get an unexpected status.
pub fn unexpectedStatus(status: NTSTATUS) std.os.UnexpectedError {
if (std.os.unexpected_error_tracing) {
std.debug.warn("error.Unexpected NTSTATUS=0x{x}\n", .{@enumToInt(status)});
std.debug.dumpCurrentStackTrace(null);
}
return error.Unexpected;
}
pub fn SetThreadDescription(hThread: HANDLE, lpThreadDescription: LPCWSTR) !void {
if (kernel32.SetThreadDescription(hThread, lpThreadDescription) == 0) {
switch (kernel32.GetLastError()) {
else => |err| return unexpectedError(err),
}
}
}
pub fn GetThreadDescription(hThread: HANDLE, ppszThreadDescription: *LPWSTR) !void {
if (kernel32.GetThreadDescription(hThread, ppszThreadDescription) == 0) {
switch (kernel32.GetLastError()) {
else => |err| return unexpectedError(err),
}
}
}
test "" {
if (builtin.os.tag == .windows) {
_ = @import("windows/test.zig");
}
} | lib/std/os/windows.zig |
const std = @import("std");
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const expectEqualSlices = std.testing.expectEqualSlices;
const maxInt = std.math.maxInt;
const minInt = std.math.minInt;
const mem = std.mem;
test "division" {
if (@import("builtin").arch == .riscv64) {
// TODO: https://github.com/ziglang/zig/issues/3338
return error.SkipZigTest;
}
testDivision();
comptime testDivision();
}
fn testDivision() void {
expect(div(u32, 13, 3) == 4);
expect(div(f16, 1.0, 2.0) == 0.5);
expect(div(f32, 1.0, 2.0) == 0.5);
expect(divExact(u32, 55, 11) == 5);
expect(divExact(i32, -55, 11) == -5);
expect(divExact(f16, 55.0, 11.0) == 5.0);
expect(divExact(f16, -55.0, 11.0) == -5.0);
expect(divExact(f32, 55.0, 11.0) == 5.0);
expect(divExact(f32, -55.0, 11.0) == -5.0);
expect(divFloor(i32, 5, 3) == 1);
expect(divFloor(i32, -5, 3) == -2);
expect(divFloor(f16, 5.0, 3.0) == 1.0);
expect(divFloor(f16, -5.0, 3.0) == -2.0);
expect(divFloor(f32, 5.0, 3.0) == 1.0);
expect(divFloor(f32, -5.0, 3.0) == -2.0);
expect(divFloor(i32, -0x80000000, -2) == 0x40000000);
expect(divFloor(i32, 0, -0x80000000) == 0);
expect(divFloor(i32, -0x40000001, 0x40000000) == -2);
expect(divFloor(i32, -0x80000000, 1) == -0x80000000);
expect(divFloor(i32, 10, 12) == 0);
expect(divFloor(i32, -14, 12) == -2);
expect(divFloor(i32, -2, 12) == -1);
expect(divTrunc(i32, 5, 3) == 1);
expect(divTrunc(i32, -5, 3) == -1);
expect(divTrunc(f16, 5.0, 3.0) == 1.0);
expect(divTrunc(f16, -5.0, 3.0) == -1.0);
expect(divTrunc(f32, 5.0, 3.0) == 1.0);
expect(divTrunc(f32, -5.0, 3.0) == -1.0);
expect(divTrunc(f64, 5.0, 3.0) == 1.0);
expect(divTrunc(f64, -5.0, 3.0) == -1.0);
expect(divTrunc(i32, 10, 12) == 0);
expect(divTrunc(i32, -14, 12) == -1);
expect(divTrunc(i32, -2, 12) == 0);
expect(mod(i32, 10, 12) == 10);
expect(mod(i32, -14, 12) == 10);
expect(mod(i32, -2, 12) == 10);
comptime {
expect(
1194735857077236777412821811143690633098347576 % 508740759824825164163191790951174292733114988 == 177254337427586449086438229241342047632117600,
);
expect(
@rem(-1194735857077236777412821811143690633098347576, 508740759824825164163191790951174292733114988) == -177254337427586449086438229241342047632117600,
);
expect(
1194735857077236777412821811143690633098347576 / 508740759824825164163191790951174292733114988 == 2,
);
expect(
@divTrunc(-1194735857077236777412821811143690633098347576, 508740759824825164163191790951174292733114988) == -2,
);
expect(
@divTrunc(1194735857077236777412821811143690633098347576, -508740759824825164163191790951174292733114988) == -2,
);
expect(
@divTrunc(-1194735857077236777412821811143690633098347576, -508740759824825164163191790951174292733114988) == 2,
);
expect(
4126227191251978491697987544882340798050766755606969681711 % 10 == 1,
);
}
}
fn div(comptime T: type, a: T, b: T) T {
return a / b;
}
fn divExact(comptime T: type, a: T, b: T) T {
return @divExact(a, b);
}
fn divFloor(comptime T: type, a: T, b: T) T {
return @divFloor(a, b);
}
fn divTrunc(comptime T: type, a: T, b: T) T {
return @divTrunc(a, b);
}
fn mod(comptime T: type, a: T, b: T) T {
return @mod(a, b);
}
test "@addWithOverflow" {
var result: u8 = undefined;
expect(@addWithOverflow(u8, 250, 100, &result));
expect(!@addWithOverflow(u8, 100, 150, &result));
expect(result == 250);
}
// TODO test mulWithOverflow
// TODO test subWithOverflow
test "@shlWithOverflow" {
var result: u16 = undefined;
expect(@shlWithOverflow(u16, 0b0010111111111111, 3, &result));
expect(!@shlWithOverflow(u16, 0b0010111111111111, 2, &result));
expect(result == 0b1011111111111100);
}
test "@clz" {
testClz();
comptime testClz();
}
fn testClz() void {
expect(clz(u8, 0b10001010) == 0);
expect(clz(u8, 0b00001010) == 4);
expect(clz(u8, 0b00011010) == 3);
expect(clz(u8, 0b00000000) == 8);
expect(clz(u128, 0xffffffffffffffff) == 64);
expect(clz(u128, 0x10000000000000000) == 63);
}
fn clz(comptime T: type, x: T) usize {
return @clz(T, x);
}
test "@ctz" {
testCtz();
comptime testCtz();
}
fn testCtz() void {
expect(ctz(u8, 0b10100000) == 5);
expect(ctz(u8, 0b10001010) == 1);
expect(ctz(u8, 0b00000000) == 8);
expect(ctz(u16, 0b00000000) == 16);
}
fn ctz(comptime T: type, x: T) usize {
return @ctz(T, x);
}
test "assignment operators" {
var i: u32 = 0;
i += 5;
expect(i == 5);
i -= 2;
expect(i == 3);
i *= 20;
expect(i == 60);
i /= 3;
expect(i == 20);
i %= 11;
expect(i == 9);
i <<= 1;
expect(i == 18);
i >>= 2;
expect(i == 4);
i = 6;
i &= 5;
expect(i == 4);
i ^= 6;
expect(i == 2);
i = 6;
i |= 3;
expect(i == 7);
}
test "three expr in a row" {
testThreeExprInARow(false, true);
comptime testThreeExprInARow(false, true);
}
fn testThreeExprInARow(f: bool, t: bool) void {
assertFalse(f or f or f);
assertFalse(t and t and f);
assertFalse(1 | 2 | 4 != 7);
assertFalse(3 ^ 6 ^ 8 != 13);
assertFalse(7 & 14 & 28 != 4);
assertFalse(9 << 1 << 2 != 9 << 3);
assertFalse(90 >> 1 >> 2 != 90 >> 3);
assertFalse(100 - 1 + 1000 != 1099);
assertFalse(5 * 4 / 2 % 3 != 1);
assertFalse(@as(i32, @as(i32, 5)) != 5);
assertFalse(!!false);
assertFalse(@as(i32, 7) != --(@as(i32, 7)));
}
fn assertFalse(b: bool) void {
expect(!b);
}
test "const number literal" {
const one = 1;
const eleven = ten + one;
expect(eleven == 11);
}
const ten = 10;
test "unsigned wrapping" {
testUnsignedWrappingEval(maxInt(u32));
comptime testUnsignedWrappingEval(maxInt(u32));
}
fn testUnsignedWrappingEval(x: u32) void {
const zero = x +% 1;
expect(zero == 0);
const orig = zero -% 1;
expect(orig == maxInt(u32));
}
test "signed wrapping" {
testSignedWrappingEval(maxInt(i32));
comptime testSignedWrappingEval(maxInt(i32));
}
fn testSignedWrappingEval(x: i32) void {
const min_val = x +% 1;
expect(min_val == minInt(i32));
const max_val = min_val -% 1;
expect(max_val == maxInt(i32));
}
test "negation wrapping" {
testNegationWrappingEval(minInt(i16));
comptime testNegationWrappingEval(minInt(i16));
}
fn testNegationWrappingEval(x: i16) void {
expect(x == -32768);
const neg = -%x;
expect(neg == -32768);
}
test "unsigned 64-bit division" {
test_u64_div();
comptime test_u64_div();
}
fn test_u64_div() void {
const result = divWithResult(1152921504606846976, 34359738365);
expect(result.quotient == 33554432);
expect(result.remainder == 100663296);
}
fn divWithResult(a: u64, b: u64) DivResult {
return DivResult{
.quotient = a / b,
.remainder = a % b,
};
}
const DivResult = struct {
quotient: u64,
remainder: u64,
};
test "binary not" {
expect(comptime x: {
break :x ~@as(u16, 0b1010101010101010) == 0b0101010101010101;
});
expect(comptime x: {
break :x ~@as(u64, 2147483647) == 18446744071562067968;
});
testBinaryNot(0b1010101010101010);
}
fn testBinaryNot(x: u16) void {
expect(~x == 0b0101010101010101);
}
test "small int addition" {
var x: @IntType(false, 2) = 0;
expect(x == 0);
x += 1;
expect(x == 1);
x += 1;
expect(x == 2);
x += 1;
expect(x == 3);
var result: @TypeOf(x) = 3;
expect(@addWithOverflow(@TypeOf(x), x, 1, &result));
expect(result == 0);
}
test "float equality" {
const x: f64 = 0.012;
const y: f64 = x + 1.0;
testFloatEqualityImpl(x, y);
comptime testFloatEqualityImpl(x, y);
}
fn testFloatEqualityImpl(x: f64, y: f64) void {
const y2 = x + 1.0;
expect(y == y2);
}
test "allow signed integer division/remainder when values are comptime known and positive or exact" {
expect(5 / 3 == 1);
expect(-5 / -3 == 1);
expect(-6 / 3 == -2);
expect(5 % 3 == 2);
expect(-6 % 3 == 0);
}
test "hex float literal parsing" {
comptime expect(0x1.0 == 1.0);
}
test "quad hex float literal parsing in range" {
const a = 0x1.af23456789bbaaab347645365cdep+5;
const b = 0x1.dedafcff354b6ae9758763545432p-9;
const c = 0x1.2f34dd5f437e849b4baab754cdefp+4534;
const d = 0x1.edcbff8ad76ab5bf46463233214fp-435;
}
test "quad hex float literal parsing accurate" {
const a: f128 = 0x1.1111222233334444555566667777p+0;
// implied 1 is dropped, with an exponent of 0 (0x3fff) after biasing.
const expected: u128 = 0x3fff1111222233334444555566667777;
expect(@bitCast(u128, a) == expected);
// non-normalized
const b: f128 = 0x11.111222233334444555566667777p-4;
expect(@bitCast(u128, b) == expected);
const S = struct {
fn doTheTest() void {
{
var f: f128 = 0x1.2eab345678439abcdefea56782346p+5;
expect(@bitCast(u128, f) == 0x40042eab345678439abcdefea5678234);
}
{
var f: f128 = 0x1.edcb34a235253948765432134674fp-1;
expect(@bitCast(u128, f) == 0x3ffeedcb34a235253948765432134674);
}
{
var f: f128 = 0x1.353e45674d89abacc3a2ebf3ff4ffp-50;
expect(@bitCast(u128, f) == 0x3fcd353e45674d89abacc3a2ebf3ff50);
}
{
var f: f128 = 0x1.ed8764648369535adf4be3214567fp-9;
expect(@bitCast(u128, f) == 0x3ff6ed8764648369535adf4be3214568);
}
const exp2ft = [_]f64{
0x1.6a09e667f3bcdp-1,
0x1.7a11473eb0187p-1,
0x1.8ace5422aa0dbp-1,
0x1.9c49182a3f090p-1,
0x1.ae89f995ad3adp-1,
0x1.c199bdd85529cp-1,
0x1.d5818dcfba487p-1,
0x1.ea4afa2a490dap-1,
0x1.0000000000000p+0,
0x1.0b5586cf9890fp+0,
0x1.172b83c7d517bp+0,
0x1.2387a6e756238p+0,
0x1.306fe0a31b715p+0,
0x1.3dea64c123422p+0,
0x1.4bfdad5362a27p+0,
0x1.5ab07dd485429p+0,
0x1.8p23,
0x1.62e430p-1,
0x1.ebfbe0p-3,
0x1.c6b348p-5,
0x1.3b2c9cp-7,
0x1.0p127,
-0x1.0p-149,
};
const answers = [_]u64{
0x3fe6a09e667f3bcd,
0x3fe7a11473eb0187,
0x3fe8ace5422aa0db,
0x3fe9c49182a3f090,
0x3feae89f995ad3ad,
0x3fec199bdd85529c,
0x3fed5818dcfba487,
0x3feea4afa2a490da,
0x3ff0000000000000,
0x3ff0b5586cf9890f,
0x3ff172b83c7d517b,
0x3ff2387a6e756238,
0x3ff306fe0a31b715,
0x3ff3dea64c123422,
0x3ff4bfdad5362a27,
0x3ff5ab07dd485429,
0x4168000000000000,
0x3fe62e4300000000,
0x3fcebfbe00000000,
0x3fac6b3480000000,
0x3f83b2c9c0000000,
0x47e0000000000000,
0xb6a0000000000000,
};
for (exp2ft) |x, i| {
expect(@bitCast(u64, x) == answers[i]);
}
}
};
S.doTheTest();
comptime S.doTheTest();
}
test "hex float literal within range" {
const a = 0x1.0p16383;
const b = 0x0.1p16387;
const c = 0x1.0p-16382;
}
test "truncating shift left" {
testShlTrunc(maxInt(u16));
comptime testShlTrunc(maxInt(u16));
}
fn testShlTrunc(x: u16) void {
const shifted = x << 1;
expect(shifted == 65534);
}
test "truncating shift right" {
testShrTrunc(maxInt(u16));
comptime testShrTrunc(maxInt(u16));
}
fn testShrTrunc(x: u16) void {
const shifted = x >> 1;
expect(shifted == 32767);
}
test "exact shift left" {
testShlExact(0b00110101);
comptime testShlExact(0b00110101);
}
fn testShlExact(x: u8) void {
const shifted = @shlExact(x, 2);
expect(shifted == 0b11010100);
}
test "exact shift right" {
testShrExact(0b10110100);
comptime testShrExact(0b10110100);
}
fn testShrExact(x: u8) void {
const shifted = @shrExact(x, 2);
expect(shifted == 0b00101101);
}
test "comptime_int addition" {
comptime {
expect(35361831660712422535336160538497375248 + 101752735581729509668353361206450473702 == 137114567242441932203689521744947848950);
expect(594491908217841670578297176641415611445982232488944558774612 + 390603545391089362063884922208143568023166603618446395589768 == 985095453608931032642182098849559179469148836107390954364380);
}
}
test "comptime_int multiplication" {
comptime {
expect(
45960427431263824329884196484953148229 * 128339149605334697009938835852565949723 == 5898522172026096622534201617172456926982464453350084962781392314016180490567,
);
expect(
594491908217841670578297176641415611445982232488944558774612 * 390603545391089362063884922208143568023166603618446395589768 == 232210647056203049913662402532976186578842425262306016094292237500303028346593132411865381225871291702600263463125370016,
);
}
}
test "comptime_int shifting" {
comptime {
expect((@as(u128, 1) << 127) == 0x80000000000000000000000000000000);
}
}
test "comptime_int multi-limb shift and mask" {
comptime {
var a = 0xefffffffa0000001eeeeeeefaaaaaaab;
expect(@as(u32, a & 0xffffffff) == 0xaaaaaaab);
a >>= 32;
expect(@as(u32, a & 0xffffffff) == 0xeeeeeeef);
a >>= 32;
expect(@as(u32, a & 0xffffffff) == 0xa0000001);
a >>= 32;
expect(@as(u32, a & 0xffffffff) == 0xefffffff);
a >>= 32;
expect(a == 0);
}
}
test "comptime_int multi-limb partial shift right" {
comptime {
var a = 0x1ffffffffeeeeeeee;
a >>= 16;
expect(a == 0x1ffffffffeeee);
}
}
test "xor" {
test_xor();
comptime test_xor();
}
fn test_xor() void {
expect(0xFF ^ 0x00 == 0xFF);
expect(0xF0 ^ 0x0F == 0xFF);
expect(0xFF ^ 0xF0 == 0x0F);
expect(0xFF ^ 0x0F == 0xF0);
expect(0xFF ^ 0xFF == 0x00);
}
test "comptime_int xor" {
comptime {
expect(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ^ 0x00000000000000000000000000000000 == 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
expect(0xFFFFFFFFFFFFFFFF0000000000000000 ^ 0x0000000000000000FFFFFFFFFFFFFFFF == 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
expect(0xFFFFFFFFFFFFFFFF0000000000000000 ^ 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0x0000000000000000FFFFFFFFFFFFFFFF);
expect(0x0000000000000000FFFFFFFFFFFFFFFF ^ 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0xFFFFFFFFFFFFFFFF0000000000000000);
expect(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ^ 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0x00000000000000000000000000000000);
expect(0xFFFFFFFF00000000FFFFFFFF00000000 ^ 0x00000000FFFFFFFF00000000FFFFFFFF == 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
expect(0xFFFFFFFF00000000FFFFFFFF00000000 ^ 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0x00000000FFFFFFFF00000000FFFFFFFF);
expect(0x00000000FFFFFFFF00000000FFFFFFFF ^ 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0xFFFFFFFF00000000FFFFFFFF00000000);
}
}
test "f128" {
test_f128();
comptime test_f128();
}
fn make_f128(x: f128) f128 {
return x;
}
fn test_f128() void {
expect(@sizeOf(f128) == 16);
expect(make_f128(1.0) == 1.0);
expect(make_f128(1.0) != 1.1);
expect(make_f128(1.0) > 0.9);
expect(make_f128(1.0) >= 0.9);
expect(make_f128(1.0) >= 1.0);
should_not_be_zero(1.0);
}
fn should_not_be_zero(x: f128) void {
expect(x != 0.0);
}
test "comptime float rem int" {
comptime {
var x = @as(f32, 1) % 2;
expect(x == 1.0);
}
}
test "remainder division" {
comptime remdiv(f16);
comptime remdiv(f32);
comptime remdiv(f64);
comptime remdiv(f128);
remdiv(f16);
remdiv(f64);
remdiv(f128);
}
fn remdiv(comptime T: type) void {
expect(@as(T, 1) == @as(T, 1) % @as(T, 2));
expect(@as(T, 1) == @as(T, 7) % @as(T, 3));
}
test "@sqrt" {
if (@import("builtin").arch == .riscv64) {
// TODO: https://github.com/ziglang/zig/issues/3338
return error.SkipZigTest;
}
testSqrt(f64, 12.0);
comptime testSqrt(f64, 12.0);
testSqrt(f32, 13.0);
comptime testSqrt(f32, 13.0);
testSqrt(f16, 13.0);
comptime testSqrt(f16, 13.0);
const x = 14.0;
const y = x * x;
const z = @sqrt(y);
comptime expect(z == x);
}
fn testSqrt(comptime T: type, x: T) void {
expect(@sqrt(x * x) == x);
}
test "comptime_int param and return" {
const a = comptimeAdd(35361831660712422535336160538497375248, 101752735581729509668353361206450473702);
expect(a == 137114567242441932203689521744947848950);
const b = comptimeAdd(594491908217841670578297176641415611445982232488944558774612, 390603545391089362063884922208143568023166603618446395589768);
expect(b == 985095453608931032642182098849559179469148836107390954364380);
}
fn comptimeAdd(comptime a: comptime_int, comptime b: comptime_int) comptime_int {
return a + b;
}
test "vector integer addition" {
const S = struct {
fn doTheTest() void {
var a: @Vector(4, i32) = [_]i32{ 1, 2, 3, 4 };
var b: @Vector(4, i32) = [_]i32{ 5, 6, 7, 8 };
var result = a + b;
var result_array: [4]i32 = result;
const expected = [_]i32{ 6, 8, 10, 12 };
expectEqualSlices(i32, &expected, &result_array);
}
};
S.doTheTest();
comptime S.doTheTest();
}
test "NaN comparison" {
if (@import("builtin").arch == .riscv64) {
// TODO: https://github.com/ziglang/zig/issues/3338
return error.SkipZigTest;
}
testNanEqNan(f16);
testNanEqNan(f32);
testNanEqNan(f64);
testNanEqNan(f128);
comptime testNanEqNan(f16);
comptime testNanEqNan(f32);
comptime testNanEqNan(f64);
comptime testNanEqNan(f128);
}
fn testNanEqNan(comptime F: type) void {
var nan1 = std.math.nan(F);
var nan2 = std.math.nan(F);
expect(nan1 != nan2);
expect(!(nan1 == nan2));
expect(!(nan1 > nan2));
expect(!(nan1 >= nan2));
expect(!(nan1 < nan2));
expect(!(nan1 <= nan2));
}
test "128-bit multiplication" {
var a: i128 = 3;
var b: i128 = 2;
var c = a * b;
expect(c == 6);
}
test "vector comparison" {
const S = struct {
fn doTheTest() void {
var a: @Vector(6, i32) = [_]i32{1, 3, -1, 5, 7, 9};
var b: @Vector(6, i32) = [_]i32{-1, 3, 0, 6, 10, -10};
expect(mem.eql(bool, &@as([6]bool, a < b), &[_]bool{false, false, true, true, true, false}));
expect(mem.eql(bool, &@as([6]bool, a <= b), &[_]bool{false, true, true, true, true, false}));
expect(mem.eql(bool, &@as([6]bool, a == b), &[_]bool{false, true, false, false, false, false}));
expect(mem.eql(bool, &@as([6]bool, a != b), &[_]bool{true, false, true, true, true, true}));
expect(mem.eql(bool, &@as([6]bool, a > b), &[_]bool{true, false, false, false, false, true}));
expect(mem.eql(bool, &@as([6]bool, a >= b), &[_]bool{true, true, false, false, false, true}));
}
};
S.doTheTest();
comptime S.doTheTest();
}
test "compare undefined literal with comptime_int" {
var x = undefined == 1;
// x is now undefined with type bool
x = true;
expect(x);
} | test/stage1/behavior/math.zig |
const std = @import("std");
const offsets = @import("offsets.zig");
const DocumentStore = @import("document_store.zig");
const analysis = @import("analysis.zig");
const ast = std.zig.ast;
usingnamespace @import("ast.zig");
pub const TokenType = enum(u32) {
type,
parameter,
variable,
enumMember,
field,
errorTag,
function,
keyword,
comment,
string,
number,
operator,
builtin,
label,
keywordLiteral,
};
pub const TokenModifiers = packed struct {
namespace: bool = false,
@"struct": bool = false,
@"enum": bool = false,
@"union": bool = false,
@"opaque": bool = false,
declaration: bool = false,
@"async": bool = false,
documentation: bool = false,
generic: bool = false,
fn toInt(self: TokenModifiers) u32 {
var res: u32 = 0;
inline for (std.meta.fields(TokenModifiers)) |field, i| {
if (@field(self, field.name)) {
res |= 1 << i;
}
}
return res;
}
fn set(self: *TokenModifiers, comptime field: []const u8) callconv(.Inline) void {
@field(self, field) = true;
}
};
const Comment = struct {
/// Length of the comment
length: u32,
/// Source index of the comment
start: u32,
};
const CommentList = std.ArrayList(Comment);
const Builder = struct {
handle: *DocumentStore.Handle,
current_token: ?ast.TokenIndex,
arr: std.ArrayList(u32),
encoding: offsets.Encoding,
comments: CommentList,
fn init(allocator: *std.mem.Allocator, handle: *DocumentStore.Handle, encoding: offsets.Encoding) Builder {
return Builder{
.handle = handle,
.current_token = null,
.arr = std.ArrayList(u32).init(allocator),
.encoding = encoding,
.comments = CommentList.init(allocator),
};
}
fn highlightComment(
self: *Builder,
prev_end: usize,
comment_start: usize,
comment_end: usize,
token_modifiers: TokenModifiers,
) !void {
const comment_delta = offsets.tokenRelativeLocation(
self.handle.tree,
prev_end,
comment_start,
self.encoding,
) catch return;
const comment_length = offsets.lineSectionLength(
self.handle.tree,
comment_start,
comment_end,
self.encoding,
) catch return;
try self.arr.appendSlice(&.{
@truncate(u32, comment_delta.line),
@truncate(u32, comment_delta.column),
@truncate(u32, comment_length),
@enumToInt(TokenType.comment),
token_modifiers.toInt(),
});
}
fn add(self: *Builder, token: ast.TokenIndex, token_type: TokenType, token_modifiers: TokenModifiers) !void {
const starts = self.handle.tree.tokens.items(.start);
var start_idx = if (self.current_token) |current_token|
starts[current_token]
else
0;
if (start_idx > starts[token])
return;
var comments_end: usize = start_idx;
var comments_start: usize = start_idx;
// Highlight comments in the gap
{
const source = self.handle.tree.source;
var state: enum { none, comment, doc_comment, comment_start } = .none;
var prev_byte = source[start_idx];
var i: usize = start_idx + 1;
while (i < starts[token]) : ({
prev_byte = source[i];
i += 1;
}) {
if (prev_byte == '/' and source[i] == '/') {
switch (state) {
.none => {
comments_start = i - 1;
state = .comment_start;
},
.comment_start => state = .doc_comment,
else => {},
}
continue;
} else if (prev_byte == '/' and source[i] == '!' and state == .comment_start) {
state = .doc_comment;
continue;
}
if (source[i] == '\n' and state != .none) {
try self.highlightComment(comments_end, comments_start, i, switch (state) {
.comment, .comment_start => .{},
.doc_comment => .{ .documentation = true },
else => unreachable,
});
comments_end = i;
state = .none;
} else if (state == .comment_start) {
state = .comment;
}
}
if (state != .none) {
try self.highlightComment(comments_end, comments_start, i, switch (state) {
.comment, .comment_start => .{},
.doc_comment => .{ .documentation = true },
else => unreachable,
});
}
}
const delta = offsets.tokenRelativeLocation(
self.handle.tree,
comments_start,
starts[token],
self.encoding,
) catch return;
try self.arr.appendSlice(&.{
@truncate(u32, delta.line),
@truncate(u32, delta.column),
@truncate(u32, offsets.tokenLength(self.handle.tree, token, self.encoding)),
@enumToInt(token_type),
token_modifiers.toInt(),
});
self.current_token = token;
}
fn toOwnedSlice(self: *Builder) []u32 {
return self.arr.toOwnedSlice();
}
};
fn writeToken(
builder: *Builder,
token_idx: ?ast.TokenIndex,
tok_type: TokenType,
) callconv(.Inline) !void {
return try writeTokenMod(builder, token_idx, tok_type, .{});
}
fn writeTokenMod(
builder: *Builder,
token_idx: ?ast.TokenIndex,
tok_type: TokenType,
tok_mod: TokenModifiers,
) callconv(.Inline) !void {
if (token_idx) |ti| {
try builder.add(ti, tok_type, tok_mod);
}
}
fn writeDocComments(builder: *Builder, tree: ast.Tree, doc: ast.TokenIndex) !void {
const token_tags = tree.tokens.items(.tag);
var tok_idx = doc;
while (token_tags[tok_idx] == .doc_comment or
token_tags[tok_idx] == .container_doc_comment) : (tok_idx += 1)
{
var tok_mod = TokenModifiers{};
tok_mod.set("documentation");
try builder.add(tok_idx, .comment, tok_mod);
}
}
fn fieldTokenType(container_decl: ast.Node.Index, handle: *DocumentStore.Handle) ?TokenType {
const main_token = handle.tree.nodes.items(.main_token)[container_decl];
if (main_token > handle.tree.tokens.len) return null;
return @as(?TokenType, switch (handle.tree.tokens.items(.tag)[main_token]) {
.keyword_struct => .field,
.keyword_union, .keyword_enum => .enumMember,
else => null,
});
}
/// This is used to highlight gaps between AST nodes.
/// These gaps can be just gaps between statements/declarations with comments inside them
/// Or malformed code.
const GapHighlighter = struct {
builder: *Builder,
current_idx: ast.TokenIndex,
// TODO More highlighting here
fn handleTok(self: *GapHighlighter, tok: ast.TokenIndex) !void {
const tok_id = self.builder.handle.tree.tokens.items(.tag)[tok];
if (tok_id == .container_doc_comment or tok_id == .doc_comment) {
try writeTokenMod(self.builder, tok, .comment, .{ .documentation = true });
} else if (@enumToInt(tok_id) >= @enumToInt(std.zig.Token.Tag.keyword_align) and
@enumToInt(tok_id) <= @enumToInt(std.zig.Token.Tag.keyword_while))
{
const tok_type: TokenType = switch (tok_id) {
.keyword_true,
.keyword_false,
.keyword_null,
.keyword_undefined,
.keyword_unreachable,
=> .keywordLiteral,
else => .keyword,
};
try writeToken(self.builder, tok, tok_type);
} else if (@enumToInt(tok_id) >= @enumToInt(std.zig.Token.Tag.bang) and
@enumToInt(tok_id) <= @enumToInt(std.zig.Token.Tag.tilde) and
tok_id != .period and tok_id != .comma and tok_id != .r_paren and
tok_id != .l_paren and tok_id != .r_brace and tok_id != .l_brace and
tok_id != .semicolon and tok_id != .colon)
{
try writeToken(self.builder, tok, .operator);
} else if (tok_id == .integer_literal or tok_id == .float_literal) {
try writeToken(self.builder, tok, .number);
} else if (tok_id == .string_literal or tok_id == .multiline_string_literal_line or tok_id == .char_literal) {
try writeToken(self.builder, tok, .string);
}
}
fn init(builder: *Builder, start: ast.TokenIndex) GapHighlighter {
return .{ .builder = builder, .current_idx = start };
}
fn next(self: *GapHighlighter, node: ast.Node.Index) !void {
const tree = self.builder.handle.tree;
if (self.current_idx > 0 and tree.tokens.items(.tag)[self.current_idx - 1] == .container_doc_comment) {
try self.handleTok(self.current_idx - 1);
}
var i = self.current_idx;
while (i < tree.firstToken(node)) : (i += 1) {
try self.handleTok(i);
}
self.current_idx = lastToken(tree, node) + 1;
}
fn end(self: *GapHighlighter, last: ast.TokenIndex) !void {
var i = self.current_idx;
while (i < last) : (i += 1) {
try self.handleTok(i);
}
}
};
fn colorIdentifierBasedOnType(builder: *Builder, type_node: analysis.TypeWithHandle, target_tok: ast.TokenIndex, tok_mod: TokenModifiers) !void {
const tree = builder.handle.tree;
if (type_node.type.is_type_val) {
var new_tok_mod = tok_mod;
if (type_node.isNamespace())
new_tok_mod.set("namespace")
else if (type_node.isStructType())
new_tok_mod.set("struct")
else if (type_node.isEnumType())
new_tok_mod.set("enum")
else if (type_node.isUnionType())
new_tok_mod.set("union")
else if (type_node.isOpaqueType())
new_tok_mod.set("opaque");
try writeTokenMod(builder, target_tok, .type, new_tok_mod);
} else if (type_node.isTypeFunc()) {
try writeTokenMod(builder, target_tok, .type, tok_mod);
} else if (type_node.isFunc()) {
var new_tok_mod = tok_mod;
if (type_node.isGenericFunc()) {
new_tok_mod.set("generic");
}
try writeTokenMod(builder, target_tok, .function, new_tok_mod);
} else {
try writeTokenMod(builder, target_tok, .variable, tok_mod);
}
}
fn writeNodeTokens(
builder: *Builder,
arena: *std.heap.ArenaAllocator,
store: *DocumentStore,
maybe_node: ?ast.Node.Index,
) error{OutOfMemory}!void {
const node = maybe_node orelse return;
const handle = builder.handle;
const tree = handle.tree;
const node_tags = tree.nodes.items(.tag);
const token_tags = tree.tokens.items(.tag);
const node_data = tree.nodes.items(.data);
const main_tokens = tree.nodes.items(.main_token);
if (node == 0 or node > node_data.len) return;
const FrameSize = @sizeOf(@Frame(writeNodeTokens));
var child_frame = try arena.child_allocator.alignedAlloc(u8, std.Target.stack_align, FrameSize);
defer arena.child_allocator.free(child_frame);
const tag = node_tags[node];
const main_token = main_tokens[node];
switch (tag) {
.root => unreachable,
.container_field,
.container_field_align,
.container_field_init,
=> try writeContainerField(builder, arena, store, node, .field, child_frame),
.@"errdefer" => {
try writeToken(builder, main_token, .keyword);
if (node_data[node].lhs != 0) {
const payload_tok = node_data[node].lhs;
try writeToken(builder, payload_tok - 1, .operator);
try writeToken(builder, payload_tok, .variable);
try writeToken(builder, payload_tok + 1, .operator);
}
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, node_data[node].rhs });
},
.block,
.block_semicolon,
.block_two,
.block_two_semicolon,
=> {
const first_tok = if (token_tags[main_token - 1] == .colon and token_tags[main_token - 2] == .identifier) block: {
try writeToken(builder, main_token - 2, .label);
break :block main_token + 1;
} else 0;
var gap_highlighter = GapHighlighter.init(builder, first_tok);
const statements: []const ast.Node.Index = switch (tag) {
.block, .block_semicolon => tree.extra_data[node_data[node].lhs..node_data[node].rhs],
.block_two, .block_two_semicolon => blk: {
const statements = &[_]ast.Node.Index{ node_data[node].lhs, node_data[node].rhs };
const len: usize = if (node_data[node].lhs == 0)
@as(usize, 0)
else if (node_data[node].rhs == 0)
@as(usize, 1)
else
@as(usize, 2);
break :blk statements[0..len];
},
else => unreachable,
};
for (statements) |child| {
try gap_highlighter.next(child);
if (node_tags[child].isContainerField()) {
try writeContainerField(builder, arena, store, child, .field, child_frame);
} else {
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, child });
}
}
try gap_highlighter.end(lastToken(tree, node));
},
.global_var_decl,
.local_var_decl,
.simple_var_decl,
.aligned_var_decl,
=> {
const var_decl = varDecl(tree, node).?;
if (analysis.getDocCommentTokenIndex(token_tags, main_token)) |comment_idx|
try writeDocComments(builder, tree, comment_idx);
try writeToken(builder, var_decl.visib_token, .keyword);
try writeToken(builder, var_decl.extern_export_token, .keyword);
try writeToken(builder, var_decl.threadlocal_token, .keyword);
try writeToken(builder, var_decl.comptime_token, .keyword);
try writeToken(builder, var_decl.ast.mut_token, .keyword);
if (try analysis.resolveTypeOfNode(store, arena, .{ .node = node, .handle = handle })) |decl_type| {
try colorIdentifierBasedOnType(builder, decl_type, var_decl.ast.mut_token + 1, .{ .declaration = true });
} else {
try writeTokenMod(builder, var_decl.ast.mut_token + 1, .variable, .{ .declaration = true });
}
if (var_decl.ast.type_node != 0)
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, var_decl.ast.type_node });
if (var_decl.ast.align_node != 0)
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, var_decl.ast.align_node });
if (var_decl.ast.section_node != 0)
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, var_decl.ast.section_node });
try writeToken(builder, var_decl.ast.mut_token + 2, .operator);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, var_decl.ast.init_node });
},
.@"usingnamespace" => {
const first_tok = tree.firstToken(node);
if (first_tok > 0 and token_tags[first_tok - 1] == .doc_comment)
try writeDocComments(builder, tree, first_tok - 1);
try writeToken(builder, if (token_tags[first_tok] == .keyword_pub) first_tok else null, .keyword);
try writeToken(builder, main_token, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, node_data[node].lhs });
},
.container_decl,
.container_decl_trailing,
.container_decl_two,
.container_decl_two_trailing,
.container_decl_arg,
.container_decl_arg_trailing,
.tagged_union,
.tagged_union_trailing,
.tagged_union_enum_tag,
.tagged_union_enum_tag_trailing,
.tagged_union_two,
.tagged_union_two_trailing,
=> {
var buf: [2]ast.Node.Index = undefined;
const decl: ast.full.ContainerDecl = switch (tag) {
.container_decl, .container_decl_trailing => tree.containerDecl(node),
.container_decl_two, .container_decl_two_trailing => tree.containerDeclTwo(&buf, node),
.container_decl_arg, .container_decl_arg_trailing => tree.containerDeclArg(node),
.tagged_union, .tagged_union_trailing => tree.taggedUnion(node),
.tagged_union_enum_tag, .tagged_union_enum_tag_trailing => tree.taggedUnionEnumTag(node),
.tagged_union_two, .tagged_union_two_trailing => tree.taggedUnionTwo(&buf, node),
else => unreachable,
};
try writeToken(builder, decl.layout_token, .keyword);
try writeToken(builder, decl.ast.main_token, .keyword);
if (decl.ast.enum_token) |enum_token| {
if (decl.ast.arg != 0)
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, decl.ast.arg })
else
try writeToken(builder, enum_token, .keyword);
} else if (decl.ast.arg != 0) try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, decl.ast.arg });
var gap_highlighter = GapHighlighter.init(builder, main_token + 1);
const field_token_type = fieldTokenType(node, handle);
for (decl.ast.members) |child| {
try gap_highlighter.next(child);
if (node_tags[child].isContainerField()) {
try writeContainerField(builder, arena, store, child, field_token_type, child_frame);
} else {
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, child });
}
}
try gap_highlighter.end(lastToken(tree, node));
},
.error_value => {
if (node_data[node].lhs != 0) {
try writeToken(builder, node_data[node].lhs - 1, .keyword);
}
try writeToken(builder, node_data[node].rhs, .errorTag);
},
.identifier => {
if (analysis.isTypeIdent(tree, main_token)) {
return try writeToken(builder, main_token, .type);
}
if (try analysis.lookupSymbolGlobal(
store,
arena,
handle,
tree.getNodeSource(node),
tree.tokens.items(.start)[main_token],
)) |child| {
if (child.decl.* == .param_decl) {
return try writeToken(builder, main_token, .parameter);
}
var bound_type_params = analysis.BoundTypeParams.init(&arena.allocator);
if (try child.resolveType(store, arena, &bound_type_params)) |decl_type| {
try colorIdentifierBasedOnType(builder, decl_type, main_token, .{});
} else {
try writeTokenMod(builder, main_token, .variable, .{});
}
}
},
.fn_proto,
.fn_proto_one,
.fn_proto_simple,
.fn_proto_multi,
.fn_decl,
=> {
var buf: [1]ast.Node.Index = undefined;
const fn_proto: ast.full.FnProto = fnProto(tree, node, &buf).?;
if (analysis.getDocCommentTokenIndex(token_tags, main_token)) |docs|
try writeDocComments(builder, tree, docs);
try writeToken(builder, fn_proto.visib_token, .keyword);
try writeToken(builder, fn_proto.extern_export_token, .keyword);
try writeToken(builder, fn_proto.lib_name, .string);
try writeToken(builder, fn_proto.ast.fn_token, .keyword);
const func_name_tok_type: TokenType = if (analysis.isTypeFunction(tree, fn_proto))
.type
else
.function;
const tok_mod = if (analysis.isGenericFunction(tree, fn_proto))
TokenModifiers{ .generic = true }
else
TokenModifiers{};
try writeTokenMod(builder, fn_proto.name_token, func_name_tok_type, tok_mod);
var it = fn_proto.iterate(tree);
while (it.next()) |param_decl| {
if (param_decl.first_doc_comment) |docs| try writeDocComments(builder, tree, docs);
try writeToken(builder, param_decl.comptime_noalias, .keyword);
try writeTokenMod(builder, param_decl.name_token, .parameter, .{ .declaration = true });
if (param_decl.anytype_ellipsis3) |any_token| {
try writeToken(builder, any_token, .type);
} else if (param_decl.type_expr != 0) try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, param_decl.type_expr });
}
if (fn_proto.ast.align_expr != 0)
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, fn_proto.ast.align_expr });
if (fn_proto.ast.section_expr != 0)
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, fn_proto.ast.section_expr });
if (fn_proto.ast.callconv_expr != 0)
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, fn_proto.ast.callconv_expr });
if (fn_proto.ast.return_type != 0)
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, fn_proto.ast.return_type });
if (tag == .fn_decl)
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, node_data[node].rhs });
},
.anyframe_type => {
try writeToken(builder, main_token, .type);
if (node_data[node].rhs != 0) {
try writeToken(builder, node_data[node].lhs, .type);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, node_data[node].rhs });
}
},
.@"defer" => {
try writeToken(builder, main_token, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, node_data[node].rhs });
},
.@"comptime",
.@"nosuspend",
=> {
if (analysis.getDocCommentTokenIndex(token_tags, main_token)) |doc|
try writeDocComments(builder, tree, doc);
try writeToken(builder, main_token, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, node_data[node].lhs });
},
.@"switch",
.switch_comma,
=> {
try writeToken(builder, main_token, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, node_data[node].lhs });
const extra = tree.extraData(node_data[node].rhs, ast.Node.SubRange);
const cases = tree.extra_data[extra.start..extra.end];
var gap_highlighter = GapHighlighter.init(builder, lastToken(tree, node_data[node].lhs) + 1);
for (cases) |case_node| {
try gap_highlighter.next(case_node);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, case_node });
}
try gap_highlighter.end(lastToken(tree, node));
},
.switch_case_one,
.switch_case,
=> {
const switch_case = if (tag == .switch_case) tree.switchCase(node) else tree.switchCaseOne(node);
for (switch_case.ast.values) |item_node| try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, item_node });
// check it it's 'else'
if (switch_case.ast.values.len == 0) try writeToken(builder, switch_case.ast.arrow_token - 1, .keyword);
try writeToken(builder, switch_case.ast.arrow_token, .operator);
if (switch_case.payload_token) |payload_token| {
const p_token = @boolToInt(token_tags[payload_token] == .asterisk);
try writeToken(builder, p_token, .variable);
}
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, switch_case.ast.target_expr });
},
.@"while",
.while_simple,
.while_cont,
.for_simple,
.@"for",
=> {
const while_node = whileAst(tree, node).?;
try writeToken(builder, while_node.label_token, .label);
try writeToken(builder, while_node.inline_token, .keyword);
try writeToken(builder, while_node.ast.while_token, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, while_node.ast.cond_expr });
if (while_node.payload_token) |payload| {
try writeToken(builder, payload - 1, .operator);
try writeToken(builder, payload, .variable);
var r_pipe = payload + 1;
if (token_tags[r_pipe] == .comma) {
r_pipe += 1;
try writeToken(builder, r_pipe, .variable);
r_pipe += 1;
}
try writeToken(builder, r_pipe, .operator);
}
if (while_node.ast.cont_expr != 0)
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, while_node.ast.cont_expr });
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, while_node.ast.then_expr });
if (while_node.ast.else_expr != 0) {
try writeToken(builder, while_node.else_token, .keyword);
if (while_node.error_token) |err_token| {
try writeToken(builder, err_token - 1, .operator);
try writeToken(builder, err_token, .variable);
try writeToken(builder, err_token + 1, .operator);
}
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, while_node.ast.else_expr });
}
},
.@"if",
.if_simple,
=> {
const if_node = ifFull(tree, node);
try writeToken(builder, if_node.ast.if_token, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, if_node.ast.cond_expr });
if (if_node.payload_token) |payload| {
// if (?x) |x|
try writeToken(builder, payload - 1, .operator); // |
try writeToken(builder, payload, .variable); // x
try writeToken(builder, payload + 1, .operator); // |
}
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, if_node.ast.then_expr });
if (if_node.ast.else_expr != 0) {
try writeToken(builder, if_node.else_token, .keyword);
if (if_node.error_token) |err_token| {
// else |err|
try writeToken(builder, err_token - 1, .operator); // |
try writeToken(builder, err_token, .variable); // err
try writeToken(builder, err_token + 1, .operator); // |
}
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, if_node.ast.else_expr });
}
},
.array_init,
.array_init_comma,
.array_init_one,
.array_init_one_comma,
.array_init_dot,
.array_init_dot_comma,
.array_init_dot_two,
.array_init_dot_two_comma,
=> {
var buf: [2]ast.Node.Index = undefined;
const array_init: ast.full.ArrayInit = switch (tag) {
.array_init, .array_init_comma => tree.arrayInit(node),
.array_init_one, .array_init_one_comma => tree.arrayInitOne(buf[0..1], node),
.array_init_dot, .array_init_dot_comma => tree.arrayInitDot(node),
.array_init_dot_two, .array_init_dot_two_comma => tree.arrayInitDotTwo(&buf, node),
else => unreachable,
};
if (array_init.ast.type_expr != 0)
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, array_init.ast.type_expr });
for (array_init.ast.elements) |elem| try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, elem });
},
.struct_init,
.struct_init_comma,
.struct_init_dot,
.struct_init_dot_comma,
.struct_init_one,
.struct_init_one_comma,
.struct_init_dot_two,
.struct_init_dot_two_comma,
=> {
var buf: [2]ast.Node.Index = undefined;
const struct_init: ast.full.StructInit = switch (tag) {
.struct_init, .struct_init_comma => tree.structInit(node),
.struct_init_dot, .struct_init_dot_comma => tree.structInitDot(node),
.struct_init_one, .struct_init_one_comma => tree.structInitOne(buf[0..1], node),
.struct_init_dot_two, .struct_init_dot_two_comma => tree.structInitDotTwo(&buf, node),
else => unreachable,
};
var field_token_type: ?TokenType = null;
if (struct_init.ast.type_expr != 0) {
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, struct_init.ast.type_expr });
field_token_type = if (try analysis.resolveTypeOfNode(store, arena, .{
.node = struct_init.ast.type_expr,
.handle = handle,
})) |struct_type| switch (struct_type.type.data) {
.other => |type_node| if (isContainer(struct_type.handle.tree, type_node))
fieldTokenType(type_node, struct_type.handle)
else
null,
else => null,
} else null;
}
var gap_highlighter = GapHighlighter.init(builder, struct_init.ast.lbrace);
for (struct_init.ast.fields) |field_init| {
try gap_highlighter.next(field_init);
const init_token = tree.firstToken(field_init);
try writeToken(builder, init_token - 3, field_token_type orelse .field); // '.'
try writeToken(builder, init_token - 2, field_token_type orelse .field); // name
try writeToken(builder, init_token - 1, .operator); // '='
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, field_init });
}
try gap_highlighter.end(lastToken(tree, node));
},
.call,
.call_comma,
.async_call,
.async_call_comma,
.call_one,
.call_one_comma,
.async_call_one,
.async_call_one_comma,
=> {
var params: [1]ast.Node.Index = undefined;
const call: ast.full.Call = switch (tag) {
.call, .call_comma, .async_call, .async_call_comma => tree.callFull(node),
.call_one, .call_one_comma, .async_call_one, .async_call_one_comma => tree.callOne(¶ms, node),
else => unreachable,
};
try writeToken(builder, call.async_token, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, call.ast.fn_expr });
if (builder.current_token) |curr_tok| {
if (curr_tok != lastToken(tree, call.ast.fn_expr) and token_tags[lastToken(tree, call.ast.fn_expr)] == .identifier) {
try writeToken(builder, lastToken(tree, call.ast.fn_expr), .function);
}
}
for (call.ast.params) |param| try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, param });
},
.slice,
.slice_open,
.slice_sentinel,
=> {
const slice: ast.full.Slice = switch (tag) {
.slice => tree.slice(node),
.slice_open => tree.sliceOpen(node),
.slice_sentinel => tree.sliceSentinel(node),
else => unreachable,
};
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, slice.ast.sliced });
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, slice.ast.start });
try writeToken(builder, lastToken(tree, slice.ast.start) + 1, .operator);
if (slice.ast.end != 0)
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, slice.ast.end });
if (slice.ast.sentinel != 0)
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, slice.ast.sentinel });
},
.array_access => {
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, node_data[node].lhs });
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, node_data[node].rhs });
},
.deref => {
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, node_data[node].lhs });
try writeToken(builder, main_token, .operator);
},
.unwrap_optional => {
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, node_data[node].lhs });
try writeToken(builder, main_token + 1, .operator);
},
.grouped_expression => {
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, node_data[node].lhs });
},
.@"break",
.@"continue",
=> {
try writeToken(builder, main_token, .keyword);
if (node_data[node].lhs != 0)
try writeToken(builder, node_data[node].lhs, .label);
if (node_data[node].rhs != 0)
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, node_data[node].rhs });
},
.@"suspend", .@"return" => {
try writeToken(builder, main_token, .keyword);
if (node_data[node].lhs != 0)
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, node_data[node].lhs });
},
.integer_literal,
.float_literal,
=> {
try writeToken(builder, main_token, .number);
},
.enum_literal => {
try writeToken(builder, main_token - 1, .enumMember);
try writeToken(builder, main_token, .enumMember);
},
.builtin_call,
.builtin_call_comma,
.builtin_call_two,
.builtin_call_two_comma,
=> {
const data = node_data[node];
const params = switch (tag) {
.builtin_call, .builtin_call_comma => tree.extra_data[data.lhs..data.rhs],
.builtin_call_two, .builtin_call_two_comma => if (data.lhs == 0)
&[_]ast.Node.Index{}
else if (data.rhs == 0)
&[_]ast.Node.Index{data.lhs}
else
&[_]ast.Node.Index{ data.lhs, data.rhs },
else => unreachable,
};
try writeToken(builder, main_token, .builtin);
for (params) |param|
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, param });
},
.string_literal,
.char_literal,
=> {
try writeToken(builder, main_token, .string);
},
.multiline_string_literal => {
var cur_tok = main_token;
const last_tok = node_data[node].rhs;
while (cur_tok <= last_tok) : (cur_tok += 1) try writeToken(builder, cur_tok, .string);
},
.true_literal,
.false_literal,
.null_literal,
.undefined_literal,
.unreachable_literal,
=> {
try writeToken(builder, main_token, .keywordLiteral);
},
.error_set_decl => {
try writeToken(builder, main_token, .keyword);
},
.@"asm",
.asm_output,
.asm_input,
.asm_simple,
=> {
const asm_node: ast.full.Asm = switch (tag) {
.@"asm" => tree.asmFull(node),
.asm_simple => tree.asmSimple(node),
else => return, // TODO Inputs, outputs
};
try writeToken(builder, main_token, .keyword);
try writeToken(builder, asm_node.volatile_token, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, asm_node.ast.template });
// TODO Inputs, outputs.
},
.@"anytype" => {
try writeToken(builder, main_token, .type);
},
.test_decl => {
if (analysis.getDocCommentTokenIndex(token_tags, main_token)) |doc|
try writeDocComments(builder, tree, doc);
try writeToken(builder, main_token, .keyword);
if (token_tags[main_token + 1] == .string_literal)
try writeToken(builder, main_token + 1, .string);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, node_data[node].rhs });
},
.@"catch" => {
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, node_data[node].lhs });
try writeToken(builder, main_token, .keyword);
if (token_tags[main_token + 1] == .pipe)
try writeToken(builder, main_token + 1, .variable);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, node_data[node].rhs });
},
.add,
.add_wrap,
.array_cat,
.array_mult,
.assign,
.assign_bit_and,
.assign_bit_or,
.assign_bit_shift_left,
.assign_bit_shift_right,
.assign_bit_xor,
.assign_div,
.assign_sub,
.assign_sub_wrap,
.assign_mod,
.assign_add,
.assign_add_wrap,
.assign_mul,
.assign_mul_wrap,
.bang_equal,
.bit_and,
.bit_or,
.bit_shift_left,
.bit_shift_right,
.bit_xor,
.bool_and,
.bool_or,
.div,
.equal_equal,
.error_union,
.greater_or_equal,
.greater_than,
.less_or_equal,
.less_than,
.merge_error_sets,
.mod,
.mul,
.mul_wrap,
.switch_range,
.sub,
.sub_wrap,
.@"orelse",
=> {
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, node_data[node].lhs });
const token_type: TokenType = switch (tag) {
.bool_and, .bool_or => .keyword,
else => .operator,
};
try writeToken(builder, main_token, token_type);
if (node_data[node].rhs != 0)
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, node_data[node].rhs });
},
.field_access => {
const data = node_data[node];
if (data.rhs == 0) return;
const rhs_str = tree.tokenSlice(data.rhs);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, data.lhs });
// TODO This is basically exactly the same as what is done in analysis.resolveTypeOfNode, with the added
// writeToken code.
// Maybe we can hook into it insead? Also applies to Identifier and VarDecl
var bound_type_params = analysis.BoundTypeParams.init(&arena.allocator);
const lhs_type = try analysis.resolveFieldAccessLhsType(
store,
arena,
(try analysis.resolveTypeOfNodeInternal(store, arena, .{
.node = data.lhs,
.handle = handle,
}, &bound_type_params)) orelse return,
&bound_type_params,
);
const left_type_node = switch (lhs_type.type.data) {
.other => |n| n,
else => return,
};
if (try analysis.lookupSymbolContainer(store, arena, .{
.node = left_type_node,
.handle = lhs_type.handle,
}, rhs_str, !lhs_type.type.is_type_val)) |decl_type| {
switch (decl_type.decl.*) {
.ast_node => |decl_node| {
if (decl_type.handle.tree.nodes.items(.tag)[decl_node].isContainerField()) {
const tok_type: ?TokenType = if (isContainer(lhs_type.handle.tree, left_type_node))
fieldTokenType(decl_node, lhs_type.handle)
else if (left_type_node == 0)
TokenType.field
else
null;
if (tok_type) |tt| try writeToken(builder, data.rhs, tt);
return;
} else if (decl_type.handle.tree.nodes.items(.tag)[decl_node] == .error_value) {
try writeToken(builder, data.rhs, .errorTag);
}
},
else => {},
}
if (try decl_type.resolveType(store, arena, &bound_type_params)) |resolved_type| {
try colorIdentifierBasedOnType(builder, resolved_type, data.rhs, .{});
}
}
},
.ptr_type,
.ptr_type_aligned,
.ptr_type_bit_range,
.ptr_type_sentinel,
=> {
const ptr_type = ptrType(tree, node).?;
if (ptr_type.size == .One and token_tags[main_token] == .asterisk_asterisk and
main_token == main_tokens[ptr_type.ast.child_type])
{
return try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, ptr_type.ast.child_type });
}
if (ptr_type.size == .One) try writeToken(builder, main_token, .operator);
if (ptr_type.ast.sentinel != 0) {
return try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, ptr_type.ast.sentinel });
}
try writeToken(builder, ptr_type.allowzero_token, .keyword);
if (ptr_type.ast.align_node != 0) {
const first_tok = tree.firstToken(ptr_type.ast.align_node);
try writeToken(builder, first_tok - 2, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, ptr_type.ast.align_node });
if (ptr_type.ast.bit_range_start != 0) {
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, ptr_type.ast.bit_range_start });
try writeToken(builder, tree.firstToken(ptr_type.ast.bit_range_end - 1), .operator);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, ptr_type.ast.bit_range_end });
}
}
try writeToken(builder, ptr_type.const_token, .keyword);
try writeToken(builder, ptr_type.volatile_token, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, ptr_type.ast.child_type });
},
.array_type,
.array_type_sentinel,
=> {
const array_type: ast.full.ArrayType = if (tag == .array_type)
tree.arrayType(node)
else
tree.arrayTypeSentinel(node);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, array_type.ast.elem_count });
if (array_type.ast.sentinel != 0)
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, array_type.ast.sentinel });
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, array_type.ast.elem_type });
},
.address_of,
.bit_not,
.bool_not,
.optional_type,
.negation,
.negation_wrap,
=> {
try writeToken(builder, main_token, .operator);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, node_data[node].lhs });
},
.@"try",
.@"resume",
.@"await",
=> {
try writeToken(builder, main_token, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, node_data[node].lhs });
},
.anyframe_literal => try writeToken(builder, main_token, .keyword),
}
}
fn writeContainerField(
builder: *Builder,
arena: *std.heap.ArenaAllocator,
store: *DocumentStore,
node: ast.Node.Index,
field_token_type: ?TokenType,
child_frame: anytype,
) !void {
const tree = builder.handle.tree;
const container_field = containerField(tree, node).?;
const base = tree.nodes.items(.main_token)[node];
const tokens = tree.tokens.items(.tag);
if (analysis.getDocCommentTokenIndex(tokens, base)) |docs|
try writeDocComments(builder, tree, docs);
try writeToken(builder, container_field.comptime_token, .keyword);
if (field_token_type) |tok_type| try writeToken(builder, container_field.ast.name_token, tok_type);
if (container_field.ast.type_expr != 0) {
if (container_field.ast.align_expr != 0) {
try writeToken(builder, tree.firstToken(container_field.ast.align_expr) - 2, .keyword);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, container_field.ast.align_expr });
}
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, container_field.ast.type_expr });
}
if (container_field.ast.value_expr != 0) block: {
const eq_tok: ast.TokenIndex = if (container_field.ast.type_expr != 0)
lastToken(tree, container_field.ast.type_expr) + 1
else if (container_field.ast.align_expr != 0)
lastToken(tree, container_field.ast.align_expr) + 1
else
break :block; // Check this, I believe it is correct.
try writeToken(builder, eq_tok, .operator);
try await @asyncCall(child_frame, {}, writeNodeTokens, .{ builder, arena, store, container_field.ast.value_expr });
}
}
// TODO Range version, edit version.
pub fn writeAllSemanticTokens(arena: *std.heap.ArenaAllocator, store: *DocumentStore, handle: *DocumentStore.Handle, encoding: offsets.Encoding) ![]u32 {
var builder = Builder.init(arena.child_allocator, handle, encoding);
// reverse the ast from the root declarations
var gap_highlighter = GapHighlighter.init(&builder, 0);
var buf: [2]ast.Node.Index = undefined;
for (declMembers(handle.tree, 0, &buf)) |child| {
try gap_highlighter.next(child);
try writeNodeTokens(&builder, arena, store, child);
}
try gap_highlighter.end(@truncate(u32, handle.tree.tokens.len) - 1);
return builder.toOwnedSlice();
} | src/semantic_tokens.zig |
const std = @import("../std.zig");
const builtin = std.builtin;
const io = std.io;
const assert = std.debug.assert;
const testing = std.testing;
const trait = std.meta.trait;
const meta = std.meta;
const math = std.math;
/// Creates a stream which allows for reading bit fields from another stream
pub fn BitReader(endian: builtin.Endian, comptime ReaderType: type) type {
return struct {
forward_reader: ReaderType,
bit_buffer: u7,
bit_count: u3,
pub const Error = ReaderType.Error;
pub const Reader = io.Reader(*Self, Error, read);
/// Deprecated: use `Reader`
pub const InStream = io.InStream(*Self, Error, read);
const Self = @This();
const u8_bit_count = comptime meta.bitCount(u8);
const u7_bit_count = comptime meta.bitCount(u7);
const u4_bit_count = comptime meta.bitCount(u4);
pub fn init(forward_reader: ReaderType) Self {
return Self{
.forward_reader = forward_reader,
.bit_buffer = 0,
.bit_count = 0,
};
}
/// Reads `bits` bits from the stream and returns a specified unsigned int type
/// containing them in the least significant end, returning an error if the
/// specified number of bits could not be read.
pub fn readBitsNoEof(self: *Self, comptime U: type, bits: usize) !U {
var n: usize = undefined;
const result = try self.readBits(U, bits, &n);
if (n < bits) return error.EndOfStream;
return result;
}
/// Reads `bits` bits from the stream and returns a specified unsigned int type
/// containing them in the least significant end. The number of bits successfully
/// read is placed in `out_bits`, as reaching the end of the stream is not an error.
pub fn readBits(self: *Self, comptime U: type, bits: usize, out_bits: *usize) Error!U {
comptime assert(trait.isUnsignedInt(U));
//by extending the buffer to a minimum of u8 we can cover a number of edge cases
// related to shifting and casting.
const u_bit_count = comptime meta.bitCount(U);
const buf_bit_count = bc: {
assert(u_bit_count >= bits);
break :bc if (u_bit_count <= u8_bit_count) u8_bit_count else u_bit_count;
};
const Buf = std.meta.Int(.unsigned, buf_bit_count);
const BufShift = math.Log2Int(Buf);
out_bits.* = @as(usize, 0);
if (U == u0 or bits == 0) return 0;
var out_buffer = @as(Buf, 0);
if (self.bit_count > 0) {
const n = if (self.bit_count >= bits) @intCast(u3, bits) else self.bit_count;
const shift = u7_bit_count - n;
switch (endian) {
.Big => {
out_buffer = @as(Buf, self.bit_buffer >> shift);
if (n >= u7_bit_count)
self.bit_buffer = 0
else
self.bit_buffer <<= n;
},
.Little => {
const value = (self.bit_buffer << shift) >> shift;
out_buffer = @as(Buf, value);
if (n >= u7_bit_count)
self.bit_buffer = 0
else
self.bit_buffer >>= n;
},
}
self.bit_count -= n;
out_bits.* = n;
}
//at this point we know bit_buffer is empty
//copy bytes until we have enough bits, then leave the rest in bit_buffer
while (out_bits.* < bits) {
const n = bits - out_bits.*;
const next_byte = self.forward_reader.readByte() catch |err| {
if (err == error.EndOfStream) {
return @intCast(U, out_buffer);
}
//@BUG: See #1810. Not sure if the bug is that I have to do this for some
// streams, or that I don't for streams with emtpy errorsets.
return @errSetCast(Error, err);
};
switch (endian) {
.Big => {
if (n >= u8_bit_count) {
out_buffer <<= @intCast(u3, u8_bit_count - 1);
out_buffer <<= 1;
out_buffer |= @as(Buf, next_byte);
out_bits.* += u8_bit_count;
continue;
}
const shift = @intCast(u3, u8_bit_count - n);
out_buffer <<= @intCast(BufShift, n);
out_buffer |= @as(Buf, next_byte >> shift);
out_bits.* += n;
self.bit_buffer = @truncate(u7, next_byte << @intCast(u3, n - 1));
self.bit_count = shift;
},
.Little => {
if (n >= u8_bit_count) {
out_buffer |= @as(Buf, next_byte) << @intCast(BufShift, out_bits.*);
out_bits.* += u8_bit_count;
continue;
}
const shift = @intCast(u3, u8_bit_count - n);
const value = (next_byte << shift) >> shift;
out_buffer |= @as(Buf, value) << @intCast(BufShift, out_bits.*);
out_bits.* += n;
self.bit_buffer = @truncate(u7, next_byte >> @intCast(u3, n));
self.bit_count = shift;
},
}
}
return @intCast(U, out_buffer);
}
pub fn alignToByte(self: *Self) void {
self.bit_buffer = 0;
self.bit_count = 0;
}
pub fn read(self: *Self, buffer: []u8) Error!usize {
var out_bits: usize = undefined;
var out_bits_total = @as(usize, 0);
//@NOTE: I'm not sure this is a good idea, maybe alignToByte should be forced
if (self.bit_count > 0) {
for (buffer) |*b, i| {
b.* = try self.readBits(u8, u8_bit_count, &out_bits);
out_bits_total += out_bits;
}
const incomplete_byte = @boolToInt(out_bits_total % u8_bit_count > 0);
return (out_bits_total / u8_bit_count) + incomplete_byte;
}
return self.forward_reader.read(buffer);
}
pub fn reader(self: *Self) Reader {
return .{ .context = self };
}
/// Deprecated: use `reader`
pub fn inStream(self: *Self) InStream {
return .{ .context = self };
}
};
}
pub fn bitReader(
comptime endian: builtin.Endian,
underlying_stream: anytype,
) BitReader(endian, @TypeOf(underlying_stream)) {
return BitReader(endian, @TypeOf(underlying_stream)).init(underlying_stream);
}
test "api coverage" {
const mem_be = [_]u8{ 0b11001101, 0b00001011 };
const mem_le = [_]u8{ 0b00011101, 0b10010101 };
var mem_in_be = io.fixedBufferStream(&mem_be);
var bit_stream_be = bitReader(.Big, mem_in_be.reader());
var out_bits: usize = undefined;
const expect = testing.expect;
const expectError = testing.expectError;
expect(1 == try bit_stream_be.readBits(u2, 1, &out_bits));
expect(out_bits == 1);
expect(2 == try bit_stream_be.readBits(u5, 2, &out_bits));
expect(out_bits == 2);
expect(3 == try bit_stream_be.readBits(u128, 3, &out_bits));
expect(out_bits == 3);
expect(4 == try bit_stream_be.readBits(u8, 4, &out_bits));
expect(out_bits == 4);
expect(5 == try bit_stream_be.readBits(u9, 5, &out_bits));
expect(out_bits == 5);
expect(1 == try bit_stream_be.readBits(u1, 1, &out_bits));
expect(out_bits == 1);
mem_in_be.pos = 0;
bit_stream_be.bit_count = 0;
expect(0b110011010000101 == try bit_stream_be.readBits(u15, 15, &out_bits));
expect(out_bits == 15);
mem_in_be.pos = 0;
bit_stream_be.bit_count = 0;
expect(0b1100110100001011 == try bit_stream_be.readBits(u16, 16, &out_bits));
expect(out_bits == 16);
_ = try bit_stream_be.readBits(u0, 0, &out_bits);
expect(0 == try bit_stream_be.readBits(u1, 1, &out_bits));
expect(out_bits == 0);
expectError(error.EndOfStream, bit_stream_be.readBitsNoEof(u1, 1));
var mem_in_le = io.fixedBufferStream(&mem_le);
var bit_stream_le = bitReader(.Little, mem_in_le.reader());
expect(1 == try bit_stream_le.readBits(u2, 1, &out_bits));
expect(out_bits == 1);
expect(2 == try bit_stream_le.readBits(u5, 2, &out_bits));
expect(out_bits == 2);
expect(3 == try bit_stream_le.readBits(u128, 3, &out_bits));
expect(out_bits == 3);
expect(4 == try bit_stream_le.readBits(u8, 4, &out_bits));
expect(out_bits == 4);
expect(5 == try bit_stream_le.readBits(u9, 5, &out_bits));
expect(out_bits == 5);
expect(1 == try bit_stream_le.readBits(u1, 1, &out_bits));
expect(out_bits == 1);
mem_in_le.pos = 0;
bit_stream_le.bit_count = 0;
expect(0b001010100011101 == try bit_stream_le.readBits(u15, 15, &out_bits));
expect(out_bits == 15);
mem_in_le.pos = 0;
bit_stream_le.bit_count = 0;
expect(0b1001010100011101 == try bit_stream_le.readBits(u16, 16, &out_bits));
expect(out_bits == 16);
_ = try bit_stream_le.readBits(u0, 0, &out_bits);
expect(0 == try bit_stream_le.readBits(u1, 1, &out_bits));
expect(out_bits == 0);
expectError(error.EndOfStream, bit_stream_le.readBitsNoEof(u1, 1));
} | lib/std/io/bit_reader.zig |
const std = @import("../../index.zig");
const builtin = @import("builtin");
const os = std.os;
const unicode = std.unicode;
const windows = std.os.windows;
const assert = std.debug.assert;
const mem = std.mem;
const BufMap = std.BufMap;
const cstr = std.cstr;
// > The maximum path of 32,767 characters is approximate, because the "\\?\"
// > prefix may be expanded to a longer string by the system at run time, and
// > this expansion applies to the total length.
// from https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#maximum-path-length-limitation
pub const PATH_MAX_WIDE = 32767;
pub const WaitError = error{
WaitAbandoned,
WaitTimeOut,
/// See https://github.com/ziglang/zig/issues/1396
Unexpected,
};
pub fn windowsWaitSingle(handle: windows.HANDLE, milliseconds: windows.DWORD) WaitError!void {
const result = windows.WaitForSingleObject(handle, milliseconds);
return switch (result) {
windows.WAIT_ABANDONED => error.WaitAbandoned,
windows.WAIT_OBJECT_0 => {},
windows.WAIT_TIMEOUT => error.WaitTimeOut,
windows.WAIT_FAILED => x: {
const err = windows.GetLastError();
break :x switch (err) {
else => os.unexpectedErrorWindows(err),
};
},
else => error.Unexpected,
};
}
pub fn windowsClose(handle: windows.HANDLE) void {
assert(windows.CloseHandle(handle) != 0);
}
pub const ReadError = error{
OperationAborted,
BrokenPipe,
Unexpected,
};
pub const WriteError = error{
SystemResources,
OperationAborted,
BrokenPipe,
/// See https://github.com/ziglang/zig/issues/1396
Unexpected,
};
pub fn windowsWrite(handle: windows.HANDLE, bytes: []const u8) WriteError!void {
var bytes_written: windows.DWORD = undefined;
if (windows.WriteFile(handle, bytes.ptr, @intCast(u32, bytes.len), &bytes_written, null) == 0) {
const err = windows.GetLastError();
return switch (err) {
windows.ERROR.INVALID_USER_BUFFER => WriteError.SystemResources,
windows.ERROR.NOT_ENOUGH_MEMORY => WriteError.SystemResources,
windows.ERROR.OPERATION_ABORTED => WriteError.OperationAborted,
windows.ERROR.NOT_ENOUGH_QUOTA => WriteError.SystemResources,
windows.ERROR.IO_PENDING => unreachable,
windows.ERROR.BROKEN_PIPE => WriteError.BrokenPipe,
else => os.unexpectedErrorWindows(err),
};
}
}
pub fn windowsIsTty(handle: windows.HANDLE) bool {
if (windowsIsCygwinPty(handle))
return true;
var out: windows.DWORD = undefined;
return windows.GetConsoleMode(handle, &out) != 0;
}
pub fn windowsIsCygwinPty(handle: windows.HANDLE) bool {
const size = @sizeOf(windows.FILE_NAME_INFO);
var name_info_bytes align(@alignOf(windows.FILE_NAME_INFO)) = []u8{0} ** (size + windows.MAX_PATH);
if (windows.GetFileInformationByHandleEx(
handle,
windows.FileNameInfo,
@ptrCast(*c_void, &name_info_bytes[0]),
@intCast(u32, name_info_bytes.len),
) == 0) {
return true;
}
const name_info = @ptrCast(*const windows.FILE_NAME_INFO, &name_info_bytes[0]);
const name_bytes = name_info_bytes[size .. size + usize(name_info.FileNameLength)];
const name_wide = @bytesToSlice(u16, name_bytes);
return mem.indexOf(u16, name_wide, []u16{ 'm', 's', 'y', 's', '-' }) != null or
mem.indexOf(u16, name_wide, []u16{ '-', 'p', 't', 'y' }) != null;
}
pub const OpenError = error{
SharingViolation,
PathAlreadyExists,
/// When any of the path components can not be found or the file component can not
/// be found. Some operating systems distinguish between path components not found and
/// file components not found, but they are collapsed into FileNotFound to gain
/// consistency across operating systems.
FileNotFound,
AccessDenied,
PipeBusy,
NameTooLong,
/// On Windows, file paths must be valid Unicode.
InvalidUtf8,
/// On Windows, file paths cannot contain these characters:
/// '/', '*', '?', '"', '<', '>', '|'
BadPathName,
/// See https://github.com/ziglang/zig/issues/1396
Unexpected,
};
pub fn windowsOpenW(
file_path_w: [*]const u16,
desired_access: windows.DWORD,
share_mode: windows.DWORD,
creation_disposition: windows.DWORD,
flags_and_attrs: windows.DWORD,
) OpenError!windows.HANDLE {
const result = windows.CreateFileW(file_path_w, desired_access, share_mode, null, creation_disposition, flags_and_attrs, null);
if (result == windows.INVALID_HANDLE_VALUE) {
const err = windows.GetLastError();
switch (err) {
windows.ERROR.SHARING_VIOLATION => return OpenError.SharingViolation,
windows.ERROR.ALREADY_EXISTS => return OpenError.PathAlreadyExists,
windows.ERROR.FILE_EXISTS => return OpenError.PathAlreadyExists,
windows.ERROR.FILE_NOT_FOUND => return OpenError.FileNotFound,
windows.ERROR.PATH_NOT_FOUND => return OpenError.FileNotFound,
windows.ERROR.ACCESS_DENIED => return OpenError.AccessDenied,
windows.ERROR.PIPE_BUSY => return OpenError.PipeBusy,
else => return os.unexpectedErrorWindows(err),
}
}
return result;
}
pub fn windowsOpen(
file_path: []const u8,
desired_access: windows.DWORD,
share_mode: windows.DWORD,
creation_disposition: windows.DWORD,
flags_and_attrs: windows.DWORD,
) OpenError!windows.HANDLE {
const file_path_w = try sliceToPrefixedFileW(file_path);
return windowsOpenW(&file_path_w, desired_access, share_mode, creation_disposition, flags_and_attrs);
}
/// Caller must free result.
pub fn createWindowsEnvBlock(allocator: *mem.Allocator, env_map: *const BufMap) ![]u16 {
// count bytes needed
const max_chars_needed = x: {
var max_chars_needed: usize = 1; // 1 for the final null byte
var it = env_map.iterator();
while (it.next()) |pair| {
// +1 for '='
// +1 for null byte
max_chars_needed += pair.key.len + pair.value.len + 2;
}
break :x max_chars_needed;
};
const result = try allocator.alloc(u16, max_chars_needed);
errdefer allocator.free(result);
var it = env_map.iterator();
var i: usize = 0;
while (it.next()) |pair| {
i += try unicode.utf8ToUtf16Le(result[i..], pair.key);
result[i] = '=';
i += 1;
i += try unicode.utf8ToUtf16Le(result[i..], pair.value);
result[i] = 0;
i += 1;
}
result[i] = 0;
i += 1;
return allocator.shrink(u16, result, i);
}
pub fn windowsFindFirstFile(
dir_path: []const u8,
find_file_data: *windows.WIN32_FIND_DATAW,
) !windows.HANDLE {
const dir_path_w = try sliceToPrefixedSuffixedFileW(dir_path, []u16{ '\\', '*', 0 });
const handle = windows.FindFirstFileW(&dir_path_w, find_file_data);
if (handle == windows.INVALID_HANDLE_VALUE) {
const err = windows.GetLastError();
switch (err) {
windows.ERROR.FILE_NOT_FOUND => return error.FileNotFound,
windows.ERROR.PATH_NOT_FOUND => return error.FileNotFound,
else => return os.unexpectedErrorWindows(err),
}
}
return handle;
}
/// Returns `true` if there was another file, `false` otherwise.
pub fn windowsFindNextFile(handle: windows.HANDLE, find_file_data: *windows.WIN32_FIND_DATAW) !bool {
if (windows.FindNextFileW(handle, find_file_data) == 0) {
const err = windows.GetLastError();
return switch (err) {
windows.ERROR.NO_MORE_FILES => false,
else => os.unexpectedErrorWindows(err),
};
}
return true;
}
pub const WindowsCreateIoCompletionPortError = error{Unexpected};
pub fn windowsCreateIoCompletionPort(file_handle: windows.HANDLE, existing_completion_port: ?windows.HANDLE, completion_key: usize, concurrent_thread_count: windows.DWORD) !windows.HANDLE {
const handle = windows.CreateIoCompletionPort(file_handle, existing_completion_port, completion_key, concurrent_thread_count) orelse {
const err = windows.GetLastError();
switch (err) {
windows.ERROR.INVALID_PARAMETER => unreachable,
else => return os.unexpectedErrorWindows(err),
}
};
return handle;
}
pub const WindowsPostQueuedCompletionStatusError = error{Unexpected};
pub fn windowsPostQueuedCompletionStatus(completion_port: windows.HANDLE, bytes_transferred_count: windows.DWORD, completion_key: usize, lpOverlapped: ?*windows.OVERLAPPED) WindowsPostQueuedCompletionStatusError!void {
if (windows.PostQueuedCompletionStatus(completion_port, bytes_transferred_count, completion_key, lpOverlapped) == 0) {
const err = windows.GetLastError();
switch (err) {
else => return os.unexpectedErrorWindows(err),
}
}
}
pub const WindowsWaitResult = enum {
Normal,
Aborted,
Cancelled,
EOF,
};
pub fn windowsGetQueuedCompletionStatus(completion_port: windows.HANDLE, bytes_transferred_count: *windows.DWORD, lpCompletionKey: *usize, lpOverlapped: *?*windows.OVERLAPPED, dwMilliseconds: windows.DWORD) WindowsWaitResult {
if (windows.GetQueuedCompletionStatus(completion_port, bytes_transferred_count, lpCompletionKey, lpOverlapped, dwMilliseconds) == windows.FALSE) {
const err = windows.GetLastError();
switch (err) {
windows.ERROR.ABANDONED_WAIT_0 => return WindowsWaitResult.Aborted,
windows.ERROR.OPERATION_ABORTED => return WindowsWaitResult.Cancelled,
windows.ERROR.HANDLE_EOF => return WindowsWaitResult.EOF,
else => {
if (std.debug.runtime_safety) {
std.debug.panic("unexpected error: {}\n", err);
}
},
}
}
return WindowsWaitResult.Normal;
}
pub fn cStrToPrefixedFileW(s: [*]const u8) ![PATH_MAX_WIDE + 1]u16 {
return sliceToPrefixedFileW(mem.toSliceConst(u8, s));
}
pub fn sliceToPrefixedFileW(s: []const u8) ![PATH_MAX_WIDE + 1]u16 {
return sliceToPrefixedSuffixedFileW(s, []u16{0});
}
pub fn sliceToPrefixedSuffixedFileW(s: []const u8, comptime suffix: []const u16) ![PATH_MAX_WIDE + suffix.len]u16 {
// TODO well defined copy elision
var result: [PATH_MAX_WIDE + suffix.len]u16 = undefined;
// > File I/O functions in the Windows API convert "/" to "\" as part of
// > converting the name to an NT-style name, except when using the "\\?\"
// > prefix as detailed in the following sections.
// from https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#maximum-path-length-limitation
// Because we want the larger maximum path length for absolute paths, we
// disallow forward slashes in zig std lib file functions on Windows.
for (s) |byte| {
switch (byte) {
'/', '*', '?', '"', '<', '>', '|' => return error.BadPathName,
else => {},
}
}
const start_index = if (mem.startsWith(u8, s, "\\\\") or !os.path.isAbsolute(s)) 0 else blk: {
const prefix = []u16{ '\\', '\\', '?', '\\' };
mem.copy(u16, result[0..], prefix);
break :blk prefix.len;
};
const end_index = start_index + try std.unicode.utf8ToUtf16Le(result[start_index..], s);
assert(end_index <= result.len);
if (end_index + suffix.len > result.len) return error.NameTooLong;
mem.copy(u16, result[end_index..], suffix);
return result;
} | std/os/windows/util.zig |
const aoc = @import("../aoc.zig");
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const Player = struct {
const Deck = std.ArrayList(u8);
deck: Deck,
player2: bool,
last_card: u8 = undefined,
fn fromGroup(allocator: Allocator, group: []const u8) !Player {
var deck = Deck.init(allocator);
var tokenizer = std.mem.tokenize(u8, group, "\n");
const player_row = tokenizer.next().?;
const player2 = player_row[player_row.len - 2] == '2';
while (tokenizer.next()) |card| {
try deck.append(try std.fmt.parseInt(u8, card, 10));
}
return Player { .deck = deck, .player2 = player2 };
}
fn deinit(self: *Player) void {
self.deck.deinit();
}
fn popFirst(self: *Player) void {
self.last_card = self.deck.orderedRemove(0);
}
fn stealCard(self: *Player, other: *const Player) !void {
try self.deck.append(self.last_card);
try self.deck.append(other.last_card);
}
fn score(self: *const Player) usize {
var winning_score: usize = 0;
for (self.deck.items) |card, idx| {
winning_score += card * (self.deck.items.len - idx);
}
return winning_score;
}
fn copy(self: *const Player) !Player {
var deck = Deck.init(self.deck.allocator);
try deck.appendSlice(self.deck.items);
return Player { .deck = deck, .player2 = self.player2 };
}
};
const Combat = struct {
player1: Player,
player2: Player,
fn init(player1: *const Player, player2: *const Player) !Combat {
return Combat { .player1 = try player1.copy(), .player2 = try player2.copy() };
}
fn deinit(self: *Combat) void {
self.player1.deinit();
self.player2.deinit();
}
fn play(self: *Combat) !*const Player {
while(true) {
if (self.checkEmptyDeck()) |winner| {
return winner;
}
self.player1.popFirst();
self.player2.popFirst();
try self.checkLargestCard();
}
}
fn checkEmptyDeck(self: *const Combat) ?*const Player {
if (self.player1.deck.items.len == 0) {
return &self.player2;
}
if (self.player2.deck.items.len == 0) {
return &self.player1;
}
return null;
}
fn checkLargestCard(self: *Combat) !void {
if (self.player1.last_card > self.player2.last_card) {
try self.player1.stealCard(&self.player2);
}
else {
try self.player2.stealCard(&self.player1);
}
}
};
const RecursiveCombat = struct {
const CardArrangement = struct { deck1: []const u8, deck2: []const u8 };
const CardsSeen = std.ArrayList(CardArrangement);
arena: ArenaAllocator,
combat: Combat,
cards_seen: CardsSeen,
fn init(allocator: Allocator, player1: *const Player, player2: *const Player) !RecursiveCombat {
return RecursiveCombat {
.arena = ArenaAllocator.init(allocator),
.combat = try Combat.init(player1, player2),
.cards_seen = CardsSeen.init(allocator),
};
}
fn deinit(self: *RecursiveCombat) void {
self.cards_seen.deinit();
self.combat.deinit();
self.arena.deinit();
}
fn play(self: *RecursiveCombat) anyerror!*const Player {
while (true) {
// std.debug.print("Round {d}\n", .{self.cards_seen.items.len});
if (self.combat.checkEmptyDeck()) |winner| {
return winner;
}
for (self.cards_seen.items) |cards_seen| {
if (std.mem.eql(u8, cards_seen.deck1, self.combat.player1.deck.items) and std.mem.eql(u8, cards_seen.deck2, self.combat.player2.deck.items)) {
// std.debug.print("!!!DUPE DECK!!!\n", .{});
return &self.combat.player1;
}
}
try self.cards_seen.append(.{
.deck1 = try self.arena.allocator().dupe(u8, self.combat.player1.deck.items),
.deck2 = try self.arena.allocator().dupe(u8, self.combat.player2.deck.items),
});
self.combat.player1.popFirst();
self.combat.player2.popFirst();
if (self.combat.player1.last_card <= self.combat.player1.deck.items.len and self.combat.player2.last_card <= self.combat.player2.deck.items.len) {
// std.debug.print(">>>\n", .{});
var subgame = try RecursiveCombat.init(self.arena.child_allocator, &self.combat.player1, &self.combat.player2);
defer subgame.deinit();
subgame.combat.player1.deck.shrinkRetainingCapacity(self.combat.player1.last_card);
subgame.combat.player2.deck.shrinkRetainingCapacity(self.combat.player2.last_card);
if ((try subgame.play()).player2) {
try self.combat.player2.stealCard(&self.combat.player1);
}
else {
try self.combat.player1.stealCard(&self.combat.player2);
}
// std.debug.print("<<<\n", .{});
}
else {
try self.combat.checkLargestCard();
}
}
}
};
pub fn run(problem: *aoc.Problem) !aoc.Solution {
var player1 = try Player.fromGroup(problem.allocator, problem.group().?);
defer player1.deinit();
var player2 = try Player.fromGroup(problem.allocator, problem.group().?);
defer player2.deinit();
var combat = try Combat.init(&player1, &player2);
defer combat.deinit();
const res1 = (try combat.play()).score();
var recursive_combat = try RecursiveCombat.init(problem.allocator, &player1, &player2);
defer recursive_combat.deinit();
const res2 = (try recursive_combat.play()).score();
return problem.solution(res1, res2);
} | src/main/zig/2020/day22.zig |
const std = @import("std");
const c = @import("../c.zig");
const gui = @import("../gui.zig");
pub const Color = struct {
const Self = @This();
r: f32,
g: f32,
b: f32,
fn encode(self: Self, buf: *std.ArrayList(c.vec4)) !void {
try buf.append(.{ .x = self.r, .y = self.g, .z = self.b, .w = 0 });
}
};
pub const Diffuse = struct {
const Self = @This();
color: Color,
fn encode(self: Self, buf: *std.ArrayList(c.vec4)) !void {
return self.color.encode(buf);
}
fn draw_gui(self: *Self) bool {
return c.igColorEdit3("", @ptrCast([*c]f32, &self.color), 0);
}
};
pub const Light = struct {
const Self = @This();
// The GUI clamps colors to 0-1, so we include a secondary multiplier
// to adjust brightness beyond that range.
color: Color,
intensity: f32,
fn encode(self: Self, buf: *std.ArrayList(c.vec4)) !void {
return buf.append(.{
.x = self.color.r * self.intensity,
.y = self.color.g * self.intensity,
.z = self.color.b * self.intensity,
.w = 0,
});
}
fn draw_gui(self: *Self) bool {
const a = c.igColorEdit3("", @ptrCast([*c]f32, &self.color), 0);
c.igPushItemWidth(c.igGetWindowWidth() * 0.4);
const b = c.igDragFloat("intensity", &self.intensity, 0.05, 1, 10, "%.2f", 0);
c.igPopItemWidth();
return a or b;
}
};
pub const Metal = struct {
const Self = @This();
color: Color,
fuzz: f32,
fn encode(self: Self, buf: *std.ArrayList(c.vec4)) !void {
try buf.append(.{
.x = self.color.r,
.y = self.color.g,
.z = self.color.b,
.w = self.fuzz,
});
}
fn draw_gui(self: *Self) bool {
const a = c.igColorEdit3("", @ptrCast([*c]f32, &self.color), 0);
c.igPushItemWidth(c.igGetWindowWidth() * 0.4);
const b = c.igDragFloat("fuzz", &self.fuzz, 0.01, 0, 10, "%.2f", 0);
c.igPopItemWidth();
return a or b;
}
};
pub const Glass = struct {
const Self = @This();
eta: f32,
slope: f32,
fn encode(self: Self, buf: *std.ArrayList(c.vec4)) !void {
try buf.append(.{
.x = self.eta,
.y = self.slope,
.z = 0,
.w = 0,
});
}
fn draw_gui(self: *Self) bool {
c.igPushItemWidth(c.igGetWindowWidth() * 0.4);
const a = c.igDragFloat("eta", &self.eta, 0.01, 1, 2, "%.2f", 0);
const b = c.igDragFloat("slope", &self.slope, 0.0001, 0, 0.01, "%.4f", 0);
c.igPopItemWidth();
return a or b;
}
};
pub const Laser = struct {
const Self = @This();
// The GUI clamps colors to 0-1, so we include a secondary multiplier
// to adjust brightness beyond that range.
color: Color,
intensity: f32,
focus: f32,
fn encode(self: Self, buf: *std.ArrayList(c.vec4)) !void {
return buf.append(.{
.x = self.color.r * self.intensity,
.y = self.color.g * self.intensity,
.z = self.color.b * self.intensity,
.w = self.focus,
});
}
fn draw_gui(self: *Self) bool {
const a = c.igColorEdit3("", @ptrCast([*c]f32, &self.color), 0);
c.igPushItemWidth(c.igGetWindowWidth() * 0.4);
const b = c.igDragFloat("intensity", &self.intensity, 0.05, 1, 500, "%.2f", 0);
const f = c.igDragFloat("focus", &self.focus, 0.01, 0, 1, "%.2f", 0);
c.igPopItemWidth();
return a or b or f;
}
};
pub const Metaflat = struct {
// Nothing in the struct
};
pub const Material = union(enum) {
const Self = @This();
Diffuse: Diffuse,
Light: Light,
Metal: Metal,
Glass: Glass,
Laser: Laser,
Metaflat: Metaflat,
pub fn tag(self: Self) u32 {
return switch (self) {
.Diffuse => c.MAT_DIFFUSE,
.Light => c.MAT_LIGHT,
.Metal => c.MAT_METAL,
.Glass => c.MAT_GLASS,
.Laser => c.MAT_LASER,
.Metaflat => c.MAT_METAFLAT,
};
}
pub fn new_diffuse(r: f32, g: f32, b: f32) Self {
return .{
.Diffuse = .{ .color = .{ .r = r, .g = g, .b = b } },
};
}
pub fn new_light(r: f32, g: f32, b: f32, intensity: f32) Self {
return .{
.Light = .{
.color = .{ .r = r, .g = g, .b = b },
.intensity = intensity,
},
};
}
pub fn new_metal(r: f32, g: f32, b: f32, fuzz: f32) Self {
return .{
.Metal = .{ .color = .{ .r = r, .g = g, .b = b }, .fuzz = fuzz },
};
}
pub fn new_glass(eta: f32, slope: f32) Self {
return .{
.Glass = .{ .eta = eta, .slope = slope },
};
}
pub fn new_laser(r: f32, g: f32, b: f32, intensity: f32, focus: f32) Self {
return .{
.Laser = .{
.color = .{ .r = r, .g = g, .b = b },
.intensity = intensity,
.focus = focus,
},
};
}
pub fn new_metaflat() Self {
return .{
.Metaflat = .{},
};
}
pub fn encode(self: Self, buf: *std.ArrayList(c.vec4)) !void {
// We don't encode the tag here, because we can put it into the Shape
// header to save space.
return switch (self) {
.Diffuse => |m| m.encode(buf),
.Light => |m| m.encode(buf),
.Metal => |m| m.encode(buf),
.Glass => |m| m.encode(buf),
.Laser => |m| m.encode(buf),
.Metaflat => {},
};
}
fn color(self: *const Self) Color {
return switch (self.*) {
.Diffuse => |m| m.color,
.Light => |m| m.color,
.Metal => |m| m.color,
.Glass => Color{ .r = 1, .g = 0.5, .b = 0.5 },
.Laser => |m| m.color,
.Metaflat => Color{ .r = 1, .g = 0.5, .b = 0.5 },
};
}
pub fn draw_gui(self: *Self) bool {
comptime var widgets = @import("../gui/widgets.zig");
var changed = false;
if (widgets.draw_enum_combo(Self, self.*)) |e| {
// Swap the material type if the combo box returns a new tag
changed = true;
switch (e) {
.Diffuse => self.* = .{
.Diffuse = .{
.color = self.color(),
},
},
.Light => self.* = .{
.Light = .{
.color = self.color(),
.intensity = 1,
},
},
.Metal => self.* = .{
.Metal = .{
.color = self.color(),
.fuzz = 0.1,
},
},
.Glass => self.* = .{
.Glass = .{
.eta = 0.15,
.slope = 0.013,
},
},
.Laser => self.* = .{
.Laser = .{
.color = self.color(),
.intensity = 1,
.focus = 0.5,
},
},
.Metaflat => self.* = .{
.Metaflat = .{},
},
}
}
changed = switch (self.*) {
.Diffuse => |*d| d.draw_gui(),
.Light => |*d| d.draw_gui(),
.Metal => |*d| d.draw_gui(),
.Glass => |*d| d.draw_gui(),
.Laser => |*d| d.draw_gui(),
.Metaflat => false,
} or changed;
return changed;
}
}; | src/scene/material.zig |
const std = @import("std");
const testing = std.testing;
pub const Sector = packed struct {
// Sectors are 4KiB in size.
comptime {
std.debug.assert(@sizeOf(Sector) == 0x1000);
}
// The relevant size of this data depends on the id, and can range from 2000 to 3968 bytes. The rest
// is just padding.
data: [0xF80]u8,
// Unused data for padding.
//
// Offset: 0xF80
_: [0x074]u8,
// Specifies the data and size.
//
// Offset: 0xFF4
id: u16,
// Stores the checksum value derived from the data, and is compared to see if the save is valid.
//
// Offset: 0xFF6
checksum: u16,
// Should be the magic number of 0x08012025. If not, the save isn't considered valid.
//
// Offset: 0xFF8
security: u32,
// Represents the number of times the game has been saved. Interestingly, this number doesn't
// have to be the same for all sectors in a slot. If both slots are valid, the slot with the
// higher counter is chosen.
//
// Offset: 0xFFC
counter: u32,
// Magic number. If all sectors in a slot don't match this, the slot is considered empty. If some
// match but not all, it's considered invalid.
pub const security_num: u32 = 0x08012025;
// The size corresponds to the ID.
const size = [14]u16{
3884, 3968, 3968, 3968, 3848, 3968, 3968,
3968, 3968, 3968, 3968, 3968, 3968, 2000,
};
pub fn getChecksum(self: Sector) u16 {
std.debug.assert(self.id < 14);
return calculateChecksum(self.data[0..size[self.id]]);
}
};
/// Iterates over a slice as u32 values, get the sum, and returns the sum of the
/// first and last 16 bits as an u16.
fn calculateChecksum(slice: []const u8) u16 {
std.debug.assert(slice.len % 4 == 0);
var checksum: u32 = 0;
var count: u16 = 0;
while (count < slice.len) : (count += 4) {
checksum +%= std.mem.readIntSliceLittle(u32, slice[count .. count + 4]);
}
return @truncate(u16, (checksum >> 16) +% checksum);
}
test "sample checksum" {
const array = [_]u8{ 0x20, 0x30, 0x50, 0x10 } ** 0x10;
const checksum = calculateChecksum(&array);
try testing.expectEqual(checksum, 1795);
} | src/save/sector.zig |
const builtin = @import("builtin");
const math = @import("index.zig").math;
pub fn doClientRequest(default: usize, request: usize, a1: usize, a2: usize, a3: usize, a4: usize, a5: usize) usize {
if (!builtin.valgrind_support) {
return default;
}
switch (builtin.arch) {
builtin.Arch.i386 => {
return asm volatile (
\\ roll $3, %%edi ; roll $13, %%edi
\\ roll $29, %%edi ; roll $19, %%edi
\\ xchgl %%ebx,%%ebx
: [_] "={edx}" (-> usize)
: [_] "{eax}" (&[]usize{ request, a1, a2, a3, a4, a5 }),
[_] "0" (default)
: "cc", "memory"
);
},
builtin.Arch.x86_64 => {
return asm volatile (
\\ rolq $3, %%rdi ; rolq $13, %%rdi
\\ rolq $61, %%rdi ; rolq $51, %%rdi
\\ xchgq %%rbx,%%rbx
: [_] "={rdx}" (-> usize)
: [_] "{rax}" (&[]usize{ request, a1, a2, a3, a4, a5 }),
[_] "0" (default)
: "cc", "memory"
);
},
// ppc32
// ppc64
// arm
// arm64
// s390x
// mips32
// mips64
else => {
return default;
},
}
}
pub const ClientRequest = extern enum {
RunningOnValgrind = 4097,
DiscardTranslations = 4098,
ClientCall0 = 4353,
ClientCall1 = 4354,
ClientCall2 = 4355,
ClientCall3 = 4356,
CountErrors = 4609,
GdbMonitorCommand = 4610,
MalloclikeBlock = 4865,
ResizeinplaceBlock = 4875,
FreelikeBlock = 4866,
CreateMempool = 4867,
DestroyMempool = 4868,
MempoolAlloc = 4869,
MempoolFree = 4870,
MempoolTrim = 4871,
MoveMempool = 4872,
MempoolChange = 4873,
MempoolExists = 4874,
Printf = 5121,
PrintfBacktrace = 5122,
PrintfValistByRef = 5123,
PrintfBacktraceValistByRef = 5124,
StackRegister = 5377,
StackDeregister = 5378,
StackChange = 5379,
LoadPdbDebuginfo = 5633,
MapIpToSrcloc = 5889,
ChangeErrDisablement = 6145,
VexInitForIri = 6401,
InnerThreads = 6402,
};
pub fn ToolBase(base: [2]u8) u32 {
return (@as(u32, base[0] & 0xff) << 24) | (@as(u32, base[1] & 0xff) << 16);
}
pub fn IsTool(base: [2]u8, code: usize) bool {
return ToolBase(base) == (code & 0xffff0000);
}
fn doClientRequestExpr(default: usize, request: ClientRequest, a1: usize, a2: usize, a3: usize, a4: usize, a5: usize) usize {
return doClientRequest(default, @intCast(usize, @enumToInt(request)), a1, a2, a3, a4, a5);
}
fn doClientRequestStmt(request: ClientRequest, a1: usize, a2: usize, a3: usize, a4: usize, a5: usize) void {
_ = doClientRequestExpr(0, request, a1, a2, a3, a4, a5);
}
/// Returns the number of Valgrinds this code is running under. That
/// is, 0 if running natively, 1 if running under Valgrind, 2 if
/// running under Valgrind which is running under another Valgrind,
/// etc.
pub fn runningOnValgrind() usize {
return doClientRequestExpr(0, ClientRequest.RunningOnValgrind, 0, 0, 0, 0, 0);
}
/// Discard translation of code in the slice qzz. Useful if you are debugging
/// a JITter or some such, since it provides a way to make sure valgrind will
/// retranslate the invalidated area. Returns no value.
pub fn discardTranslations(qzz: []const u8) void {
doClientRequestStmt(ClientRequest.DiscardTranslations, @ptrToInt(qzz.ptr), qzz.len, 0, 0, 0);
}
pub fn innerThreads(qzz: [*]u8) void {
doClientRequestStmt(ClientRequest.InnerThreads, qzz, 0, 0, 0, 0);
}
//pub fn printf(format: [*]const u8, args: ...) usize {
// return doClientRequestExpr(0,
// ClientRequest.PrintfValistByRef,
// @ptrToInt(format), @ptrToInt(args),
// 0, 0, 0);
//}
//pub fn printfBacktrace(format: [*]const u8, args: ...) usize {
// return doClientRequestExpr(0,
// ClientRequest.PrintfBacktraceValistByRef,
// @ptrToInt(format), @ptrToInt(args),
// 0, 0, 0);
//}
pub fn nonSIMDCall0(func: fn (usize) usize) usize {
return doClientRequestExpr(0, ClientRequest.ClientCall0, @ptrToInt(func), 0, 0, 0, 0);
}
pub fn nonSIMDCall1(func: fn (usize, usize) usize, a1: usize) usize {
return doClientRequestExpr(0, ClientRequest.ClientCall1, @ptrToInt(func), a1, 0, 0, 0);
}
pub fn nonSIMDCall2(func: fn (usize, usize, usize) usize, a1: usize, a2: usize) usize {
return doClientRequestExpr(0, ClientRequest.ClientCall2, @ptrToInt(func), a1, a2, 0, 0);
}
pub fn nonSIMDCall3(func: fn (usize, usize, usize, usize) usize, a1: usize, a2: usize, a3: usize) usize {
return doClientRequestExpr(0, ClientRequest.ClientCall3, @ptrToInt(func), a1, a2, a3, 0);
}
/// Counts the number of errors that have been recorded by a tool. Nb:
/// the tool must record the errors with VG_(maybe_record_error)() or
/// VG_(unique_error)() for them to be counted.
pub fn countErrors() usize {
return doClientRequestExpr(0, // default return
ClientRequest.CountErrors, 0, 0, 0, 0, 0);
}
pub fn mallocLikeBlock(mem: []u8, rzB: usize, is_zeroed: bool) void {
doClientRequestStmt(ClientRequest.MalloclikeBlock, @ptrToInt(mem.ptr), mem.len, rzB, @boolToInt(is_zeroed), 0);
}
pub fn resizeInPlaceBlock(oldmem: []u8, newsize: usize, rzB: usize) void {
doClientRequestStmt(ClientRequest.ResizeinplaceBlock, @ptrToInt(oldmem.ptr), oldmem.len, newsize, rzB, 0);
}
pub fn freeLikeBlock(addr: [*]u8, rzB: usize) void {
doClientRequestStmt(ClientRequest.FreelikeBlock, @ptrToInt(addr), rzB, 0, 0, 0);
}
/// Create a memory pool.
pub const MempoolFlags = extern enum {
AutoFree = 1,
MetaPool = 2,
};
pub fn createMempool(pool: [*]u8, rzB: usize, is_zeroed: bool, flags: usize) void {
doClientRequestStmt(ClientRequest.CreateMempool, @ptrToInt(pool), rzB, @boolToInt(is_zeroed), flags, 0);
}
/// Destroy a memory pool.
pub fn destroyMempool(pool: [*]u8) void {
doClientRequestStmt(ClientRequest.DestroyMempool, pool, 0, 0, 0, 0);
}
/// Associate a piece of memory with a memory pool.
pub fn mempoolAlloc(pool: [*]u8, mem: []u8) void {
doClientRequestStmt(ClientRequest.MempoolAlloc, @ptrToInt(pool), @ptrToInt(mem.ptr), mem.len, 0, 0);
}
/// Disassociate a piece of memory from a memory pool.
pub fn mempoolFree(pool: [*]u8, addr: [*]u8) void {
doClientRequestStmt(ClientRequest.MempoolFree, @ptrToInt(pool), @ptrToInt(addr), 0, 0, 0);
}
/// Disassociate any pieces outside a particular range.
pub fn mempoolTrim(pool: [*]u8, mem: []u8) void {
doClientRequestStmt(ClientRequest.MempoolTrim, @ptrToInt(pool), @ptrToInt(mem.ptr), mem.len, 0, 0);
}
/// Resize and/or move a piece associated with a memory pool.
pub fn moveMempool(poolA: [*]u8, poolB: [*]u8) void {
doClientRequestStmt(ClientRequest.MoveMempool, @ptrToInt(poolA), @ptrToInt(poolB), 0, 0, 0);
}
/// Resize and/or move a piece associated with a memory pool.
pub fn mempoolChange(pool: [*]u8, addrA: [*]u8, mem: []u8) void {
doClientRequestStmt(ClientRequest.MempoolChange, @ptrToInt(pool), @ptrToInt(addrA), @ptrToInt(mem.ptr), mem.len, 0);
}
/// Return if a mempool exists.
pub fn mempoolExists(pool: [*]u8) bool {
return doClientRequestExpr(0, ClientRequest.MempoolExists, @ptrToInt(pool), 0, 0, 0, 0) != 0;
}
/// Mark a piece of memory as being a stack. Returns a stack id.
/// start is the lowest addressable stack byte, end is the highest
/// addressable stack byte.
pub fn stackRegister(stack: []u8) usize {
return doClientRequestExpr(0, ClientRequest.StackRegister, @ptrToInt(stack.ptr), @ptrToInt(stack.ptr) + stack.len, 0, 0, 0);
}
/// Unmark the piece of memory associated with a stack id as being a stack.
pub fn stackDeregister(id: usize) void {
doClientRequestStmt(ClientRequest.StackDeregister, id, 0, 0, 0, 0);
}
/// Change the start and end address of the stack id.
/// start is the new lowest addressable stack byte, end is the new highest
/// addressable stack byte.
pub fn stackChange(id: usize, newstack: []u8) void {
doClientRequestStmt(ClientRequest.StackChange, id, @ptrToInt(newstack.ptr), @ptrToInt(newstack.ptr) + newstack.len, 0, 0);
}
// Load PDB debug info for Wine PE image_map.
// pub fn loadPdbDebuginfo(fd, ptr, total_size, delta) void {
// doClientRequestStmt(ClientRequest.LoadPdbDebuginfo,
// fd, ptr, total_size, delta,
// 0);
// }
/// Map a code address to a source file name and line number. buf64
/// must point to a 64-byte buffer in the caller's address space. The
/// result will be dumped in there and is guaranteed to be zero
/// terminated. If no info is found, the first byte is set to zero.
pub fn mapIpToSrcloc(addr: *const u8, buf64: [64]u8) usize {
return doClientRequestExpr(0, ClientRequest.MapIpToSrcloc, @ptrToInt(addr), @ptrToInt(&buf64[0]), 0, 0, 0);
}
/// Disable error reporting for this thread. Behaves in a stack like
/// way, so you can safely call this multiple times provided that
/// enableErrorReporting() is called the same number of times
/// to re-enable reporting. The first call of this macro disables
/// reporting. Subsequent calls have no effect except to increase the
/// number of enableErrorReporting() calls needed to re-enable
/// reporting. Child threads do not inherit this setting from their
/// parents -- they are always created with reporting enabled.
pub fn disableErrorReporting() void {
doClientRequestStmt(ClientRequest.ChangeErrDisablement, 1, 0, 0, 0, 0);
}
/// Re-enable error reporting, (see disableErrorReporting())
pub fn enableErrorReporting() void {
doClientRequestStmt(ClientRequest.ChangeErrDisablement, math.maxInt(usize), 0, 0, 0, 0);
}
/// Execute a monitor command from the client program.
/// If a connection is opened with GDB, the output will be sent
/// according to the output mode set for vgdb.
/// If no connection is opened, output will go to the log output.
/// Returns 1 if command not recognised, 0 otherwise.
pub fn monitorCommand(command: [*]u8) bool {
return doClientRequestExpr(0, ClientRequest.GdbMonitorCommand, @ptrToInt(command.ptr), 0, 0, 0, 0) != 0;
}
pub const memcheck = @import("memcheck.zig");
pub const callgrind = @import("callgrind.zig"); | lib/std/valgrind.zig |
const std = @import("std");
pub const IterationContext = struct {
pub const StackInfo = struct {
index: usize,
material: i32, // Negative indexes are used for generated materials
};
pub const EnterInfo = struct {
enter_index: usize,
enter_stack: usize,
};
value_indexes: std.ArrayList(StackInfo),
last_value_set_index: usize,
any_value_set: bool,
points: std.ArrayList([]const u8),
cur_point_name: []const u8,
enter_info: std.ArrayList(EnterInfo),
allocator: std.mem.Allocator,
pub fn create(allocator: std.mem.Allocator) IterationContext {
var cntx: IterationContext = .{
.allocator = allocator,
.value_indexes = std.ArrayList(StackInfo).init(allocator),
.last_value_set_index = undefined,
.any_value_set = false,
.points = std.ArrayList([]const u8).init(allocator),
.cur_point_name = undefined,
.enter_info = std.ArrayList(EnterInfo).init(allocator),
};
cntx.pushPointName("p");
return cntx;
}
pub fn destroy(self: *IterationContext) void {
self.value_indexes.deinit();
self.points.deinit();
self.enter_info.deinit();
}
pub fn pushPointName(self: *IterationContext, name: []const u8) void {
self.points.append(name) catch unreachable;
self.cur_point_name = name;
}
pub fn popPointName(self: *IterationContext) void {
self.allocator.free(self.cur_point_name);
_ = self.points.pop();
self.cur_point_name = self.points.items[self.points.items.len - 1];
}
pub fn pushEnterInfo(self: *IterationContext, iter: usize) void {
self.enter_info.append(.{
.enter_index = iter,
.enter_stack = self.value_indexes.items.len,
}) catch unreachable;
}
pub fn lastEnterInfo(self: *IterationContext) EnterInfo {
return self.enter_info.items[self.enter_info.items.len - 1];
}
pub fn popEnterInfo(self: *IterationContext) EnterInfo {
return self.enter_info.pop();
}
pub fn pushStackInfo(self: *IterationContext, index: usize, material: i32) void {
self.value_indexes.append(.{ .index = index, .material = material }) catch unreachable;
self.last_value_set_index = index;
self.any_value_set = true;
}
pub fn dropPreviousValueIndexes(self: *IterationContext, enter_index: usize) void {
self.value_indexes.resize(enter_index + 1) catch unreachable;
const info: StackInfo = self.value_indexes.items[enter_index];
self.last_value_set_index = info.index;
}
}; | src/sdf/iteration_context.zig |
const builtin = @import("builtin");
const std = @import("std");
const debug = std.debug;
const io = std.io;
const math = std.math;
const mem = std.mem;
const meta = std.meta;
const time = std.time;
const Decl = builtin.TypeInfo.Declaration;
pub fn benchmark(comptime B: type) !void {
const args = if (@hasDecl(B, "args")) B.args else [_]void{{}};
const iterations: u32 = if (@hasDecl(B, "iterations")) B.iterations else 100000;
comptime var max_fn_name_len = 0;
const functions = comptime blk: {
var res: []const Decl = &[_]Decl{};
for (meta.declarations(B)) |decl| {
if (decl.data != Decl.Data.Fn)
continue;
if (max_fn_name_len < decl.name.len)
max_fn_name_len = decl.name.len;
res = res ++ [_]Decl{decl};
}
break :blk res;
};
if (functions.len == 0)
@compileError("No benchmarks to run.");
const max_name_spaces = comptime math.max(max_fn_name_len + digits(u64, 10, args.len) + 1, "Benchmark".len);
var timer = try time.Timer.start();
debug.warn("\n", .{});
debug.warn("Benchmark", .{});
nTimes(' ', (max_name_spaces - "Benchmark".len) + 1);
nTimes(' ', digits(u64, 10, math.maxInt(u64)) - "Mean(ns)".len);
debug.warn("Mean(ns)\n", .{});
nTimes('-', max_name_spaces + digits(u64, 10, math.maxInt(u64)) + 1);
debug.warn("\n", .{});
inline for (functions) |def| {
for (args) |arg, index| {
var runtime_sum: u128 = 0;
var i: usize = 0;
while (i < iterations) : (i += 1) {
timer.reset();
const res = switch (@TypeOf(arg)) {
void => @field(B, def.name)(),
else => @field(B, def.name)(arg),
};
const runtime = timer.read();
runtime_sum += runtime;
doNotOptimize(res);
}
const runtime_mean = @intCast(u64, runtime_sum / iterations);
debug.warn("{}.{}", .{ def.name, index });
nTimes(' ', (max_name_spaces - (def.name.len + digits(u64, 10, index) + 1)) + 1);
nTimes(' ', digits(u64, 10, math.maxInt(u64)) - digits(u64, 10, runtime_mean));
debug.warn("{}\n", .{runtime_mean});
}
}
}
/// Pretend to use the value so the optimizer cant optimize it out.
fn doNotOptimize(val: var) void {
const T = @TypeOf(val);
var store: T = undefined;
@ptrCast(*volatile T, &store).* = val;
}
fn digits(comptime N: type, comptime base: comptime_int, n: N) usize {
comptime var res = 1;
comptime var check = base;
inline while (check <= math.maxInt(N)) : ({
check *= base;
res += 1;
}) {
if (n < check)
return res;
}
return res;
}
fn nTimes(c: u8, times: usize) void {
var i: usize = 0;
while (i < times) : (i += 1)
debug.warn("{c}", .{c});
}
const zee_alloc = @import("main.zig");
var test_buf: [1024 * 1024]u8 = undefined;
test "ZeeAlloc benchmark" {
try benchmark(struct {
const Arg = struct {
num: usize,
size: usize,
fn benchAllocator(a: Arg, allocator: *std.mem.Allocator, comptime free: bool) !void {
var i: usize = 0;
while (i < a.num) : (i += 1) {
const bytes = try allocator.alloc(u8, a.size);
defer if (free) allocator.free(bytes);
}
}
};
pub const args = [_]Arg{
Arg{ .num = 10 * 1, .size = 1024 * 1 },
Arg{ .num = 10 * 2, .size = 1024 * 1 },
Arg{ .num = 10 * 4, .size = 1024 * 1 },
Arg{ .num = 10 * 1, .size = 1024 * 2 },
Arg{ .num = 10 * 2, .size = 1024 * 2 },
Arg{ .num = 10 * 4, .size = 1024 * 2 },
Arg{ .num = 10 * 1, .size = 1024 * 4 },
Arg{ .num = 10 * 2, .size = 1024 * 4 },
Arg{ .num = 10 * 4, .size = 1024 * 4 },
};
pub const iterations = 10000;
pub fn FixedBufferAllocator(a: Arg) void {
var fba = std.heap.FixedBufferAllocator.init(test_buf[0..]);
a.benchAllocator(&fba.allocator, false) catch unreachable;
}
pub fn Arena_FixedBufferAllocator(a: Arg) void {
var fba = std.heap.FixedBufferAllocator.init(test_buf[0..]);
var arena = std.heap.ArenaAllocator.init(&fba.allocator);
defer arena.deinit();
a.benchAllocator(&arena.allocator, false) catch unreachable;
}
pub fn ZeeAlloc_FixedBufferAllocator(a: Arg) void {
var fba = std.heap.FixedBufferAllocator.init(test_buf[0..]);
var za = zee_alloc.ZeeAllocDefaults.init(&fba.allocator);
a.benchAllocator(&za.allocator, false) catch unreachable;
}
pub fn PageAllocator(a: Arg) void {
a.benchAllocator(std.heap.page_allocator, true) catch unreachable;
}
pub fn Arena_PageAllocator(a: Arg) void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
a.benchAllocator(&arena.allocator, false) catch unreachable;
}
pub fn ZeeAlloc_PageAllocator(a: Arg) void {
var za = zee_alloc.ZeeAllocDefaults.init(std.heap.page_allocator);
a.benchAllocator(&za.allocator, false) catch unreachable;
}
});
} | src/bench.zig |
const std = @import("std");
pub fn build(b: *std.build.Builder) void
{
const mode = b.standardReleaseOptions();
const target = b.standardTargetOptions(.{});
const cOptions = &[_][]const u8 {
"-Wall",
"-Wextra",
"-Werror",
};
const brsslToolSources = [_][]const u8 {
"deps/BearSSL/tools/brssl.c",
"deps/BearSSL/tools/certs.c",
"deps/BearSSL/tools/chain.c",
"deps/BearSSL/tools/client.c",
"deps/BearSSL/tools/errors.c",
"deps/BearSSL/tools/files.c",
"deps/BearSSL/tools/impl.c",
"deps/BearSSL/tools/keys.c",
"deps/BearSSL/tools/names.c",
"deps/BearSSL/tools/server.c",
"deps/BearSSL/tools/skey.c",
"deps/BearSSL/tools/sslio.c",
"deps/BearSSL/tools/ta.c",
"deps/BearSSL/tools/twrch.c",
"deps/BearSSL/tools/vector.c",
"deps/BearSSL/tools/verify.c",
"deps/BearSSL/tools/xmem.c",
};
const brssl = b.addExecutable("brssl", null);
inline for (brsslToolSources) |src| {
brssl.addCSourceFile(src, cOptions);
}
brssl.setBuildMode(mode);
brssl.setTarget(target);
addLib(brssl, target, ".");
brssl.linkLibC();
brssl.install();
const testCrt = b.addTest("test/test_crt.zig");
testCrt.setBuildMode(mode);
testCrt.setTarget(target);
addLib(testCrt, target, ".");
testCrt.linkLibC();
const testKey = b.addTest("test/test_key.zig");
testKey.setBuildMode(mode);
testKey.setTarget(target);
addLib(testKey, target, ".");
testKey.linkLibC();
const testPem = b.addTest("test/test_pem.zig");
testPem.setBuildMode(mode);
testPem.setTarget(target);
addLib(testPem, target, ".");
testPem.linkLibC();
const runTests = b.step("test", "Run all tests");
runTests.dependOn(&testCrt.step);
runTests.dependOn(&testKey.step);
runTests.dependOn(&testPem.step);
}
pub fn getPkg(comptime dir: []const u8) std.build.Pkg
{
return .{
.name = "bearssl",
.path = .{
.path = dir ++ "/src/bearssl.zig"
},
.dependencies = null,
};
}
pub fn addLib(
step: *std.build.LibExeObjStep,
target: std.zig.CrossTarget,
comptime dir: []const u8) void
{
step.addPackage(getPkg(dir));
step.addIncludeDir(dir ++ "/deps/BearSSL/inc");
step.addIncludeDir(dir ++ "/deps/BearSSL/src");
const cOptions = &[_][]const u8 {
"-Wall",
"-Wextra",
"-Werror",
"-Wno-unknown-pragmas",
"-DBR_LE_UNALIGNED=0", // this prevents BearSSL from using undefined behaviour when doing potential unaligned access
};
var fullSources: [bearsslSources.len][]const u8 = undefined;
inline for (bearsslSources) |file, i| {
fullSources[i] = dir ++ file;
}
step.addCSourceFiles(&fullSources, cOptions);
if (target.isWindows()) {
step.linkSystemLibrary("advapi32");
}
}
const bearsslSources = [_][]const u8 {
"/deps/BearSSL/src/settings.c",
"/deps/BearSSL/src/aead/ccm.c",
"/deps/BearSSL/src/aead/eax.c",
"/deps/BearSSL/src/aead/gcm.c",
"/deps/BearSSL/src/codec/ccopy.c",
"/deps/BearSSL/src/codec/dec16be.c",
"/deps/BearSSL/src/codec/dec16le.c",
"/deps/BearSSL/src/codec/dec32be.c",
"/deps/BearSSL/src/codec/dec32le.c",
"/deps/BearSSL/src/codec/dec64be.c",
"/deps/BearSSL/src/codec/dec64le.c",
"/deps/BearSSL/src/codec/enc16be.c",
"/deps/BearSSL/src/codec/enc16le.c",
"/deps/BearSSL/src/codec/enc32be.c",
"/deps/BearSSL/src/codec/enc32le.c",
"/deps/BearSSL/src/codec/enc64be.c",
"/deps/BearSSL/src/codec/enc64le.c",
"/deps/BearSSL/src/codec/pemdec.c",
"/deps/BearSSL/src/codec/pemenc.c",
"/deps/BearSSL/src/ec/ec_all_m15.c",
"/deps/BearSSL/src/ec/ec_all_m31.c",
"/deps/BearSSL/src/ec/ec_c25519_i15.c",
"/deps/BearSSL/src/ec/ec_c25519_i31.c",
"/deps/BearSSL/src/ec/ec_c25519_m15.c",
"/deps/BearSSL/src/ec/ec_c25519_m31.c",
"/deps/BearSSL/src/ec/ec_c25519_m62.c",
"/deps/BearSSL/src/ec/ec_c25519_m64.c",
"/deps/BearSSL/src/ec/ec_curve25519.c",
"/deps/BearSSL/src/ec/ec_default.c",
"/deps/BearSSL/src/ec/ec_keygen.c",
"/deps/BearSSL/src/ec/ec_p256_m15.c",
"/deps/BearSSL/src/ec/ec_p256_m31.c",
"/deps/BearSSL/src/ec/ec_p256_m62.c",
"/deps/BearSSL/src/ec/ec_p256_m64.c",
"/deps/BearSSL/src/ec/ec_prime_i15.c",
"/deps/BearSSL/src/ec/ec_prime_i31.c",
"/deps/BearSSL/src/ec/ec_pubkey.c",
"/deps/BearSSL/src/ec/ec_secp256r1.c",
"/deps/BearSSL/src/ec/ec_secp384r1.c",
"/deps/BearSSL/src/ec/ec_secp521r1.c",
"/deps/BearSSL/src/ec/ecdsa_atr.c",
"/deps/BearSSL/src/ec/ecdsa_default_sign_asn1.c",
"/deps/BearSSL/src/ec/ecdsa_default_sign_raw.c",
"/deps/BearSSL/src/ec/ecdsa_default_vrfy_asn1.c",
"/deps/BearSSL/src/ec/ecdsa_default_vrfy_raw.c",
"/deps/BearSSL/src/ec/ecdsa_i15_bits.c",
"/deps/BearSSL/src/ec/ecdsa_i15_sign_asn1.c",
"/deps/BearSSL/src/ec/ecdsa_i15_sign_raw.c",
"/deps/BearSSL/src/ec/ecdsa_i15_vrfy_asn1.c",
"/deps/BearSSL/src/ec/ecdsa_i15_vrfy_raw.c",
"/deps/BearSSL/src/ec/ecdsa_i31_bits.c",
"/deps/BearSSL/src/ec/ecdsa_i31_sign_asn1.c",
"/deps/BearSSL/src/ec/ecdsa_i31_sign_raw.c",
"/deps/BearSSL/src/ec/ecdsa_i31_vrfy_asn1.c",
"/deps/BearSSL/src/ec/ecdsa_i31_vrfy_raw.c",
"/deps/BearSSL/src/ec/ecdsa_rta.c",
"/deps/BearSSL/src/hash/dig_oid.c",
"/deps/BearSSL/src/hash/dig_size.c",
"/deps/BearSSL/src/hash/ghash_ctmul.c",
"/deps/BearSSL/src/hash/ghash_ctmul32.c",
"/deps/BearSSL/src/hash/ghash_ctmul64.c",
"/deps/BearSSL/src/hash/ghash_pclmul.c",
"/deps/BearSSL/src/hash/ghash_pwr8.c",
"/deps/BearSSL/src/hash/md5.c",
"/deps/BearSSL/src/hash/md5sha1.c",
"/deps/BearSSL/src/hash/mgf1.c",
"/deps/BearSSL/src/hash/multihash.c",
"/deps/BearSSL/src/hash/sha1.c",
"/deps/BearSSL/src/hash/sha2big.c",
"/deps/BearSSL/src/hash/sha2small.c",
"/deps/BearSSL/src/int/i15_add.c",
"/deps/BearSSL/src/int/i15_bitlen.c",
"/deps/BearSSL/src/int/i15_decmod.c",
"/deps/BearSSL/src/int/i15_decode.c",
"/deps/BearSSL/src/int/i15_decred.c",
"/deps/BearSSL/src/int/i15_encode.c",
"/deps/BearSSL/src/int/i15_fmont.c",
"/deps/BearSSL/src/int/i15_iszero.c",
"/deps/BearSSL/src/int/i15_moddiv.c",
"/deps/BearSSL/src/int/i15_modpow.c",
"/deps/BearSSL/src/int/i15_modpow2.c",
"/deps/BearSSL/src/int/i15_montmul.c",
"/deps/BearSSL/src/int/i15_mulacc.c",
"/deps/BearSSL/src/int/i15_muladd.c",
"/deps/BearSSL/src/int/i15_ninv15.c",
"/deps/BearSSL/src/int/i15_reduce.c",
"/deps/BearSSL/src/int/i15_rshift.c",
"/deps/BearSSL/src/int/i15_sub.c",
"/deps/BearSSL/src/int/i15_tmont.c",
"/deps/BearSSL/src/int/i31_add.c",
"/deps/BearSSL/src/int/i31_bitlen.c",
"/deps/BearSSL/src/int/i31_decmod.c",
"/deps/BearSSL/src/int/i31_decode.c",
"/deps/BearSSL/src/int/i31_decred.c",
"/deps/BearSSL/src/int/i31_encode.c",
"/deps/BearSSL/src/int/i31_fmont.c",
"/deps/BearSSL/src/int/i31_iszero.c",
"/deps/BearSSL/src/int/i31_moddiv.c",
"/deps/BearSSL/src/int/i31_modpow.c",
"/deps/BearSSL/src/int/i31_modpow2.c",
"/deps/BearSSL/src/int/i31_montmul.c",
"/deps/BearSSL/src/int/i31_mulacc.c",
"/deps/BearSSL/src/int/i31_muladd.c",
"/deps/BearSSL/src/int/i31_ninv31.c",
"/deps/BearSSL/src/int/i31_reduce.c",
"/deps/BearSSL/src/int/i31_rshift.c",
"/deps/BearSSL/src/int/i31_sub.c",
"/deps/BearSSL/src/int/i31_tmont.c",
"/deps/BearSSL/src/int/i32_add.c",
"/deps/BearSSL/src/int/i32_bitlen.c",
"/deps/BearSSL/src/int/i32_decmod.c",
"/deps/BearSSL/src/int/i32_decode.c",
"/deps/BearSSL/src/int/i32_decred.c",
"/deps/BearSSL/src/int/i32_div32.c",
"/deps/BearSSL/src/int/i32_encode.c",
"/deps/BearSSL/src/int/i32_fmont.c",
"/deps/BearSSL/src/int/i32_iszero.c",
"/deps/BearSSL/src/int/i32_modpow.c",
"/deps/BearSSL/src/int/i32_montmul.c",
"/deps/BearSSL/src/int/i32_mulacc.c",
"/deps/BearSSL/src/int/i32_muladd.c",
"/deps/BearSSL/src/int/i32_ninv32.c",
"/deps/BearSSL/src/int/i32_reduce.c",
"/deps/BearSSL/src/int/i32_sub.c",
"/deps/BearSSL/src/int/i32_tmont.c",
"/deps/BearSSL/src/int/i62_modpow2.c",
"/deps/BearSSL/src/kdf/hkdf.c",
"/deps/BearSSL/src/kdf/shake.c",
"/deps/BearSSL/src/mac/hmac.c",
"/deps/BearSSL/src/mac/hmac_ct.c",
"/deps/BearSSL/src/rand/aesctr_drbg.c",
"/deps/BearSSL/src/rand/hmac_drbg.c",
"/deps/BearSSL/src/rand/sysrng.c",
"/deps/BearSSL/src/rsa/rsa_default_keygen.c",
"/deps/BearSSL/src/rsa/rsa_default_modulus.c",
"/deps/BearSSL/src/rsa/rsa_default_oaep_decrypt.c",
"/deps/BearSSL/src/rsa/rsa_default_oaep_encrypt.c",
"/deps/BearSSL/src/rsa/rsa_default_pkcs1_sign.c",
"/deps/BearSSL/src/rsa/rsa_default_pkcs1_vrfy.c",
"/deps/BearSSL/src/rsa/rsa_default_priv.c",
"/deps/BearSSL/src/rsa/rsa_default_privexp.c",
"/deps/BearSSL/src/rsa/rsa_default_pss_sign.c",
"/deps/BearSSL/src/rsa/rsa_default_pss_vrfy.c",
"/deps/BearSSL/src/rsa/rsa_default_pub.c",
"/deps/BearSSL/src/rsa/rsa_default_pubexp.c",
"/deps/BearSSL/src/rsa/rsa_i15_keygen.c",
"/deps/BearSSL/src/rsa/rsa_i15_modulus.c",
"/deps/BearSSL/src/rsa/rsa_i15_oaep_decrypt.c",
"/deps/BearSSL/src/rsa/rsa_i15_oaep_encrypt.c",
"/deps/BearSSL/src/rsa/rsa_i15_pkcs1_sign.c",
"/deps/BearSSL/src/rsa/rsa_i15_pkcs1_vrfy.c",
"/deps/BearSSL/src/rsa/rsa_i15_priv.c",
"/deps/BearSSL/src/rsa/rsa_i15_privexp.c",
"/deps/BearSSL/src/rsa/rsa_i15_pss_sign.c",
"/deps/BearSSL/src/rsa/rsa_i15_pss_vrfy.c",
"/deps/BearSSL/src/rsa/rsa_i15_pub.c",
"/deps/BearSSL/src/rsa/rsa_i15_pubexp.c",
"/deps/BearSSL/src/rsa/rsa_i31_keygen.c",
"/deps/BearSSL/src/rsa/rsa_i31_keygen_inner.c",
"/deps/BearSSL/src/rsa/rsa_i31_modulus.c",
"/deps/BearSSL/src/rsa/rsa_i31_oaep_decrypt.c",
"/deps/BearSSL/src/rsa/rsa_i31_oaep_encrypt.c",
"/deps/BearSSL/src/rsa/rsa_i31_pkcs1_sign.c",
"/deps/BearSSL/src/rsa/rsa_i31_pkcs1_vrfy.c",
"/deps/BearSSL/src/rsa/rsa_i31_priv.c",
"/deps/BearSSL/src/rsa/rsa_i31_privexp.c",
"/deps/BearSSL/src/rsa/rsa_i31_pss_sign.c",
"/deps/BearSSL/src/rsa/rsa_i31_pss_vrfy.c",
"/deps/BearSSL/src/rsa/rsa_i31_pub.c",
"/deps/BearSSL/src/rsa/rsa_i31_pubexp.c",
"/deps/BearSSL/src/rsa/rsa_i32_oaep_decrypt.c",
"/deps/BearSSL/src/rsa/rsa_i32_oaep_encrypt.c",
"/deps/BearSSL/src/rsa/rsa_i32_pkcs1_sign.c",
"/deps/BearSSL/src/rsa/rsa_i32_pkcs1_vrfy.c",
"/deps/BearSSL/src/rsa/rsa_i32_priv.c",
"/deps/BearSSL/src/rsa/rsa_i32_pss_sign.c",
"/deps/BearSSL/src/rsa/rsa_i32_pss_vrfy.c",
"/deps/BearSSL/src/rsa/rsa_i32_pub.c",
"/deps/BearSSL/src/rsa/rsa_i62_keygen.c",
"/deps/BearSSL/src/rsa/rsa_i62_oaep_decrypt.c",
"/deps/BearSSL/src/rsa/rsa_i62_oaep_encrypt.c",
"/deps/BearSSL/src/rsa/rsa_i62_pkcs1_sign.c",
"/deps/BearSSL/src/rsa/rsa_i62_pkcs1_vrfy.c",
"/deps/BearSSL/src/rsa/rsa_i62_priv.c",
"/deps/BearSSL/src/rsa/rsa_i62_pss_sign.c",
"/deps/BearSSL/src/rsa/rsa_i62_pss_vrfy.c",
"/deps/BearSSL/src/rsa/rsa_i62_pub.c",
"/deps/BearSSL/src/rsa/rsa_oaep_pad.c",
"/deps/BearSSL/src/rsa/rsa_oaep_unpad.c",
"/deps/BearSSL/src/rsa/rsa_pkcs1_sig_pad.c",
"/deps/BearSSL/src/rsa/rsa_pkcs1_sig_unpad.c",
"/deps/BearSSL/src/rsa/rsa_pss_sig_pad.c",
"/deps/BearSSL/src/rsa/rsa_pss_sig_unpad.c",
"/deps/BearSSL/src/rsa/rsa_ssl_decrypt.c",
"/deps/BearSSL/src/ssl/prf.c",
"/deps/BearSSL/src/ssl/prf_md5sha1.c",
"/deps/BearSSL/src/ssl/prf_sha256.c",
"/deps/BearSSL/src/ssl/prf_sha384.c",
"/deps/BearSSL/src/ssl/ssl_ccert_single_ec.c",
"/deps/BearSSL/src/ssl/ssl_ccert_single_rsa.c",
"/deps/BearSSL/src/ssl/ssl_client.c",
"/deps/BearSSL/src/ssl/ssl_client_default_rsapub.c",
"/deps/BearSSL/src/ssl/ssl_client_full.c",
"/deps/BearSSL/src/ssl/ssl_engine.c",
"/deps/BearSSL/src/ssl/ssl_engine_default_aescbc.c",
"/deps/BearSSL/src/ssl/ssl_engine_default_aesccm.c",
"/deps/BearSSL/src/ssl/ssl_engine_default_aesgcm.c",
"/deps/BearSSL/src/ssl/ssl_engine_default_chapol.c",
"/deps/BearSSL/src/ssl/ssl_engine_default_descbc.c",
"/deps/BearSSL/src/ssl/ssl_engine_default_ec.c",
"/deps/BearSSL/src/ssl/ssl_engine_default_ecdsa.c",
"/deps/BearSSL/src/ssl/ssl_engine_default_rsavrfy.c",
"/deps/BearSSL/src/ssl/ssl_hashes.c",
"/deps/BearSSL/src/ssl/ssl_hs_client.c",
"/deps/BearSSL/src/ssl/ssl_hs_server.c",
"/deps/BearSSL/src/ssl/ssl_io.c",
"/deps/BearSSL/src/ssl/ssl_keyexport.c",
"/deps/BearSSL/src/ssl/ssl_lru.c",
"/deps/BearSSL/src/ssl/ssl_rec_cbc.c",
"/deps/BearSSL/src/ssl/ssl_rec_ccm.c",
"/deps/BearSSL/src/ssl/ssl_rec_chapol.c",
"/deps/BearSSL/src/ssl/ssl_rec_gcm.c",
"/deps/BearSSL/src/ssl/ssl_scert_single_ec.c",
"/deps/BearSSL/src/ssl/ssl_scert_single_rsa.c",
"/deps/BearSSL/src/ssl/ssl_server.c",
"/deps/BearSSL/src/ssl/ssl_server_full_ec.c",
"/deps/BearSSL/src/ssl/ssl_server_full_rsa.c",
"/deps/BearSSL/src/ssl/ssl_server_mine2c.c",
"/deps/BearSSL/src/ssl/ssl_server_mine2g.c",
"/deps/BearSSL/src/ssl/ssl_server_minf2c.c",
"/deps/BearSSL/src/ssl/ssl_server_minf2g.c",
"/deps/BearSSL/src/ssl/ssl_server_minr2g.c",
"/deps/BearSSL/src/ssl/ssl_server_minu2g.c",
"/deps/BearSSL/src/ssl/ssl_server_minv2g.c",
"/deps/BearSSL/src/symcipher/aes_big_cbcdec.c",
"/deps/BearSSL/src/symcipher/aes_big_cbcenc.c",
"/deps/BearSSL/src/symcipher/aes_big_ctr.c",
"/deps/BearSSL/src/symcipher/aes_big_ctrcbc.c",
"/deps/BearSSL/src/symcipher/aes_big_dec.c",
"/deps/BearSSL/src/symcipher/aes_big_enc.c",
"/deps/BearSSL/src/symcipher/aes_common.c",
"/deps/BearSSL/src/symcipher/aes_ct.c",
"/deps/BearSSL/src/symcipher/aes_ct64.c",
"/deps/BearSSL/src/symcipher/aes_ct64_cbcdec.c",
"/deps/BearSSL/src/symcipher/aes_ct64_cbcenc.c",
"/deps/BearSSL/src/symcipher/aes_ct64_ctr.c",
"/deps/BearSSL/src/symcipher/aes_ct64_ctrcbc.c",
"/deps/BearSSL/src/symcipher/aes_ct64_dec.c",
"/deps/BearSSL/src/symcipher/aes_ct64_enc.c",
"/deps/BearSSL/src/symcipher/aes_ct_cbcdec.c",
"/deps/BearSSL/src/symcipher/aes_ct_cbcenc.c",
"/deps/BearSSL/src/symcipher/aes_ct_ctr.c",
"/deps/BearSSL/src/symcipher/aes_ct_ctrcbc.c",
"/deps/BearSSL/src/symcipher/aes_ct_dec.c",
"/deps/BearSSL/src/symcipher/aes_ct_enc.c",
"/deps/BearSSL/src/symcipher/aes_pwr8.c",
"/deps/BearSSL/src/symcipher/aes_pwr8_cbcdec.c",
"/deps/BearSSL/src/symcipher/aes_pwr8_cbcenc.c",
"/deps/BearSSL/src/symcipher/aes_pwr8_ctr.c",
"/deps/BearSSL/src/symcipher/aes_pwr8_ctrcbc.c",
"/deps/BearSSL/src/symcipher/aes_small_cbcdec.c",
"/deps/BearSSL/src/symcipher/aes_small_cbcenc.c",
"/deps/BearSSL/src/symcipher/aes_small_ctr.c",
"/deps/BearSSL/src/symcipher/aes_small_ctrcbc.c",
"/deps/BearSSL/src/symcipher/aes_small_dec.c",
"/deps/BearSSL/src/symcipher/aes_small_enc.c",
"/deps/BearSSL/src/symcipher/aes_x86ni.c",
"/deps/BearSSL/src/symcipher/aes_x86ni_cbcdec.c",
"/deps/BearSSL/src/symcipher/aes_x86ni_cbcenc.c",
"/deps/BearSSL/src/symcipher/aes_x86ni_ctr.c",
"/deps/BearSSL/src/symcipher/aes_x86ni_ctrcbc.c",
"/deps/BearSSL/src/symcipher/chacha20_ct.c",
"/deps/BearSSL/src/symcipher/chacha20_sse2.c",
"/deps/BearSSL/src/symcipher/des_ct.c",
"/deps/BearSSL/src/symcipher/des_ct_cbcdec.c",
"/deps/BearSSL/src/symcipher/des_ct_cbcenc.c",
"/deps/BearSSL/src/symcipher/des_support.c",
"/deps/BearSSL/src/symcipher/des_tab.c",
"/deps/BearSSL/src/symcipher/des_tab_cbcdec.c",
"/deps/BearSSL/src/symcipher/des_tab_cbcenc.c",
"/deps/BearSSL/src/symcipher/poly1305_ctmul.c",
"/deps/BearSSL/src/symcipher/poly1305_ctmul32.c",
"/deps/BearSSL/src/symcipher/poly1305_ctmulq.c",
"/deps/BearSSL/src/symcipher/poly1305_i15.c",
"/deps/BearSSL/src/x509/asn1enc.c",
"/deps/BearSSL/src/x509/encode_ec_pk8der.c",
"/deps/BearSSL/src/x509/encode_ec_rawder.c",
"/deps/BearSSL/src/x509/encode_rsa_pk8der.c",
"/deps/BearSSL/src/x509/encode_rsa_rawder.c",
"/deps/BearSSL/src/x509/skey_decoder.c",
"/deps/BearSSL/src/x509/x509_decoder.c",
"/deps/BearSSL/src/x509/x509_knownkey.c",
"/deps/BearSSL/src/x509/x509_minimal.c",
"/deps/BearSSL/src/x509/x509_minimal_full.c",
}; | build.zig |
const clap = @import("clap");
const format = @import("format");
const std = @import("std");
const ston = @import("ston");
const util = @import("util");
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 os = std.os;
const rand = std.rand;
const testing = std.testing;
const unicode = std.unicode;
const Utf8 = util.unicode.Utf8View;
const escape = util.escape;
const Program = @This();
allocator: mem.Allocator,
seed: u64,
pokemons: NameSet = NameSet{},
trainers: NameSet = NameSet{},
moves: NameSet = NameSet{},
abilities: NameSet = NameSet{},
items: NameSet = NameSet{},
pub const main = util.generateMain(Program);
pub const version = "0.0.0";
pub const description =
\\Randomizes the names of things.
\\
;
pub const params = &[_]clap.Param(clap.Help){
clap.parseParam("-h, --help Display this help text and exit. ") catch unreachable,
clap.parseParam("-s, --seed <INT> The seed to use for random numbers. A random seed will be picked if this is not specified.") catch unreachable,
clap.parseParam("-v, --version Output version information and exit. ") catch unreachable,
};
pub fn init(allocator: mem.Allocator, args: anytype) !Program {
const seed = try util.args.seed(args);
return Program{
.allocator = allocator,
.seed = seed,
};
}
pub fn run(
program: *Program,
comptime Reader: type,
comptime Writer: type,
stdio: util.CustomStdIoStreams(Reader, Writer),
) anyerror!void {
try format.io(program.allocator, stdio.in, stdio.out, program, useGame);
try program.randomize();
try program.output(stdio.out);
}
fn output(program: *Program, writer: anytype) !void {
try ston.serialize(writer, .{
.pokemons = program.pokemons,
.trainers = program.trainers,
.moves = program.moves,
.abilities = program.abilities,
.items = program.items,
});
}
fn useGame(program: *Program, parsed: format.Game) !void {
const allocator = program.allocator;
switch (parsed) {
.pokemons => |pokemons| switch (pokemons.value) {
.name => |str| {
_ = try program.pokemons.put(allocator, pokemons.index, .{
.name = .{ .value = try escape.default.unescapeAlloc(allocator, str) },
});
return;
},
.stats,
.types,
.catch_rate,
.base_exp_yield,
.ev_yield,
.items,
.gender_ratio,
.egg_cycles,
.base_friendship,
.growth_rate,
.egg_groups,
.abilities,
.color,
.evos,
.moves,
.tms,
.hms,
.pokedex_entry,
=> return error.DidNotConsumeData,
},
.trainers => |trainers| switch (trainers.value) {
.name => |str| {
_ = try program.trainers.put(allocator, trainers.index, .{
.name = .{ .value = try escape.default.unescapeAlloc(allocator, str) },
});
return;
},
.class,
.encounter_music,
.trainer_picture,
.items,
.party_type,
.party_size,
.party,
=> return error.DidNotConsumeData,
},
.moves => |moves| switch (moves.value) {
.name => |str| {
_ = try program.moves.put(allocator, moves.index, .{
.name = .{ .value = try escape.default.unescapeAlloc(allocator, str) },
});
return;
},
.description,
.effect,
.power,
.type,
.accuracy,
.pp,
.target,
.priority,
.category,
=> return error.DidNotConsumeData,
},
.abilities => |abilities| switch (abilities.value) {
.name => |str| {
_ = try program.abilities.put(allocator, abilities.index, .{
.name = .{ .value = try escape.default.unescapeAlloc(allocator, str) },
});
return;
},
},
.items => |items| switch (items.value) {
.name => |str| {
_ = try program.items.put(allocator, items.index, .{
.name = .{ .value = try escape.default.unescapeAlloc(allocator, str) },
});
return;
},
.battle_effect,
.description,
.price,
.pocket,
=> return error.DidNotConsumeData,
},
.version,
.game_title,
.gamecode,
.instant_text,
.starters,
.text_delays,
.types,
.tms,
.hms,
.pokedex,
.maps,
.wild_pokemons,
.static_pokemons,
.given_pokemons,
.pokeball_items,
.hidden_hollows,
.text,
=> return error.DidNotConsumeData,
}
unreachable;
}
fn randomize(program: *Program) !void {
const allocator = program.allocator;
const random = rand.DefaultPrng.init(program.seed).random();
for ([_]NameSet{
program.pokemons,
program.trainers,
program.moves,
program.abilities,
program.items,
}) |set| {
var max: usize = 0;
var pairs = CodepointPairs{};
// Build our codepoint pair map. This map contains a mapping from C1 -> []C2+N,
// where CX is a codepoint and N is the number of times C2 was seen after C1.
// This map will be used to generate names later.
for (set.values()) |item| {
const view = unicode.Utf8View.init(item.name.value) catch continue;
var node = (try pairs.getOrPutValue(allocator, start_of_string, .{})).value_ptr;
var it = view.iterator();
while (it.nextCodepointSlice()) |code| {
const occurance = (try node.codepoints.getOrPutValue(allocator, code, 0))
.value_ptr;
occurance.* += 1;
node.total += 1;
node = (try pairs.getOrPutValue(allocator, code, .{})).value_ptr;
}
const occurance = (try node.codepoints.getOrPutValue(allocator, end_of_string, 0))
.value_ptr;
occurance.* += 1;
node.total += 1;
max = math.max(max, item.name.value.len);
}
// Generate our random names from our pair map. This is done by picking a C2
// based on our current C1. C2 is chosen by using the occurnaces of C2 as weights
// and picking at random from here.
for (set.values()) |*str| {
var new_name = std.ArrayList(u8).init(allocator);
var node = pairs.get(start_of_string).?;
while (new_name.items.len < max) {
var i = random.intRangeLessThan(usize, 0, node.total);
const pick = for (node.codepoints.values()) |item, j| {
if (i < item)
break node.codepoints.keys()[j];
i -= item;
} else unreachable;
if (mem.eql(u8, pick, end_of_string))
break;
if (new_name.items.len + pick.len > max)
break;
try new_name.appendSlice(pick);
node = pairs.get(pick).?;
}
str.name.value = new_name.toOwnedSlice();
}
}
}
const end_of_string = "\x00";
const start_of_string = "\x01";
const CodepointPairs = std.StringArrayHashMapUnmanaged(Occurences);
const NameSet = std.AutoArrayHashMapUnmanaged(u16, Name);
const Name = struct {
name: ston.String([]const u8),
};
const Occurences = struct {
total: usize = 0,
codepoints: std.StringArrayHashMapUnmanaged(usize) = std.StringArrayHashMapUnmanaged(usize){},
};
test "tm35-random-names" {
// TODO: Tests
} | src/randomizers/tm35-rand-names.zig |
pub const WCM_SETTINGS_ID_FLAG_REFERENCE = @as(u32, 0);
pub const WCM_SETTINGS_ID_FLAG_DEFINITION = @as(u32, 1);
pub const LINK_STORE_TO_ENGINE_INSTANCE = @as(u32, 1);
pub const LIMITED_VALIDATION_MODE = @as(u32, 1);
pub const WCM_E_INTERNALERROR = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255424));
pub const WCM_E_STATENODENOTFOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255423));
pub const WCM_E_STATENODENOTALLOWED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255422));
pub const WCM_E_ATTRIBUTENOTFOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255421));
pub const WCM_E_ATTRIBUTENOTALLOWED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255420));
pub const WCM_E_INVALIDVALUE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255419));
pub const WCM_E_INVALIDVALUEFORMAT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255418));
pub const WCM_E_TYPENOTSPECIFIED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255417));
pub const WCM_E_INVALIDDATATYPE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255416));
pub const WCM_E_NOTPOSITIONED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255415));
pub const WCM_E_READONLYITEM = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255414));
pub const WCM_E_INVALIDPATH = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255413));
pub const WCM_E_WRONGESCAPESTRING = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255412));
pub const WCM_E_INVALIDVERSIONFORMAT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255411));
pub const WCM_E_INVALIDLANGUAGEFORMAT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255410));
pub const WCM_E_KEYNOTCHANGEABLE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255409));
pub const WCM_E_EXPRESSIONNOTFOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255408));
pub const WCM_E_SUBSTITUTIONNOTFOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255407));
pub const WCM_E_USERALREADYREGISTERED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255406));
pub const WCM_E_USERNOTFOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255405));
pub const WCM_E_NAMESPACENOTFOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255404));
pub const WCM_E_NAMESPACEALREADYREGISTERED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255403));
pub const WCM_E_STORECORRUPTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255402));
pub const WCM_E_INVALIDEXPRESSIONSYNTAX = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255401));
pub const WCM_E_NOTIFICATIONNOTFOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255400));
pub const WCM_E_CONFLICTINGASSERTION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255399));
pub const WCM_E_ASSERTIONFAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255398));
pub const WCM_E_DUPLICATENAME = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255397));
pub const WCM_E_INVALIDKEY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255396));
pub const WCM_E_INVALIDSTREAM = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255395));
pub const WCM_E_HANDLERNOTFOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255394));
pub const WCM_E_INVALIDHANDLERSYNTAX = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255393));
pub const WCM_E_VALIDATIONFAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255392));
pub const WCM_E_RESTRICTIONFAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255391));
pub const WCM_E_MANIFESTCOMPILATIONFAILED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255390));
pub const WCM_E_CYCLICREFERENCE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255389));
pub const WCM_E_MIXTYPEASSERTION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255388));
pub const WCM_E_NOTSUPPORTEDFUNCTION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255387));
pub const WCM_E_VALUETOOBIG = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255386));
pub const WCM_E_INVALIDATTRIBUTECOMBINATION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255385));
pub const WCM_E_ABORTOPERATION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255384));
pub const WCM_E_MISSINGCONFIGURATION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255383));
pub const WCM_E_INVALIDPROCESSORFORMAT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255382));
pub const WCM_E_SOURCEMANEMPTYVALUE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145255381));
pub const WCM_S_INTERNALERROR = @import("../zig.zig").typedConst(HRESULT, @as(i32, 2232320));
pub const WCM_S_ATTRIBUTENOTFOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, 2232321));
pub const WCM_S_LEGACYSETTINGWARNING = @import("../zig.zig").typedConst(HRESULT, @as(i32, 2232322));
pub const WCM_S_INVALIDATTRIBUTECOMBINATION = @import("../zig.zig").typedConst(HRESULT, @as(i32, 2232324));
pub const WCM_S_ATTRIBUTENOTALLOWED = @import("../zig.zig").typedConst(HRESULT, @as(i32, 2232325));
pub const WCM_S_NAMESPACENOTFOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, 2232326));
pub const WCM_E_UNKNOWNRESULT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2145251325));
//--------------------------------------------------------------------------------
// Section: Types (16)
//--------------------------------------------------------------------------------
const CLSID_SettingsEngine_Value = @import("../zig.zig").Guid.initString("9f7d7bb5-20b3-11da-81a5-0030f1642e3c");
pub const CLSID_SettingsEngine = &CLSID_SettingsEngine_Value;
pub const WcmTargetMode = enum(i32) {
fflineMode = 1,
nlineMode = 2,
};
pub const OfflineMode = WcmTargetMode.fflineMode;
pub const OnlineMode = WcmTargetMode.nlineMode;
pub const WcmNamespaceEnumerationFlags = enum(i32) {
SharedEnumeration = 1,
UserEnumeration = 2,
AllEnumeration = 3,
};
pub const SharedEnumeration = WcmNamespaceEnumerationFlags.SharedEnumeration;
pub const UserEnumeration = WcmNamespaceEnumerationFlags.UserEnumeration;
pub const AllEnumeration = WcmNamespaceEnumerationFlags.AllEnumeration;
pub const WcmDataType = enum(i32) {
Byte = 1,
SByte = 2,
UInt16 = 3,
Int16 = 4,
UInt32 = 5,
Int32 = 6,
UInt64 = 7,
Int64 = 8,
Boolean = 11,
String = 12,
FlagArray = 32768,
};
pub const dataTypeByte = WcmDataType.Byte;
pub const dataTypeSByte = WcmDataType.SByte;
pub const dataTypeUInt16 = WcmDataType.UInt16;
pub const dataTypeInt16 = WcmDataType.Int16;
pub const dataTypeUInt32 = WcmDataType.UInt32;
pub const dataTypeInt32 = WcmDataType.Int32;
pub const dataTypeUInt64 = WcmDataType.UInt64;
pub const dataTypeInt64 = WcmDataType.Int64;
pub const dataTypeBoolean = WcmDataType.Boolean;
pub const dataTypeString = WcmDataType.String;
pub const dataTypeFlagArray = WcmDataType.FlagArray;
pub const WcmSettingType = enum(i32) {
Scalar = 1,
Complex = 2,
List = 3,
};
pub const settingTypeScalar = WcmSettingType.Scalar;
pub const settingTypeComplex = WcmSettingType.Complex;
pub const settingTypeList = WcmSettingType.List;
pub const WcmRestrictionFacets = enum(i32) {
MaxLength = 1,
Enumeration = 2,
MaxInclusive = 4,
MinInclusive = 8,
};
pub const restrictionFacetMaxLength = WcmRestrictionFacets.MaxLength;
pub const restrictionFacetEnumeration = WcmRestrictionFacets.Enumeration;
pub const restrictionFacetMaxInclusive = WcmRestrictionFacets.MaxInclusive;
pub const restrictionFacetMinInclusive = WcmRestrictionFacets.MinInclusive;
pub const WcmUserStatus = enum(i32) {
nknownStatus = 0,
serRegistered = 1,
serUnregistered = 2,
serLoaded = 3,
serUnloaded = 4,
};
pub const UnknownStatus = WcmUserStatus.nknownStatus;
pub const UserRegistered = WcmUserStatus.serRegistered;
pub const UserUnregistered = WcmUserStatus.serUnregistered;
pub const UserLoaded = WcmUserStatus.serLoaded;
pub const UserUnloaded = WcmUserStatus.serUnloaded;
pub const WcmNamespaceAccess = enum(i32) {
OnlyAccess = 1,
WriteAccess = 2,
};
pub const ReadOnlyAccess = WcmNamespaceAccess.OnlyAccess;
pub const ReadWriteAccess = WcmNamespaceAccess.WriteAccess;
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IItemEnumerator_Value = @import("../zig.zig").Guid.initString("9f7d7bb7-20b3-11da-81a5-0030f1642e3c");
pub const IID_IItemEnumerator = &IID_IItemEnumerator_Value;
pub const IItemEnumerator = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Current: fn(
self: *const IItemEnumerator,
Item: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MoveNext: fn(
self: *const IItemEnumerator,
ItemValid: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reset: fn(
self: *const IItemEnumerator,
) 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 IItemEnumerator_Current(self: *const T, Item: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IItemEnumerator.VTable, self.vtable).Current(@ptrCast(*const IItemEnumerator, self), Item);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IItemEnumerator_MoveNext(self: *const T, ItemValid: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IItemEnumerator.VTable, self.vtable).MoveNext(@ptrCast(*const IItemEnumerator, self), ItemValid);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IItemEnumerator_Reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IItemEnumerator.VTable, self.vtable).Reset(@ptrCast(*const IItemEnumerator, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_ISettingsIdentity_Value = @import("../zig.zig").Guid.initString("9f7d7bb6-20b3-11da-81a5-0030f1642e3c");
pub const IID_ISettingsIdentity = &IID_ISettingsIdentity_Value;
pub const ISettingsIdentity = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetAttribute: fn(
self: *const ISettingsIdentity,
Reserved: ?*anyopaque,
Name: ?[*:0]const u16,
Value: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetAttribute: fn(
self: *const ISettingsIdentity,
Reserved: ?*anyopaque,
Name: ?[*:0]const u16,
Value: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFlags: fn(
self: *const ISettingsIdentity,
Flags: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetFlags: fn(
self: *const ISettingsIdentity,
Flags: 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 ISettingsIdentity_GetAttribute(self: *const T, Reserved: ?*anyopaque, Name: ?[*:0]const u16, Value: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsIdentity.VTable, self.vtable).GetAttribute(@ptrCast(*const ISettingsIdentity, self), Reserved, Name, Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsIdentity_SetAttribute(self: *const T, Reserved: ?*anyopaque, Name: ?[*:0]const u16, Value: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsIdentity.VTable, self.vtable).SetAttribute(@ptrCast(*const ISettingsIdentity, self), Reserved, Name, Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsIdentity_GetFlags(self: *const T, Flags: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsIdentity.VTable, self.vtable).GetFlags(@ptrCast(*const ISettingsIdentity, self), Flags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsIdentity_SetFlags(self: *const T, Flags: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsIdentity.VTable, self.vtable).SetFlags(@ptrCast(*const ISettingsIdentity, self), Flags);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_ITargetInfo_Value = @import("../zig.zig").Guid.initString("9f7d7bb8-20b3-11da-81a5-0030f1642e3c");
pub const IID_ITargetInfo = &IID_ITargetInfo_Value;
pub const ITargetInfo = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetTargetMode: fn(
self: *const ITargetInfo,
TargetMode: ?*WcmTargetMode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetTargetMode: fn(
self: *const ITargetInfo,
TargetMode: WcmTargetMode,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTemporaryStoreLocation: fn(
self: *const ITargetInfo,
TemporaryStoreLocation: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetTemporaryStoreLocation: fn(
self: *const ITargetInfo,
TemporaryStoreLocation: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTargetID: fn(
self: *const ITargetInfo,
TargetID: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetTargetID: fn(
self: *const ITargetInfo,
TargetID: Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTargetProcessorArchitecture: fn(
self: *const ITargetInfo,
ProcessorArchitecture: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetTargetProcessorArchitecture: fn(
self: *const ITargetInfo,
ProcessorArchitecture: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetProperty: fn(
self: *const ITargetInfo,
Offline: BOOL,
Property: ?[*:0]const u16,
Value: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetProperty: fn(
self: *const ITargetInfo,
Offline: BOOL,
Property: ?[*:0]const u16,
Value: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetEnumerator: fn(
self: *const ITargetInfo,
Enumerator: ?*?*IItemEnumerator,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ExpandTarget: fn(
self: *const ITargetInfo,
Offline: BOOL,
Location: ?[*:0]const u16,
ExpandedLocation: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ExpandTargetPath: fn(
self: *const ITargetInfo,
Offline: BOOL,
Location: ?[*:0]const u16,
ExpandedLocation: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetModulePath: fn(
self: *const ITargetInfo,
Module: ?[*:0]const u16,
Path: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
LoadModule: fn(
self: *const ITargetInfo,
Module: ?[*:0]const u16,
ModuleHandle: ?*?HINSTANCE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetWow64Context: fn(
self: *const ITargetInfo,
InstallerModule: ?[*:0]const u16,
Wow64Context: ?*u8,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TranslateWow64: fn(
self: *const ITargetInfo,
ClientArchitecture: ?[*:0]const u16,
Value: ?[*:0]const u16,
TranslatedValue: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetSchemaHiveLocation: fn(
self: *const ITargetInfo,
pwzHiveDir: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSchemaHiveLocation: fn(
self: *const ITargetInfo,
pHiveLocation: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetSchemaHiveMountName: fn(
self: *const ITargetInfo,
pwzMountName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSchemaHiveMountName: fn(
self: *const ITargetInfo,
pMountName: ?*?BSTR,
) 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 ITargetInfo_GetTargetMode(self: *const T, TargetMode: ?*WcmTargetMode) callconv(.Inline) HRESULT {
return @ptrCast(*const ITargetInfo.VTable, self.vtable).GetTargetMode(@ptrCast(*const ITargetInfo, self), TargetMode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITargetInfo_SetTargetMode(self: *const T, TargetMode: WcmTargetMode) callconv(.Inline) HRESULT {
return @ptrCast(*const ITargetInfo.VTable, self.vtable).SetTargetMode(@ptrCast(*const ITargetInfo, self), TargetMode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITargetInfo_GetTemporaryStoreLocation(self: *const T, TemporaryStoreLocation: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITargetInfo.VTable, self.vtable).GetTemporaryStoreLocation(@ptrCast(*const ITargetInfo, self), TemporaryStoreLocation);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITargetInfo_SetTemporaryStoreLocation(self: *const T, TemporaryStoreLocation: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const ITargetInfo.VTable, self.vtable).SetTemporaryStoreLocation(@ptrCast(*const ITargetInfo, self), TemporaryStoreLocation);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITargetInfo_GetTargetID(self: *const T, TargetID: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITargetInfo.VTable, self.vtable).GetTargetID(@ptrCast(*const ITargetInfo, self), TargetID);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITargetInfo_SetTargetID(self: *const T, TargetID: Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const ITargetInfo.VTable, self.vtable).SetTargetID(@ptrCast(*const ITargetInfo, self), TargetID);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITargetInfo_GetTargetProcessorArchitecture(self: *const T, ProcessorArchitecture: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITargetInfo.VTable, self.vtable).GetTargetProcessorArchitecture(@ptrCast(*const ITargetInfo, self), ProcessorArchitecture);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITargetInfo_SetTargetProcessorArchitecture(self: *const T, ProcessorArchitecture: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const ITargetInfo.VTable, self.vtable).SetTargetProcessorArchitecture(@ptrCast(*const ITargetInfo, self), ProcessorArchitecture);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITargetInfo_GetProperty(self: *const T, Offline: BOOL, Property: ?[*:0]const u16, Value: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITargetInfo.VTable, self.vtable).GetProperty(@ptrCast(*const ITargetInfo, self), Offline, Property, Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITargetInfo_SetProperty(self: *const T, Offline: BOOL, Property: ?[*:0]const u16, Value: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const ITargetInfo.VTable, self.vtable).SetProperty(@ptrCast(*const ITargetInfo, self), Offline, Property, Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITargetInfo_GetEnumerator(self: *const T, Enumerator: ?*?*IItemEnumerator) callconv(.Inline) HRESULT {
return @ptrCast(*const ITargetInfo.VTable, self.vtable).GetEnumerator(@ptrCast(*const ITargetInfo, self), Enumerator);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITargetInfo_ExpandTarget(self: *const T, Offline: BOOL, Location: ?[*:0]const u16, ExpandedLocation: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITargetInfo.VTable, self.vtable).ExpandTarget(@ptrCast(*const ITargetInfo, self), Offline, Location, ExpandedLocation);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITargetInfo_ExpandTargetPath(self: *const T, Offline: BOOL, Location: ?[*:0]const u16, ExpandedLocation: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITargetInfo.VTable, self.vtable).ExpandTargetPath(@ptrCast(*const ITargetInfo, self), Offline, Location, ExpandedLocation);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITargetInfo_SetModulePath(self: *const T, Module: ?[*:0]const u16, Path: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const ITargetInfo.VTable, self.vtable).SetModulePath(@ptrCast(*const ITargetInfo, self), Module, Path);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITargetInfo_LoadModule(self: *const T, Module: ?[*:0]const u16, ModuleHandle: ?*?HINSTANCE) callconv(.Inline) HRESULT {
return @ptrCast(*const ITargetInfo.VTable, self.vtable).LoadModule(@ptrCast(*const ITargetInfo, self), Module, ModuleHandle);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITargetInfo_SetWow64Context(self: *const T, InstallerModule: ?[*:0]const u16, Wow64Context: ?*u8) callconv(.Inline) HRESULT {
return @ptrCast(*const ITargetInfo.VTable, self.vtable).SetWow64Context(@ptrCast(*const ITargetInfo, self), InstallerModule, Wow64Context);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITargetInfo_TranslateWow64(self: *const T, ClientArchitecture: ?[*:0]const u16, Value: ?[*:0]const u16, TranslatedValue: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITargetInfo.VTable, self.vtable).TranslateWow64(@ptrCast(*const ITargetInfo, self), ClientArchitecture, Value, TranslatedValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITargetInfo_SetSchemaHiveLocation(self: *const T, pwzHiveDir: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const ITargetInfo.VTable, self.vtable).SetSchemaHiveLocation(@ptrCast(*const ITargetInfo, self), pwzHiveDir);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITargetInfo_GetSchemaHiveLocation(self: *const T, pHiveLocation: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITargetInfo.VTable, self.vtable).GetSchemaHiveLocation(@ptrCast(*const ITargetInfo, self), pHiveLocation);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITargetInfo_SetSchemaHiveMountName(self: *const T, pwzMountName: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const ITargetInfo.VTable, self.vtable).SetSchemaHiveMountName(@ptrCast(*const ITargetInfo, self), pwzMountName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITargetInfo_GetSchemaHiveMountName(self: *const T, pMountName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITargetInfo.VTable, self.vtable).GetSchemaHiveMountName(@ptrCast(*const ITargetInfo, self), pMountName);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_ISettingsEngine_Value = @import("../zig.zig").Guid.initString("9f7d7bb9-20b3-11da-81a5-0030f1642e3c");
pub const IID_ISettingsEngine = &IID_ISettingsEngine_Value;
pub const ISettingsEngine = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetNamespaces: fn(
self: *const ISettingsEngine,
Flags: WcmNamespaceEnumerationFlags,
Reserved: ?*anyopaque,
Namespaces: ?*?*IItemEnumerator,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetNamespace: fn(
self: *const ISettingsEngine,
SettingsID: ?*ISettingsIdentity,
Access: WcmNamespaceAccess,
Reserved: ?*anyopaque,
NamespaceItem: ?*?*ISettingsNamespace,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetErrorDescription: fn(
self: *const ISettingsEngine,
HResult: i32,
Message: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateSettingsIdentity: fn(
self: *const ISettingsEngine,
SettingsID: ?*?*ISettingsIdentity,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStoreStatus: fn(
self: *const ISettingsEngine,
Reserved: ?*anyopaque,
Status: ?*WcmUserStatus,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
LoadStore: fn(
self: *const ISettingsEngine,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UnloadStore: fn(
self: *const ISettingsEngine,
Reserved: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RegisterNamespace: fn(
self: *const ISettingsEngine,
SettingsID: ?*ISettingsIdentity,
Stream: ?*IStream,
PushSettings: BOOL,
Results: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UnregisterNamespace: fn(
self: *const ISettingsEngine,
SettingsID: ?*ISettingsIdentity,
RemoveSettings: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateTargetInfo: fn(
self: *const ISettingsEngine,
Target: ?*?*ITargetInfo,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTargetInfo: fn(
self: *const ISettingsEngine,
Target: ?*?*ITargetInfo,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetTargetInfo: fn(
self: *const ISettingsEngine,
Target: ?*ITargetInfo,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateSettingsContext: fn(
self: *const ISettingsEngine,
Flags: u32,
Reserved: ?*anyopaque,
SettingsContext: ?*?*ISettingsContext,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetSettingsContext: fn(
self: *const ISettingsEngine,
SettingsContext: ?*ISettingsContext,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ApplySettingsContext: fn(
self: *const ISettingsEngine,
SettingsContext: ?*ISettingsContext,
pppwzIdentities: ?*?*?PWSTR,
pcIdentities: ?*usize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSettingsContext: fn(
self: *const ISettingsEngine,
SettingsContext: ?*?*ISettingsContext,
) 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 ISettingsEngine_GetNamespaces(self: *const T, Flags: WcmNamespaceEnumerationFlags, Reserved: ?*anyopaque, Namespaces: ?*?*IItemEnumerator) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsEngine.VTable, self.vtable).GetNamespaces(@ptrCast(*const ISettingsEngine, self), Flags, Reserved, Namespaces);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsEngine_GetNamespace(self: *const T, SettingsID: ?*ISettingsIdentity, Access: WcmNamespaceAccess, Reserved: ?*anyopaque, NamespaceItem: ?*?*ISettingsNamespace) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsEngine.VTable, self.vtable).GetNamespace(@ptrCast(*const ISettingsEngine, self), SettingsID, Access, Reserved, NamespaceItem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsEngine_GetErrorDescription(self: *const T, HResult: i32, Message: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsEngine.VTable, self.vtable).GetErrorDescription(@ptrCast(*const ISettingsEngine, self), HResult, Message);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsEngine_CreateSettingsIdentity(self: *const T, SettingsID: ?*?*ISettingsIdentity) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsEngine.VTable, self.vtable).CreateSettingsIdentity(@ptrCast(*const ISettingsEngine, self), SettingsID);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsEngine_GetStoreStatus(self: *const T, Reserved: ?*anyopaque, Status: ?*WcmUserStatus) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsEngine.VTable, self.vtable).GetStoreStatus(@ptrCast(*const ISettingsEngine, self), Reserved, Status);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsEngine_LoadStore(self: *const T, Flags: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsEngine.VTable, self.vtable).LoadStore(@ptrCast(*const ISettingsEngine, self), Flags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsEngine_UnloadStore(self: *const T, Reserved: ?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsEngine.VTable, self.vtable).UnloadStore(@ptrCast(*const ISettingsEngine, self), Reserved);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsEngine_RegisterNamespace(self: *const T, SettingsID: ?*ISettingsIdentity, Stream: ?*IStream, PushSettings: BOOL, Results: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsEngine.VTable, self.vtable).RegisterNamespace(@ptrCast(*const ISettingsEngine, self), SettingsID, Stream, PushSettings, Results);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsEngine_UnregisterNamespace(self: *const T, SettingsID: ?*ISettingsIdentity, RemoveSettings: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsEngine.VTable, self.vtable).UnregisterNamespace(@ptrCast(*const ISettingsEngine, self), SettingsID, RemoveSettings);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsEngine_CreateTargetInfo(self: *const T, Target: ?*?*ITargetInfo) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsEngine.VTable, self.vtable).CreateTargetInfo(@ptrCast(*const ISettingsEngine, self), Target);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsEngine_GetTargetInfo(self: *const T, Target: ?*?*ITargetInfo) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsEngine.VTable, self.vtable).GetTargetInfo(@ptrCast(*const ISettingsEngine, self), Target);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsEngine_SetTargetInfo(self: *const T, Target: ?*ITargetInfo) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsEngine.VTable, self.vtable).SetTargetInfo(@ptrCast(*const ISettingsEngine, self), Target);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsEngine_CreateSettingsContext(self: *const T, Flags: u32, Reserved: ?*anyopaque, SettingsContext: ?*?*ISettingsContext) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsEngine.VTable, self.vtable).CreateSettingsContext(@ptrCast(*const ISettingsEngine, self), Flags, Reserved, SettingsContext);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsEngine_SetSettingsContext(self: *const T, SettingsContext: ?*ISettingsContext) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsEngine.VTable, self.vtable).SetSettingsContext(@ptrCast(*const ISettingsEngine, self), SettingsContext);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsEngine_ApplySettingsContext(self: *const T, SettingsContext: ?*ISettingsContext, pppwzIdentities: ?*?*?PWSTR, pcIdentities: ?*usize) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsEngine.VTable, self.vtable).ApplySettingsContext(@ptrCast(*const ISettingsEngine, self), SettingsContext, pppwzIdentities, pcIdentities);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsEngine_GetSettingsContext(self: *const T, SettingsContext: ?*?*ISettingsContext) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsEngine.VTable, self.vtable).GetSettingsContext(@ptrCast(*const ISettingsEngine, self), SettingsContext);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_ISettingsItem_Value = @import("../zig.zig").Guid.initString("9f7d7bbb-20b3-11da-81a5-0030f1642e3c");
pub const IID_ISettingsItem = &IID_ISettingsItem_Value;
pub const ISettingsItem = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetName: fn(
self: *const ISettingsItem,
Name: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetValue: fn(
self: *const ISettingsItem,
Value: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetValue: fn(
self: *const ISettingsItem,
Value: ?*const VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSettingType: fn(
self: *const ISettingsItem,
Type: ?*WcmSettingType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDataType: fn(
self: *const ISettingsItem,
Type: ?*WcmDataType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetValueRaw: fn(
self: *const ISettingsItem,
Data: [*]?*u8,
DataSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetValueRaw: fn(
self: *const ISettingsItem,
DataType: i32,
Data: [*:0]const u8,
DataSize: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HasChild: fn(
self: *const ISettingsItem,
ItemHasChild: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Children: fn(
self: *const ISettingsItem,
Children: ?*?*IItemEnumerator,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetChild: fn(
self: *const ISettingsItem,
Name: ?[*:0]const u16,
Child: ?*?*ISettingsItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSettingByPath: fn(
self: *const ISettingsItem,
Path: ?[*:0]const u16,
Setting: ?*?*ISettingsItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateSettingByPath: fn(
self: *const ISettingsItem,
Path: ?[*:0]const u16,
Setting: ?*?*ISettingsItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveSettingByPath: fn(
self: *const ISettingsItem,
Path: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetListKeyInformation: fn(
self: *const ISettingsItem,
KeyName: ?*?BSTR,
DataType: ?*WcmDataType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateListElement: fn(
self: *const ISettingsItem,
KeyData: ?*const VARIANT,
Child: ?*?*ISettingsItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveListElement: fn(
self: *const ISettingsItem,
ElementName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Attributes: fn(
self: *const ISettingsItem,
Attributes: ?*?*IItemEnumerator,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAttribute: fn(
self: *const ISettingsItem,
Name: ?[*:0]const u16,
Value: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPath: fn(
self: *const ISettingsItem,
Path: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetRestrictionFacets: fn(
self: *const ISettingsItem,
RestrictionFacets: ?*WcmRestrictionFacets,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetRestriction: fn(
self: *const ISettingsItem,
RestrictionFacet: WcmRestrictionFacets,
FacetData: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetKeyValue: fn(
self: *const ISettingsItem,
Value: ?*VARIANT,
) 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 ISettingsItem_GetName(self: *const T, Name: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsItem.VTable, self.vtable).GetName(@ptrCast(*const ISettingsItem, self), Name);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsItem_GetValue(self: *const T, Value: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsItem.VTable, self.vtable).GetValue(@ptrCast(*const ISettingsItem, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsItem_SetValue(self: *const T, Value: ?*const VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsItem.VTable, self.vtable).SetValue(@ptrCast(*const ISettingsItem, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsItem_GetSettingType(self: *const T, Type: ?*WcmSettingType) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsItem.VTable, self.vtable).GetSettingType(@ptrCast(*const ISettingsItem, self), Type);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsItem_GetDataType(self: *const T, Type: ?*WcmDataType) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsItem.VTable, self.vtable).GetDataType(@ptrCast(*const ISettingsItem, self), Type);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsItem_GetValueRaw(self: *const T, Data: [*]?*u8, DataSize: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsItem.VTable, self.vtable).GetValueRaw(@ptrCast(*const ISettingsItem, self), Data, DataSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsItem_SetValueRaw(self: *const T, DataType: i32, Data: [*:0]const u8, DataSize: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsItem.VTable, self.vtable).SetValueRaw(@ptrCast(*const ISettingsItem, self), DataType, Data, DataSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsItem_HasChild(self: *const T, ItemHasChild: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsItem.VTable, self.vtable).HasChild(@ptrCast(*const ISettingsItem, self), ItemHasChild);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsItem_Children(self: *const T, Children: ?*?*IItemEnumerator) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsItem.VTable, self.vtable).Children(@ptrCast(*const ISettingsItem, self), Children);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsItem_GetChild(self: *const T, Name: ?[*:0]const u16, Child: ?*?*ISettingsItem) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsItem.VTable, self.vtable).GetChild(@ptrCast(*const ISettingsItem, self), Name, Child);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsItem_GetSettingByPath(self: *const T, Path: ?[*:0]const u16, Setting: ?*?*ISettingsItem) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsItem.VTable, self.vtable).GetSettingByPath(@ptrCast(*const ISettingsItem, self), Path, Setting);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsItem_CreateSettingByPath(self: *const T, Path: ?[*:0]const u16, Setting: ?*?*ISettingsItem) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsItem.VTable, self.vtable).CreateSettingByPath(@ptrCast(*const ISettingsItem, self), Path, Setting);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsItem_RemoveSettingByPath(self: *const T, Path: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsItem.VTable, self.vtable).RemoveSettingByPath(@ptrCast(*const ISettingsItem, self), Path);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsItem_GetListKeyInformation(self: *const T, KeyName: ?*?BSTR, DataType: ?*WcmDataType) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsItem.VTable, self.vtable).GetListKeyInformation(@ptrCast(*const ISettingsItem, self), KeyName, DataType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsItem_CreateListElement(self: *const T, KeyData: ?*const VARIANT, Child: ?*?*ISettingsItem) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsItem.VTable, self.vtable).CreateListElement(@ptrCast(*const ISettingsItem, self), KeyData, Child);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsItem_RemoveListElement(self: *const T, ElementName: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsItem.VTable, self.vtable).RemoveListElement(@ptrCast(*const ISettingsItem, self), ElementName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsItem_Attributes(self: *const T, Attributes: ?*?*IItemEnumerator) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsItem.VTable, self.vtable).Attributes(@ptrCast(*const ISettingsItem, self), Attributes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsItem_GetAttribute(self: *const T, Name: ?[*:0]const u16, Value: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsItem.VTable, self.vtable).GetAttribute(@ptrCast(*const ISettingsItem, self), Name, Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsItem_GetPath(self: *const T, Path: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsItem.VTable, self.vtable).GetPath(@ptrCast(*const ISettingsItem, self), Path);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsItem_GetRestrictionFacets(self: *const T, RestrictionFacets: ?*WcmRestrictionFacets) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsItem.VTable, self.vtable).GetRestrictionFacets(@ptrCast(*const ISettingsItem, self), RestrictionFacets);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsItem_GetRestriction(self: *const T, RestrictionFacet: WcmRestrictionFacets, FacetData: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsItem.VTable, self.vtable).GetRestriction(@ptrCast(*const ISettingsItem, self), RestrictionFacet, FacetData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsItem_GetKeyValue(self: *const T, Value: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsItem.VTable, self.vtable).GetKeyValue(@ptrCast(*const ISettingsItem, self), Value);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_ISettingsNamespace_Value = @import("../zig.zig").Guid.initString("9f7d7bba-20b3-11da-81a5-0030f1642e3c");
pub const IID_ISettingsNamespace = &IID_ISettingsNamespace_Value;
pub const ISettingsNamespace = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetIdentity: fn(
self: *const ISettingsNamespace,
SettingsID: ?*?*ISettingsIdentity,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Settings: fn(
self: *const ISettingsNamespace,
Settings: ?*?*IItemEnumerator,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Save: fn(
self: *const ISettingsNamespace,
PushSettings: BOOL,
Result: ?*?*ISettingsResult,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSettingByPath: fn(
self: *const ISettingsNamespace,
Path: ?[*:0]const u16,
Setting: ?*?*ISettingsItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateSettingByPath: fn(
self: *const ISettingsNamespace,
Path: ?[*:0]const u16,
Setting: ?*?*ISettingsItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveSettingByPath: fn(
self: *const ISettingsNamespace,
Path: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAttribute: fn(
self: *const ISettingsNamespace,
Name: ?[*:0]const u16,
Value: ?*VARIANT,
) 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 ISettingsNamespace_GetIdentity(self: *const T, SettingsID: ?*?*ISettingsIdentity) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsNamespace.VTable, self.vtable).GetIdentity(@ptrCast(*const ISettingsNamespace, self), SettingsID);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsNamespace_Settings(self: *const T, Settings: ?*?*IItemEnumerator) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsNamespace.VTable, self.vtable).Settings(@ptrCast(*const ISettingsNamespace, self), Settings);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsNamespace_Save(self: *const T, PushSettings: BOOL, Result: ?*?*ISettingsResult) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsNamespace.VTable, self.vtable).Save(@ptrCast(*const ISettingsNamespace, self), PushSettings, Result);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsNamespace_GetSettingByPath(self: *const T, Path: ?[*:0]const u16, Setting: ?*?*ISettingsItem) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsNamespace.VTable, self.vtable).GetSettingByPath(@ptrCast(*const ISettingsNamespace, self), Path, Setting);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsNamespace_CreateSettingByPath(self: *const T, Path: ?[*:0]const u16, Setting: ?*?*ISettingsItem) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsNamespace.VTable, self.vtable).CreateSettingByPath(@ptrCast(*const ISettingsNamespace, self), Path, Setting);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsNamespace_RemoveSettingByPath(self: *const T, Path: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsNamespace.VTable, self.vtable).RemoveSettingByPath(@ptrCast(*const ISettingsNamespace, self), Path);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsNamespace_GetAttribute(self: *const T, Name: ?[*:0]const u16, Value: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsNamespace.VTable, self.vtable).GetAttribute(@ptrCast(*const ISettingsNamespace, self), Name, Value);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_ISettingsResult_Value = @import("../zig.zig").Guid.initString("9f7d7bbc-20b3-11da-81a5-0030f1642e3c");
pub const IID_ISettingsResult = &IID_ISettingsResult_Value;
pub const ISettingsResult = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetDescription: fn(
self: *const ISettingsResult,
description: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetErrorCode: fn(
self: *const ISettingsResult,
hrOut: ?*HRESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetContextDescription: fn(
self: *const ISettingsResult,
description: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLine: fn(
self: *const ISettingsResult,
dwLine: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetColumn: fn(
self: *const ISettingsResult,
dwColumn: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSource: fn(
self: *const ISettingsResult,
file: ?*?BSTR,
) 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 ISettingsResult_GetDescription(self: *const T, description: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsResult.VTable, self.vtable).GetDescription(@ptrCast(*const ISettingsResult, self), description);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsResult_GetErrorCode(self: *const T, hrOut: ?*HRESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsResult.VTable, self.vtable).GetErrorCode(@ptrCast(*const ISettingsResult, self), hrOut);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsResult_GetContextDescription(self: *const T, description: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsResult.VTable, self.vtable).GetContextDescription(@ptrCast(*const ISettingsResult, self), description);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsResult_GetLine(self: *const T, dwLine: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsResult.VTable, self.vtable).GetLine(@ptrCast(*const ISettingsResult, self), dwLine);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsResult_GetColumn(self: *const T, dwColumn: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsResult.VTable, self.vtable).GetColumn(@ptrCast(*const ISettingsResult, self), dwColumn);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsResult_GetSource(self: *const T, file: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsResult.VTable, self.vtable).GetSource(@ptrCast(*const ISettingsResult, self), file);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_ISettingsContext_Value = @import("../zig.zig").Guid.initString("9f7d7bbd-20b3-11da-81a5-0030f1642e3c");
pub const IID_ISettingsContext = &IID_ISettingsContext_Value;
pub const ISettingsContext = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Serialize: fn(
self: *const ISettingsContext,
pStream: ?*IStream,
pTarget: ?*ITargetInfo,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Deserialize: fn(
self: *const ISettingsContext,
pStream: ?*IStream,
pTarget: ?*ITargetInfo,
pppResults: [*]?*?*ISettingsResult,
pcResultCount: ?*usize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetUserData: fn(
self: *const ISettingsContext,
pUserData: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetUserData: fn(
self: *const ISettingsContext,
pUserData: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetNamespaces: fn(
self: *const ISettingsContext,
ppNamespaceIds: ?*?*IItemEnumerator,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStoredSettings: fn(
self: *const ISettingsContext,
pIdentity: ?*ISettingsIdentity,
ppAddedSettings: ?*?*IItemEnumerator,
ppModifiedSettings: ?*?*IItemEnumerator,
ppDeletedSettings: ?*?*IItemEnumerator,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RevertSetting: fn(
self: *const ISettingsContext,
pIdentity: ?*ISettingsIdentity,
pwzSetting: ?[*:0]const u16,
) 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 ISettingsContext_Serialize(self: *const T, pStream: ?*IStream, pTarget: ?*ITargetInfo) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsContext.VTable, self.vtable).Serialize(@ptrCast(*const ISettingsContext, self), pStream, pTarget);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsContext_Deserialize(self: *const T, pStream: ?*IStream, pTarget: ?*ITargetInfo, pppResults: [*]?*?*ISettingsResult, pcResultCount: ?*usize) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsContext.VTable, self.vtable).Deserialize(@ptrCast(*const ISettingsContext, self), pStream, pTarget, pppResults, pcResultCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsContext_SetUserData(self: *const T, pUserData: ?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsContext.VTable, self.vtable).SetUserData(@ptrCast(*const ISettingsContext, self), pUserData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsContext_GetUserData(self: *const T, pUserData: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsContext.VTable, self.vtable).GetUserData(@ptrCast(*const ISettingsContext, self), pUserData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsContext_GetNamespaces(self: *const T, ppNamespaceIds: ?*?*IItemEnumerator) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsContext.VTable, self.vtable).GetNamespaces(@ptrCast(*const ISettingsContext, self), ppNamespaceIds);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsContext_GetStoredSettings(self: *const T, pIdentity: ?*ISettingsIdentity, ppAddedSettings: ?*?*IItemEnumerator, ppModifiedSettings: ?*?*IItemEnumerator, ppDeletedSettings: ?*?*IItemEnumerator) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsContext.VTable, self.vtable).GetStoredSettings(@ptrCast(*const ISettingsContext, self), pIdentity, ppAddedSettings, ppModifiedSettings, ppDeletedSettings);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISettingsContext_RevertSetting(self: *const T, pIdentity: ?*ISettingsIdentity, pwzSetting: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const ISettingsContext.VTable, self.vtable).RevertSetting(@ptrCast(*const ISettingsContext, self), pIdentity, pwzSetting);
}
};}
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 (9)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const BOOL = @import("../foundation.zig").BOOL;
const BSTR = @import("../foundation.zig").BSTR;
const HINSTANCE = @import("../foundation.zig").HINSTANCE;
const HRESULT = @import("../foundation.zig").HRESULT;
const IStream = @import("../system/com.zig").IStream;
const IUnknown = @import("../system/com.zig").IUnknown;
const PWSTR = @import("../foundation.zig").PWSTR;
const VARIANT = @import("../system/com.zig").VARIANT;
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/system/settings_management_infrastructure.zig |
const std = @import("std");
const Builder = std.build.Builder;
const builtin = @import("builtin");
pub fn build(b: *Builder) void {
// Each tutorial stage, its source file, and description
const targets = [_]Target{
.{ .name = "hello_window", .src = "src/1_1_hello_window.zig", .description = "Hello GLFW Window" },
.{ .name = "hello_triangle", .src = "src/1_2_hello_triangle.zig", .description = "Hello OpenGL Triangle" },
.{ .name = "shaders", .src = "src/1_3_shaders.zig", .description = "OpenGL Shaders" },
.{ .name = "textures", .src = "src/1_4_textures.zig", .description = "OpenGL Textures" },
.{ .name = "transformations", .src = "src/1_5_transformations.zig", .description = "Vector Transformations" },
.{ .name = "coordinate_systems", .src = "src/1_6_coordinate_systems.zig", .description = "Coordinate Systems" },
.{ .name = "camera", .src = "src/1_7_camera.zig", .description = "Camera" },
.{ .name = "colors", .src = "src/2_1_colors.zig", .description = "Colors" },
.{ .name = "basic_lighting", .src = "src/2_2_basic_lighting.zig", .description = "Basic Lighting" },
.{ .name = "materials", .src = "src/2_3_materials.zig", .description = "Materials" },
.{ .name = "lighting_maps", .src = "src/2_4_lighting_maps.zig", .description = "Lighting Maps" },
.{ .name = "light_casters", .src = "src/2_5_light_casters.zig", .description = "Light Casters" },
.{ .name = "multiple_lights", .src = "src/2_6_multiple_lights.zig", .description = "Multiple Light Sources" },
.{ .name = "ibl_specular", .src = "src/6_2_2_ibl_specular.zig", .description = "Image Based Lighting with Specular" },
};
// Build all targets
for (targets) |target| {
target.build(b);
}
}
const Target = struct {
name: []const u8,
src: []const u8,
description: []const u8,
pub fn build(self: Target, b: *Builder) void {
var exe = b.addExecutable(self.name, self.src);
exe.setBuildMode(b.standardReleaseOptions());
// OS stuff
exe.linkLibC();
switch (builtin.os.tag) {
.windows => {
exe.linkSystemLibrary("kernel32");
exe.linkSystemLibrary("user32");
exe.linkSystemLibrary("shell32");
exe.linkSystemLibrary("gdi32");
exe.addIncludeDir("D:\\dev\\vcpkg\\installed\\x64-windows-static\\include");
exe.addLibPath("D:\\dev\\vcpkg\\installed\\x64-windows-static\\lib");
},
else => {},
}
// GLFW
exe.linkSystemLibrary("glfw3");
// STB
exe.addCSourceFile("deps/stb_image/src/stb_image_impl.c", &[_][]const u8{"-std=c99"});
exe.addIncludeDir("deps/stb_image/include");
// GLAD
exe.addCSourceFile("deps/glad/src/glad.c", &[_][]const u8{"-std=c99"});
exe.addIncludeDir("deps/glad/include");
b.default_step.dependOn(&exe.step);
b.step(self.name, self.description).dependOn(&exe.run().step);
}
}; | build.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const Entry = @import("entry.zig").Entry;
const Options = @import("Options.zig");
const PathDepthPair = struct {
path: []const u8,
depth: usize,
};
pub const BreadthFirstWalker = struct {
start_path: []const u8,
paths_to_scan: ArrayList(PathDepthPair),
allocator: Allocator,
max_depth: ?usize,
hidden: bool,
current_dir: std.fs.Dir,
current_iter: std.fs.Dir.Iterator,
current_path: []const u8,
current_depth: usize,
pub const Self = @This();
pub fn init(allocator: Allocator, path: []const u8, options: Options) !Self {
var top_dir = try std.fs.cwd().openDir(path, .{ .iterate = true });
return Self{
.start_path = path,
.paths_to_scan = ArrayList(PathDepthPair).init(allocator),
.allocator = allocator,
.max_depth = options.max_depth,
.hidden = options.include_hidden,
.current_dir = top_dir,
.current_iter = top_dir.iterate(),
.current_path = try allocator.dupe(u8, path),
.current_depth = 0,
};
}
pub fn next(self: *Self) !?Entry {
outer: while (true) {
if (try self.current_iter.next()) |entry| {
// Check if the entry is hidden
if (!self.hidden and entry.name[0] == '.') {
continue :outer;
}
const full_entry_path = try self.allocator.alloc(u8, self.current_path.len + entry.name.len + 1);
std.mem.copy(u8, full_entry_path, self.current_path);
full_entry_path[self.current_path.len] = std.fs.path.sep;
std.mem.copy(u8, full_entry_path[self.current_path.len + 1 ..], entry.name);
const relative_path = full_entry_path[self.start_path.len + 1 ..];
const name = full_entry_path[self.current_path.len + 1 ..];
// Remember this directory, we are going to traverse it later
blk: {
if (entry.kind == std.fs.Dir.Entry.Kind.Directory) {
if (self.max_depth) |max_depth| {
if (self.current_depth >= max_depth) {
break :blk;
}
}
try self.paths_to_scan.append(PathDepthPair{
.path = try self.allocator.dupe(u8, full_entry_path),
.depth = self.current_depth + 1,
});
}
}
return Entry{
.allocator = self.allocator,
.name = name,
.absolute_path = full_entry_path,
.relative_path = relative_path,
.kind = entry.kind,
};
} else {
// No entries left in the current dir
self.current_dir.close();
self.allocator.free(self.current_path);
if (self.paths_to_scan.items.len > 0) {
const pair = self.paths_to_scan.orderedRemove(0);
self.current_path = pair.path;
self.current_depth = pair.depth;
self.current_dir = try std.fs.cwd().openDir(self.current_path, .{ .iterate = true });
self.current_iter = self.current_dir.iterate();
continue :outer;
}
return null;
}
}
}
pub fn deinit(self: *Self) void {
self.paths_to_scan.deinit();
}
}; | src/breadth_first.zig |
const std = @import("std");
const ignore = @import("ignore.zig");
const warn = std.debug.warn;
const testing = std.testing;
const FileInfo = @import("path/file_info").FileInfo;
test "parse" {
const rules =
\\#ignore
\\#ignore
\\foo
\\bar/*
\\baz/bar/foo.txt
\\one/more
;
var a = std.debug.global_allocator;
var rule = try ignore.parseString(a, rules);
defer rule.deinit();
testing.expectEqual(rule.patterns.len, 4);
const expects = [_][]const u8{
"foo", "bar/*", "baz/bar/foo.txt", "one/more",
};
for (rule.patterns.toSlice()) |p, i| {
testing.expectEqualSlices(u8, p.raw, expects[i]);
}
}
const Fixture = struct {
pattern: []const u8,
name: []const u8,
expect: bool,
is_dir: bool,
const Self = @This();
fn init(
pattern: []const u8,
name: []const u8,
expect: bool,
is_dir: bool,
) Self {
return Self{
.pattern = pattern,
.name = name,
.expect = expect,
.is_dir = is_dir,
};
}
};
test "ignore" {
var a = std.debug.global_allocator;
const sample = [_]Fixture{
Fixture.init("helm.txt", "helm.txt", true, false),
Fixture.init("helm.*", "helm.txt", true, false),
Fixture.init("helm.*", "rudder.txt", false, false),
Fixture.init("*.txt", "tiller.txt", true, false),
Fixture.init("*.txt", "cargo/a.txt", true, false),
Fixture.init("cargo/*.txt", "cargo/a.txt", true, false),
Fixture.init("cargo/*.*", "cargo/a.txt", true, false),
Fixture.init("cargo/*.txt", "mast/a.txt", false, false),
Fixture.init("ru[c-e]?er.txt", "rudder.txt", true, false),
Fixture.init("templates/.?*", "templates/.dotfile", true, false),
// "." should never get ignored. https://github.com/kubernetes/helm/issues/1776
Fixture.init(".*", ".", false, false),
Fixture.init(".*", "./", false, false),
Fixture.init(".*", ".joonix", true, false),
Fixture.init(".*", "helm.txt", false, false),
Fixture.init(".*", "", false, false),
// Directory tests
Fixture.init("cargo/", "cargo", true, true),
Fixture.init("cargo/", "cargo/", true, true),
Fixture.init("cargo/", "mast/", false, true),
Fixture.init("helm.txt/", "helm.txt", false, false),
// Negation tests
Fixture.init("!helm.txt", "helm.txt", false, false),
Fixture.init("!helm.txt", "tiller.txt", true, false),
Fixture.init("!*.txt", "cargo", true, true),
Fixture.init("!cargo/", "mast/", true, true),
// Absolute path tests
Fixture.init("/a.txt", "a.txt", true, false),
Fixture.init("/a.txt", "cargo/a.txt", false, false),
Fixture.init("/cargo/a.txt", "cargo/a.txt", true, false),
};
for (sample) |ts| {
try testIngore(a, ts);
}
}
fn testIngore(a: *std.mem.Allocator, fx: Fixture) !void {
var rule = try ignore.parseString(a, fx.pattern);
defer rule.deinit();
const got = rule.ignore(fx.name, FileInfo{ .is_dir = fx.is_dir });
if (got != fx.expect) {
warn("{} -- expected {} got {}\n", fx, fx.expect, got);
}
} | src/ignore/ignore_test.zig |
//! Futex is a mechanism used to block (`wait`) and unblock (`wake`) threads using a 32bit memory address as hints.
//! Blocking a thread is acknowledged only if the 32bit memory address is equal to a given value.
//! This check helps avoid block/unblock deadlocks which occur if a `wake()` happens before a `wait()`.
//! Using Futex, other Thread synchronization primitives can be built which efficiently wait for cross-thread events or signals.
const std = @import("../std.zig");
const Futex = @This();
const target = std.Target.current;
const single_threaded = std.builtin.single_threaded;
const assert = std.debug.assert;
const testing = std.testing;
const Atomic = std.atomic.Atomic;
const spinLoopHint = std.atomic.spinLoopHint;
/// Checks if `ptr` still contains the value `expect` and, if so, blocks the caller until either:
/// - The value at `ptr` is no longer equal to `expect`.
/// - The caller is unblocked by a matching `wake()`.
/// - The caller is unblocked spuriously by an arbitrary internal signal.
///
/// If `timeout` is provided, and the caller is blocked for longer than `timeout` nanoseconds`, `error.TimedOut` is returned.
///
/// The checking of `ptr` and `expect`, along with blocking the caller, is done atomically
/// and totally ordered (sequentially consistent) with respect to other wait()/wake() calls on the same `ptr`.
pub fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{TimedOut}!void {
if (single_threaded) {
// check whether the caller should block
if (ptr.loadUnchecked() != expect) {
return;
}
// There are no other threads which could notify the caller on single_threaded.
// Therefor a wait() without a timeout would block indefinitely.
const timeout_ns = timeout orelse {
@panic("deadlock");
};
// Simulate blocking with the timeout knowing that:
// - no other thread can change the ptr value
// - no other thread could unblock us if we waiting on the ptr
std.time.sleep(timeout_ns);
return error.TimedOut;
}
// Avoid calling into the OS for no-op waits()
if (timeout) |timeout_ns| {
if (timeout_ns == 0) {
if (ptr.load(.SeqCst) != expect) return;
return error.TimedOut;
}
}
return OsFutex.wait(ptr, expect, timeout);
}
/// Unblocks at most `num_waiters` callers blocked in a `wait()` call on `ptr`.
/// `num_waiters` of 1 unblocks at most one `wait(ptr, ...)` and `maxInt(u32)` unblocks effectively all `wait(ptr, ...)`.
pub fn wake(ptr: *const Atomic(u32), num_waiters: u32) void {
if (single_threaded) return;
if (num_waiters == 0) return;
return OsFutex.wake(ptr, num_waiters);
}
const OsFutex = if (target.os.tag == .windows)
WindowsFutex
else if (target.os.tag == .linux)
LinuxFutex
else if (target.isDarwin())
DarwinFutex
else if (std.builtin.link_libc)
PosixFutex
else
UnsupportedFutex;
const UnsupportedFutex = struct {
fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{TimedOut}!void {
return unsupported(.{ ptr, expect, timeout });
}
fn wake(ptr: *const Atomic(u32), num_waiters: u32) void {
return unsupported(.{ ptr, num_waiters });
}
fn unsupported(unused: anytype) noreturn {
@compileLog("Unsupported operating system", target.os.tag);
_ = unused;
unreachable;
}
};
const WindowsFutex = struct {
const windows = std.os.windows;
fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{TimedOut}!void {
var timeout_value: windows.LARGE_INTEGER = undefined;
var timeout_ptr: ?*const windows.LARGE_INTEGER = null;
// NTDLL functions work with time in units of 100 nanoseconds.
// Positive values for timeouts are absolute time while negative is relative.
if (timeout) |timeout_ns| {
timeout_ptr = &timeout_value;
timeout_value = -@intCast(windows.LARGE_INTEGER, timeout_ns / 100);
}
switch (windows.ntdll.RtlWaitOnAddress(
@ptrCast(?*const c_void, ptr),
@ptrCast(?*const c_void, &expect),
@sizeOf(@TypeOf(expect)),
timeout_ptr,
)) {
.SUCCESS => {},
.TIMEOUT => return error.TimedOut,
else => unreachable,
}
}
fn wake(ptr: *const Atomic(u32), num_waiters: u32) void {
const address = @ptrCast(?*const c_void, ptr);
switch (num_waiters) {
1 => windows.ntdll.RtlWakeAddressSingle(address),
else => windows.ntdll.RtlWakeAddressAll(address),
}
}
};
const LinuxFutex = struct {
const linux = std.os.linux;
fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{TimedOut}!void {
var ts: std.os.timespec = undefined;
var ts_ptr: ?*std.os.timespec = null;
// Futex timespec timeout is already in relative time.
if (timeout) |timeout_ns| {
ts_ptr = &ts;
ts.tv_sec = @intCast(@TypeOf(ts.tv_sec), timeout_ns / std.time.ns_per_s);
ts.tv_nsec = @intCast(@TypeOf(ts.tv_nsec), timeout_ns % std.time.ns_per_s);
}
switch (linux.getErrno(linux.futex_wait(
@ptrCast(*const i32, ptr),
linux.FUTEX_PRIVATE_FLAG | linux.FUTEX_WAIT,
@bitCast(i32, expect),
ts_ptr,
))) {
0 => {}, // notified by `wake()`
std.os.EINTR => {}, // spurious wakeup
std.os.EAGAIN => {}, // ptr.* != expect
std.os.ETIMEDOUT => return error.TimedOut,
std.os.EINVAL => {}, // possibly timeout overflow
std.os.EFAULT => unreachable,
else => unreachable,
}
}
fn wake(ptr: *const Atomic(u32), num_waiters: u32) void {
switch (linux.getErrno(linux.futex_wake(
@ptrCast(*const i32, ptr),
linux.FUTEX_PRIVATE_FLAG | linux.FUTEX_WAKE,
std.math.cast(i32, num_waiters) catch std.math.maxInt(i32),
))) {
0 => {}, // successful wake up
std.os.EINVAL => {}, // invalid futex_wait() on ptr done elsewhere
std.os.EFAULT => {}, // pointer became invalid while doing the wake
else => unreachable,
}
}
};
const DarwinFutex = struct {
const darwin = std.os.darwin;
fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{TimedOut}!void {
// Darwin XNU 7195.192.168.3.11 introduced __ulock_wait2 and migrated code paths (notably pthread_cond_t) towards it:
// https://github.com/apple/darwin-xnu/commit/d4061fb0260b3ed486147341b72468f836ed6c8f#diff-08f993cc40af475663274687b7c326cc6c3031e0db3ac8de7b24624610616be6
//
// This XNU version appears to correspond to 11.0.1:
// https://kernelshaman.blogspot.com/2021/01/building-xnu-for-macos-big-sur-1101.html
//
// ulock_wait() uses 32-bit micro-second timeouts where 0 = INFINITE or no-timeout
// ulock_wait2() uses 64-bit nano-second timeouts (with the same convention)
var timeout_ns: u64 = 0;
if (timeout) |timeout_value| {
// This should be checked by the caller.
assert(timeout_value != 0);
timeout_ns = timeout_value;
}
const addr = @ptrCast(*const c_void, ptr);
const flags = darwin.UL_COMPARE_AND_WAIT | darwin.ULF_NO_ERRNO;
// If we're using `__ulock_wait` and `timeout` is too big to fit inside a `u32` count of
// micro-seconds (around 70min), we'll request a shorter timeout. This is fine (users
// should handle spurious wakeups), but we need to remember that we did so, so that
// we don't return `TimedOut` incorrectly. If that happens, we set this variable to
// true so that we we know to ignore the ETIMEDOUT result.
var timeout_overflowed = false;
const status = blk: {
if (target.os.version_range.semver.max.major >= 11) {
break :blk darwin.__ulock_wait2(flags, addr, expect, timeout_ns, 0);
} else {
const timeout_us = std.math.cast(u32, timeout_ns / std.time.ns_per_us) catch overflow: {
timeout_overflowed = true;
break :overflow std.math.maxInt(u32);
};
break :blk darwin.__ulock_wait(flags, addr, expect, timeout_us);
}
};
if (status >= 0) return;
switch (-status) {
darwin.EINTR => {},
// Address of the futex is paged out. This is unlikely, but possible in theory, and
// pthread/libdispatch on darwin bother to handle it. In this case we'll return
// without waiting, but the caller should retry anyway.
darwin.EFAULT => {},
darwin.ETIMEDOUT => if (!timeout_overflowed) return error.TimedOut,
else => unreachable,
}
}
fn wake(ptr: *const Atomic(u32), num_waiters: u32) void {
var flags: u32 = darwin.UL_COMPARE_AND_WAIT | darwin.ULF_NO_ERRNO;
if (num_waiters > 1) {
flags |= darwin.ULF_WAKE_ALL;
}
while (true) {
const addr = @ptrCast(*const c_void, ptr);
const status = darwin.__ulock_wake(flags, addr, 0);
if (status >= 0) return;
switch (-status) {
darwin.EINTR => continue, // spurious wake()
darwin.EFAULT => continue, // address of the lock was paged out
darwin.ENOENT => return, // nothing was woken up
darwin.EALREADY => unreachable, // only for ULF_WAKE_THREAD
else => unreachable,
}
}
}
};
const PosixFutex = struct {
fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{TimedOut}!void {
const address = @ptrToInt(ptr);
const bucket = Bucket.from(address);
var waiter: List.Node = undefined;
{
assert(std.c.pthread_mutex_lock(&bucket.mutex) == 0);
defer assert(std.c.pthread_mutex_unlock(&bucket.mutex) == 0);
if (ptr.load(.SeqCst) != expect) {
return;
}
waiter.data = .{ .address = address };
bucket.list.prepend(&waiter);
}
var timed_out = false;
waiter.data.wait(timeout) catch {
defer if (!timed_out) {
waiter.data.wait(null) catch unreachable;
};
assert(std.c.pthread_mutex_lock(&bucket.mutex) == 0);
defer assert(std.c.pthread_mutex_unlock(&bucket.mutex) == 0);
if (waiter.data.address == address) {
timed_out = true;
bucket.list.remove(&waiter);
}
};
waiter.data.deinit();
if (timed_out) {
return error.TimedOut;
}
}
fn wake(ptr: *const Atomic(u32), num_waiters: u32) void {
const address = @ptrToInt(ptr);
const bucket = Bucket.from(address);
var can_notify = num_waiters;
var notified = List{};
defer while (notified.popFirst()) |waiter| {
waiter.data.notify();
};
assert(std.c.pthread_mutex_lock(&bucket.mutex) == 0);
defer assert(std.c.pthread_mutex_unlock(&bucket.mutex) == 0);
var waiters = bucket.list.first;
while (waiters) |waiter| {
assert(waiter.data.address != null);
waiters = waiter.next;
if (waiter.data.address != address) continue;
if (can_notify == 0) break;
can_notify -= 1;
bucket.list.remove(waiter);
waiter.data.address = null;
notified.prepend(waiter);
}
}
const Bucket = struct {
mutex: std.c.pthread_mutex_t = .{},
list: List = .{},
var buckets = [_]Bucket{.{}} ** 64;
fn from(address: usize) *Bucket {
return &buckets[address % buckets.len];
}
};
const List = std.TailQueue(struct {
address: ?usize,
state: State = .empty,
cond: std.c.pthread_cond_t = .{},
mutex: std.c.pthread_mutex_t = .{},
const Self = @This();
const State = enum {
empty,
waiting,
notified,
};
fn deinit(self: *Self) void {
const rc = std.c.pthread_cond_destroy(&self.cond);
assert(rc == 0 or rc == std.os.EINVAL);
const rm = std.c.pthread_mutex_destroy(&self.mutex);
assert(rm == 0 or rm == std.os.EINVAL);
}
fn wait(self: *Self, timeout: ?u64) error{TimedOut}!void {
assert(std.c.pthread_mutex_lock(&self.mutex) == 0);
defer assert(std.c.pthread_mutex_unlock(&self.mutex) == 0);
switch (self.state) {
.empty => self.state = .waiting,
.waiting => unreachable,
.notified => return,
}
var ts: std.os.timespec = undefined;
var ts_ptr: ?*const std.os.timespec = null;
if (timeout) |timeout_ns| {
ts_ptr = &ts;
std.os.clock_gettime(std.os.CLOCK_REALTIME, &ts) catch unreachable;
ts.tv_sec += @intCast(@TypeOf(ts.tv_sec), timeout_ns / std.time.ns_per_s);
ts.tv_nsec += @intCast(@TypeOf(ts.tv_nsec), timeout_ns % std.time.ns_per_s);
if (ts.tv_nsec >= std.time.ns_per_s) {
ts.tv_sec += 1;
ts.tv_nsec -= std.time.ns_per_s;
}
}
while (true) {
switch (self.state) {
.empty => unreachable,
.waiting => {},
.notified => return,
}
const ts_ref = ts_ptr orelse {
assert(std.c.pthread_cond_wait(&self.cond, &self.mutex) == 0);
continue;
};
const rc = std.c.pthread_cond_timedwait(&self.cond, &self.mutex, ts_ref);
assert(rc == 0 or rc == std.os.ETIMEDOUT);
if (rc == std.os.ETIMEDOUT) {
self.state = .empty;
return error.TimedOut;
}
}
}
fn notify(self: *Self) void {
assert(std.c.pthread_mutex_lock(&self.mutex) == 0);
defer assert(std.c.pthread_mutex_unlock(&self.mutex) == 0);
switch (self.state) {
.empty => self.state = .notified,
.waiting => {
self.state = .notified;
assert(std.c.pthread_cond_signal(&self.cond) == 0);
},
.notified => unreachable,
}
}
});
};
test "Futex - wait/wake" {
var value = Atomic(u32).init(0);
Futex.wait(&value, 1, null) catch unreachable;
const wait_noop_result = Futex.wait(&value, 0, 0);
try testing.expectError(error.TimedOut, wait_noop_result);
const wait_longer_result = Futex.wait(&value, 0, std.time.ns_per_ms);
try testing.expectError(error.TimedOut, wait_longer_result);
Futex.wake(&value, 0);
Futex.wake(&value, 1);
Futex.wake(&value, std.math.maxInt(u32));
}
test "Futex - Signal" {
if (single_threaded) {
return error.SkipZigTest;
}
const Paddle = struct {
value: Atomic(u32) = Atomic(u32).init(0),
current: u32 = 0,
fn run(self: *@This(), hit_to: *@This()) !void {
var iterations: usize = 4;
while (iterations > 0) : (iterations -= 1) {
var value: u32 = undefined;
while (true) {
value = self.value.load(.Acquire);
if (value != self.current) break;
Futex.wait(&self.value, self.current, null) catch unreachable;
}
try testing.expectEqual(value, self.current + 1);
self.current = value;
_ = hit_to.value.fetchAdd(1, .Release);
Futex.wake(&hit_to.value, 1);
}
}
};
var ping = Paddle{};
var pong = Paddle{};
const t1 = try std.Thread.spawn(.{}, Paddle.run, .{ &ping, &pong });
defer t1.join();
const t2 = try std.Thread.spawn(.{}, Paddle.run, .{ &pong, &ping });
defer t2.join();
_ = ping.value.fetchAdd(1, .Release);
Futex.wake(&ping.value, 1);
}
test "Futex - Broadcast" {
if (single_threaded) {
return error.SkipZigTest;
}
const Context = struct {
threads: [4]std.Thread = undefined,
broadcast: Atomic(u32) = Atomic(u32).init(0),
notified: Atomic(usize) = Atomic(usize).init(0),
const BROADCAST_EMPTY = 0;
const BROADCAST_SENT = 1;
const BROADCAST_RECEIVED = 2;
fn runSender(self: *@This()) !void {
self.broadcast.store(BROADCAST_SENT, .Monotonic);
Futex.wake(&self.broadcast, @intCast(u32, self.threads.len));
while (true) {
const broadcast = self.broadcast.load(.Acquire);
if (broadcast == BROADCAST_RECEIVED) break;
try testing.expectEqual(broadcast, BROADCAST_SENT);
Futex.wait(&self.broadcast, broadcast, null) catch unreachable;
}
}
fn runReceiver(self: *@This()) void {
while (true) {
const broadcast = self.broadcast.load(.Acquire);
if (broadcast == BROADCAST_SENT) break;
assert(broadcast == BROADCAST_EMPTY);
Futex.wait(&self.broadcast, broadcast, null) catch unreachable;
}
const notified = self.notified.fetchAdd(1, .Monotonic);
if (notified + 1 == self.threads.len) {
self.broadcast.store(BROADCAST_RECEIVED, .Release);
Futex.wake(&self.broadcast, 1);
}
}
};
var ctx = Context{};
for (ctx.threads) |*thread|
thread.* = try std.Thread.spawn(.{}, Context.runReceiver, .{&ctx});
defer for (ctx.threads) |thread|
thread.join();
// Try to wait for the threads to start before running runSender().
// NOTE: not actually needed for correctness.
std.time.sleep(16 * std.time.ns_per_ms);
try ctx.runSender();
const notified = ctx.notified.load(.Monotonic);
try testing.expectEqual(notified, ctx.threads.len);
}
test "Futex - Chain" {
if (single_threaded) {
return error.SkipZigTest;
}
const Signal = struct {
value: Atomic(u32) = Atomic(u32).init(0),
fn wait(self: *@This()) void {
while (true) {
const value = self.value.load(.Acquire);
if (value == 1) break;
assert(value == 0);
Futex.wait(&self.value, 0, null) catch unreachable;
}
}
fn notify(self: *@This()) void {
assert(self.value.load(.Unordered) == 0);
self.value.store(1, .Release);
Futex.wake(&self.value, 1);
}
};
const Context = struct {
completed: Signal = .{},
threads: [4]struct {
thread: std.Thread,
signal: Signal,
} = undefined,
fn run(self: *@This(), index: usize) void {
const this_signal = &self.threads[index].signal;
var next_signal = &self.completed;
if (index + 1 < self.threads.len) {
next_signal = &self.threads[index + 1].signal;
}
this_signal.wait();
next_signal.notify();
}
};
var ctx = Context{};
for (ctx.threads) |*entry, index| {
entry.signal = .{};
entry.thread = try std.Thread.spawn(.{}, Context.run, .{ &ctx, index });
}
ctx.threads[0].signal.notify();
ctx.completed.wait();
for (ctx.threads) |entry| {
entry.thread.join();
}
} | lib/std/Thread/Futex.zig |
const std = @import("std");
const builtin = std.builtin;
const arch = std.Target.current.cpu.arch;
const linkage: builtin.GlobalLinkage = if (builtin.is_test) .Internal else .Weak;
// This parameter is true iff the target architecture supports the bare minimum
// to implement the atomic load/store intrinsics.
// Some architectures support atomic load/stores but no CAS, but we ignore this
// detail to keep the export logic clean and because we need some kind of CAS to
// implement the spinlocks.
const supports_atomic_ops = switch (arch) {
.msp430, .avr => false,
.arm, .armeb, .thumb, .thumbeb =>
// The ARM v6m ISA has no ldrex/strex and so it's impossible to do CAS
// operations (unless we're targeting Linux, the kernel provides a way to
// perform CAS operations).
// XXX: The Linux code path is not implemented yet.
!std.Target.arm.featureSetHas(std.Target.current.cpu.features, .has_v6m),
else => true,
};
// The size (in bytes) of the biggest object that the architecture can
// load/store atomically.
// Objects bigger than this threshold require the use of a lock.
const largest_atomic_size = switch (arch) {
// XXX: On x86/x86_64 we could check the presence of cmpxchg8b/cmpxchg16b
// and set this parameter accordingly.
else => @sizeOf(usize),
};
const cache_line_size = 64;
const SpinlockTable = struct {
// Allocate ~4096 bytes of memory for the spinlock table
const max_spinlocks = 64;
const Spinlock = struct {
// Prevent false sharing by providing enough padding between two
// consecutive spinlock elements
v: enum(usize) { Unlocked = 0, Locked } align(cache_line_size) = .Unlocked,
fn acquire(self: *@This()) void {
while (true) {
switch (@atomicRmw(@TypeOf(self.v), &self.v, .Xchg, .Locked, .Acquire)) {
.Unlocked => break,
.Locked => {},
}
}
}
fn release(self: *@This()) void {
@atomicStore(@TypeOf(self.v), &self.v, .Unlocked, .Release);
}
};
list: [max_spinlocks]Spinlock = [_]Spinlock{.{}} ** max_spinlocks,
// The spinlock table behaves as a really simple hash table, mapping
// addresses to spinlocks. The mapping is not unique but that's only a
// performance problem as the lock will be contended by more than a pair of
// threads.
fn get(self: *@This(), address: usize) *Spinlock {
var sl = &self.list[(address >> 3) % max_spinlocks];
sl.acquire();
return sl;
}
};
var spinlocks: SpinlockTable = SpinlockTable{};
// The following builtins do not respect the specified memory model and instead
// uses seq_cst, the strongest one, for simplicity sake.
// Generic version of GCC atomic builtin functions.
// Those work on any object no matter the pointer alignment nor its size.
fn __atomic_load(size: u32, src: [*]u8, dest: [*]u8, model: i32) callconv(.C) void {
var sl = spinlocks.get(@ptrToInt(src));
defer sl.release();
@memcpy(dest, src, size);
}
fn __atomic_store(size: u32, dest: [*]u8, src: [*]u8, model: i32) callconv(.C) void {
var sl = spinlocks.get(@ptrToInt(dest));
defer sl.release();
@memcpy(dest, src, size);
}
fn __atomic_exchange(size: u32, ptr: [*]u8, val: [*]u8, old: [*]u8, model: i32) callconv(.C) void {
var sl = spinlocks.get(@ptrToInt(ptr));
defer sl.release();
@memcpy(old, ptr, size);
@memcpy(ptr, val, size);
}
fn __atomic_compare_exchange(
size: u32,
ptr: [*]u8,
expected: [*]u8,
desired: [*]u8,
success: i32,
failure: i32,
) callconv(.C) i32 {
var sl = spinlocks.get(@ptrToInt(ptr));
defer sl.release();
for (ptr[0..size]) |b, i| {
if (expected[i] != b) break;
} else {
// The two objects, ptr and expected, are equal
@memcpy(ptr, desired, size);
return 1;
}
@memcpy(expected, ptr, size);
return 0;
}
comptime {
if (supports_atomic_ops) {
@export(__atomic_load, .{ .name = "__atomic_load", .linkage = linkage });
@export(__atomic_store, .{ .name = "__atomic_store", .linkage = linkage });
@export(__atomic_exchange, .{ .name = "__atomic_exchange", .linkage = linkage });
@export(__atomic_compare_exchange, .{ .name = "__atomic_compare_exchange", .linkage = linkage });
}
}
// Specialized versions of the GCC atomic builtin functions.
// LLVM emits those iff the object size is known and the pointers are correctly
// aligned.
fn atomicLoadFn(comptime T: type) fn (*T, i32) callconv(.C) T {
return struct {
fn atomic_load_N(src: *T, model: i32) callconv(.C) T {
if (@sizeOf(T) > largest_atomic_size) {
var sl = spinlocks.get(@ptrToInt(src));
defer sl.release();
return src.*;
} else {
return @atomicLoad(T, src, .SeqCst);
}
}
}.atomic_load_N;
}
comptime {
if (supports_atomic_ops) {
const atomicLoad_u8 = atomicLoadFn(u8);
const atomicLoad_u16 = atomicLoadFn(u16);
const atomicLoad_u32 = atomicLoadFn(u32);
const atomicLoad_u64 = atomicLoadFn(u64);
@export(atomicLoad_u8, .{ .name = "__atomic_load_1", .linkage = linkage });
@export(atomicLoad_u16, .{ .name = "__atomic_load_2", .linkage = linkage });
@export(atomicLoad_u32, .{ .name = "__atomic_load_4", .linkage = linkage });
@export(atomicLoad_u64, .{ .name = "__atomic_load_8", .linkage = linkage });
}
}
fn atomicStoreFn(comptime T: type) fn (*T, T, i32) callconv(.C) void {
return struct {
fn atomic_store_N(dst: *T, value: T, model: i32) callconv(.C) void {
if (@sizeOf(T) > largest_atomic_size) {
var sl = spinlocks.get(@ptrToInt(dst));
defer sl.release();
dst.* = value;
} else {
@atomicStore(T, dst, value, .SeqCst);
}
}
}.atomic_store_N;
}
comptime {
if (supports_atomic_ops) {
const atomicStore_u8 = atomicStoreFn(u8);
const atomicStore_u16 = atomicStoreFn(u16);
const atomicStore_u32 = atomicStoreFn(u32);
const atomicStore_u64 = atomicStoreFn(u64);
@export(atomicStore_u8, .{ .name = "__atomic_store_1", .linkage = linkage });
@export(atomicStore_u16, .{ .name = "__atomic_store_2", .linkage = linkage });
@export(atomicStore_u32, .{ .name = "__atomic_store_4", .linkage = linkage });
@export(atomicStore_u64, .{ .name = "__atomic_store_8", .linkage = linkage });
}
}
fn atomicExchangeFn(comptime T: type) fn (*T, T, i32) callconv(.C) T {
return struct {
fn atomic_exchange_N(ptr: *T, val: T, model: i32) callconv(.C) T {
if (@sizeOf(T) > largest_atomic_size) {
var sl = spinlocks.get(@ptrToInt(ptr));
defer sl.release();
const value = ptr.*;
ptr.* = val;
return value;
} else {
return @atomicRmw(T, ptr, .Xchg, val, .SeqCst);
}
}
}.atomic_exchange_N;
}
comptime {
if (supports_atomic_ops) {
const atomicExchange_u8 = atomicExchangeFn(u8);
const atomicExchange_u16 = atomicExchangeFn(u16);
const atomicExchange_u32 = atomicExchangeFn(u32);
const atomicExchange_u64 = atomicExchangeFn(u64);
@export(atomicExchange_u8, .{ .name = "__atomic_exchange_1", .linkage = linkage });
@export(atomicExchange_u16, .{ .name = "__atomic_exchange_2", .linkage = linkage });
@export(atomicExchange_u32, .{ .name = "__atomic_exchange_4", .linkage = linkage });
@export(atomicExchange_u64, .{ .name = "__atomic_exchange_8", .linkage = linkage });
}
}
fn atomicCompareExchangeFn(comptime T: type) fn (*T, *T, T, i32, i32) callconv(.C) i32 {
return struct {
fn atomic_compare_exchange_N(ptr: *T, expected: *T, desired: T, success: i32, failure: i32) callconv(.C) i32 {
if (@sizeOf(T) > largest_atomic_size) {
var sl = spinlocks.get(@ptrToInt(ptr));
defer sl.release();
const value = ptr.*;
if (value == expected.*) {
ptr.* = desired;
return 1;
}
expected.* = value;
return 0;
} else {
if (@cmpxchgStrong(T, ptr, expected.*, desired, .SeqCst, .SeqCst)) |old_value| {
expected.* = old_value;
return 0;
}
return 1;
}
}
}.atomic_compare_exchange_N;
}
comptime {
if (supports_atomic_ops) {
const atomicCompareExchange_u8 = atomicCompareExchangeFn(u8);
const atomicCompareExchange_u16 = atomicCompareExchangeFn(u16);
const atomicCompareExchange_u32 = atomicCompareExchangeFn(u32);
const atomicCompareExchange_u64 = atomicCompareExchangeFn(u64);
@export(atomicCompareExchange_u8, .{ .name = "__atomic_compare_exchange_1", .linkage = linkage });
@export(atomicCompareExchange_u16, .{ .name = "__atomic_compare_exchange_2", .linkage = linkage });
@export(atomicCompareExchange_u32, .{ .name = "__atomic_compare_exchange_4", .linkage = linkage });
@export(atomicCompareExchange_u64, .{ .name = "__atomic_compare_exchange_8", .linkage = linkage });
}
}
fn fetchFn(comptime T: type, comptime op: builtin.AtomicRmwOp) fn (*T, T, i32) callconv(.C) T {
return struct {
pub fn fetch_op_N(ptr: *T, val: T, model: i32) callconv(.C) T {
if (@sizeOf(T) > largest_atomic_size) {
var sl = spinlocks.get(@ptrToInt(ptr));
defer sl.release();
const value = ptr.*;
ptr.* = switch (op) {
.Add => value +% val,
.Sub => value -% val,
.And => value & val,
.Nand => ~(value & val),
.Or => value | val,
.Xor => value ^ val,
else => @compileError("unsupported atomic op"),
};
return value;
}
return @atomicRmw(T, ptr, op, val, .SeqCst);
}
}.fetch_op_N;
}
comptime {
if (supports_atomic_ops) {
const fetch_add_u8 = fetchFn(u8, .Add);
const fetch_add_u16 = fetchFn(u16, .Add);
const fetch_add_u32 = fetchFn(u32, .Add);
const fetch_add_u64 = fetchFn(u64, .Add);
@export(fetch_add_u8, .{ .name = "__atomic_fetch_add_1", .linkage = linkage });
@export(fetch_add_u16, .{ .name = "__atomic_fetch_add_2", .linkage = linkage });
@export(fetch_add_u32, .{ .name = "__atomic_fetch_add_4", .linkage = linkage });
@export(fetch_add_u64, .{ .name = "__atomic_fetch_add_8", .linkage = linkage });
const fetch_sub_u8 = fetchFn(u8, .Sub);
const fetch_sub_u16 = fetchFn(u16, .Sub);
const fetch_sub_u32 = fetchFn(u32, .Sub);
const fetch_sub_u64 = fetchFn(u64, .Sub);
@export(fetch_sub_u8, .{ .name = "__atomic_fetch_sub_1", .linkage = linkage });
@export(fetch_sub_u16, .{ .name = "__atomic_fetch_sub_2", .linkage = linkage });
@export(fetch_sub_u32, .{ .name = "__atomic_fetch_sub_4", .linkage = linkage });
@export(fetch_sub_u64, .{ .name = "__atomic_fetch_sub_8", .linkage = linkage });
const fetch_and_u8 = fetchFn(u8, .And);
const fetch_and_u16 = fetchFn(u16, .And);
const fetch_and_u32 = fetchFn(u32, .And);
const fetch_and_u64 = fetchFn(u64, .And);
@export(fetch_and_u8, .{ .name = "__atomic_fetch_and_1", .linkage = linkage });
@export(fetch_and_u16, .{ .name = "__atomic_fetch_and_2", .linkage = linkage });
@export(fetch_and_u32, .{ .name = "__atomic_fetch_and_4", .linkage = linkage });
@export(fetch_and_u64, .{ .name = "__atomic_fetch_and_8", .linkage = linkage });
const fetch_or_u8 = fetchFn(u8, .Or);
const fetch_or_u16 = fetchFn(u16, .Or);
const fetch_or_u32 = fetchFn(u32, .Or);
const fetch_or_u64 = fetchFn(u64, .Or);
@export(fetch_or_u8, .{ .name = "__atomic_fetch_or_1", .linkage = linkage });
@export(fetch_or_u16, .{ .name = "__atomic_fetch_or_2", .linkage = linkage });
@export(fetch_or_u32, .{ .name = "__atomic_fetch_or_4", .linkage = linkage });
@export(fetch_or_u64, .{ .name = "__atomic_fetch_or_8", .linkage = linkage });
const fetch_xor_u8 = fetchFn(u8, .Xor);
const fetch_xor_u16 = fetchFn(u16, .Xor);
const fetch_xor_u32 = fetchFn(u32, .Xor);
const fetch_xor_u64 = fetchFn(u64, .Xor);
@export(fetch_xor_u8, .{ .name = "__atomic_fetch_xor_1", .linkage = linkage });
@export(fetch_xor_u16, .{ .name = "__atomic_fetch_xor_2", .linkage = linkage });
@export(fetch_xor_u32, .{ .name = "__atomic_fetch_xor_4", .linkage = linkage });
@export(fetch_xor_u64, .{ .name = "__atomic_fetch_xor_8", .linkage = linkage });
const fetch_nand_u8 = fetchFn(u8, .Nand);
const fetch_nand_u16 = fetchFn(u16, .Nand);
const fetch_nand_u32 = fetchFn(u32, .Nand);
const fetch_nand_u64 = fetchFn(u64, .Nand);
@export(fetch_nand_u8, .{ .name = "__atomic_fetch_nand_1", .linkage = linkage });
@export(fetch_nand_u16, .{ .name = "__atomic_fetch_nand_2", .linkage = linkage });
@export(fetch_nand_u32, .{ .name = "__atomic_fetch_nand_4", .linkage = linkage });
@export(fetch_nand_u64, .{ .name = "__atomic_fetch_nand_8", .linkage = linkage });
}
} | lib/std/special/compiler_rt/atomics.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const system_bus_address = "unix:path=/var/run/dbus/system_bus_socket";
pub const Connection = struct {
socket: std.net.Stream,
pub fn connectSystemBus() !Connection {
const address = std.os.getenv("DBUS_SYSTEM_BUS_ADDRESS") orelse
system_bus_address;
return Connection.connectAddress(address);
}
pub fn connectSessionBus() !Connection {
const address = std.os.getenv("DBUS_SESSION_BUS_ADDRESS") orelse
return error.EnvironmentVariableNotFound;
return Connection.connectAddress(address);
}
pub fn connectAddress(address: []const u8) !Connection {
// TODO Parse address according to spec:
// https://dbus.freedesktop.org/doc/dbus-specification.html#addresses
const expected_address_prefix = "unix:path=";
if (!std.mem.startsWith(u8, address, expected_address_prefix))
return error.AddressUnimplemented;
const socket_path = address[expected_address_prefix.len..];
return Connection.connectUnixSocket(socket_path);
}
pub fn connectUnixSocket(path: []const u8) !Connection {
const socket = try std.net.connectUnixSocket(path);
errdefer socket.close();
// Perform authentication
// We only support the EXTERNAL authentication mechanism, which
// authenticates (on unix systems) based on the user's uid
const uid = std.os.system.getuid();
var buffer: [100]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buffer);
try fbs.writer().print("{}", .{uid});
try socket.writer().print("\x00AUTH EXTERNAL {}\r\n", .{std.fmt.fmtSliceHexLower(fbs.getWritten())});
const amt = try socket.read(&buffer);
const response = buffer[0..amt];
std.log.debug("auth response: «{s}»", .{std.fmt.fmtSliceEscapeLower(response)});
if (std.mem.startsWith(u8, response, "OK ")) {
// Rest of response is server GUID in hex, which we don't use
} else if (std.mem.startsWith(u8, response, "REJECTED ")) {
// Rest of response is a list of authentication mechanisms
// supported, but we only support EXTERNAL
return error.AuthenticationRejected;
} else {
return error.UnexpectedAuthenticationResponse;
}
try socket.writer().print("BEGIN\r\n", .{});
// We are now authenticated and ready to send/receive D-Bus messages
return Connection{ .socket = socket };
}
pub fn disconnect(self: Connection) void {
self.socket.close();
}
}; | src/dbus.zig |
const std = @import("std");
const TinyCC = @import("./tcc.zig").TinyCC;
const js = @import("./quickjs.zig");
const GlobalContext = @import("./context.zig");
const purl = @import("./url.zig");
const catom = js.JsAtom.comptimeAtom;
const scoped = std.log.scoped(.main);
pub const enable_segfault_handler = false;
fn setModuleMeta(ctx: *js.JsContext, root: js.JsValue, url: [:0]const u8, args: ?[][:0]const u8) !*js.JsModuleDef {
scoped.debug("set module meta for {s} (url: {s})", .{ root, url });
if (root.getNormTag() != .Module) return error.NotAModule;
const ret: *js.JsModuleDef = root.getPointerT(js.JsModuleDef).?;
const meta = ret.getImportMeta(ctx);
defer meta.deinit(ctx);
var res = true;
res = res and try meta.defineProperty(ctx, catom(ctx, "url"), .{
.configurable = false,
.writable = false,
.enumerable = true,
.data = .{
.value = js.JsValue.init(ctx, .{ .String = url }),
},
});
res = res and try meta.defineProperty(ctx, catom(ctx, "main"), .{
.configurable = false,
.writable = false,
.enumerable = true,
.data = .{
.value = block: {
if (args) |notnull| {
var obj = js.JsValue.init(ctx, .Array);
for (notnull) |item, i| {
try obj.setProperty(ctx, i, js.JsValue.init(ctx, .{ .String = item }));
}
break :block obj;
} else {
break :block js.JsValue.init(ctx, .Undefined);
}
},
},
});
if (!res) return error.FailedToDefineProperty;
return ret;
}
fn makeUrl(allocator: *std.mem.Allocator, path: [:0]const u8) ![:0]const u8 {
comptime const fileproto = if (std.Target.current.os.tag == .windows) "file:///" else "file://";
const ret = try allocator.allocSentinel(u8, path.len + fileproto.len, 0);
std.mem.copy(u8, ret[0..fileproto.len], fileproto);
if (std.Target.current.os.tag == .windows) {
for (path) |ch, i|
ret[i + fileproto.len] = if (ch == '\\') '/' else ch;
} else {
std.mem.copy(u8, ret[fileproto.len..], path);
}
return ret;
}
const Loader = struct {
const loaderLog = std.log.scoped(.@"module loader");
header: js.JsModuleLoader = .{ .normalizefn = normalize, .loaderfn = loader },
fn enormalize(allocator: *std.mem.Allocator, ctx: *js.JsContext, base: [:0]const u8, name: [:0]const u8) ![*:0]const u8 {
loaderLog.info("try normalize (base: {s}, name: {s})", .{ base, name });
errdefer loaderLog.warn("failed to normalize", .{});
const baseurl = try purl.PartialURL.parse(allocator, base);
defer baseurl.deinit(allocator);
loaderLog.debug("parsed url: {s}", .{baseurl});
const ret = baseurl.resolveModule(allocator, name) orelse return error.ResolveFailed;
loaderLog.info("result: {s}", .{ret});
return ret.ptr;
}
fn normalize(self: *js.JsModuleLoader, ctx: *js.JsContext, base: [*:0]const u8, name: [*:0]const u8) [*:0]const u8 {
const out = std.io.getStdOut().writer();
const allocator = ctx.getRuntime().getOpaqueT(GlobalContext).?.allocator;
return enormalize(allocator, ctx, std.mem.span(base), std.mem.span(name)) catch (allocator.dupeZ(u8, std.mem.span(name)) catch unreachable);
}
fn openEx(allocator: *std.mem.Allocator, filename: []const u8) !std.fs.File {
return std.fs.cwd().openFile(filename, .{}) catch |e| switch (e) {
error.FileNotFound => {
const added = try std.fmt.allocPrint(allocator, "{s}.tjs", .{filename});
defer allocator.free(added);
return std.fs.cwd().openFile(added, .{});
},
else => return e,
};
}
fn readFile(allocator: *std.mem.Allocator, filename: []const u8) ![:0]const u8 {
const file = try openEx(allocator, filename);
defer file.close();
return file.readToEndAllocOptions(allocator, 1024 * 1024 * 1024, null, 1, 0);
}
fn loader(self: *js.JsModuleLoader, ctx: *js.JsContext, name: [*:0]const u8) ?*js.JsModuleDef {
loaderLog.info("try load module: {s}", .{name});
const E = js.JsCFunctionListEntry;
const allocator = ctx.getRuntime().getOpaqueT(GlobalContext).?.allocator;
const cmp = std.cstr.cmp;
const out = std.io.getStdOut().writer();
const filename = std.mem.span(name);
const data = readFile(allocator, filename) catch {
const errstr = std.fmt.allocPrint0(allocator, "could not load module filename '{s}': read failed", .{filename}) catch return null;
defer allocator.free(errstr);
_ = ctx.throw(.{ .Reference = errstr });
return null;
};
defer allocator.free(data);
const murl = makeUrl(allocator, filename) catch {
_ = ctx.throw(.OutOfMemory);
return null;
};
const value = ctx.eval(data, murl, .{ .module = true, .compile = true });
if (value.getNormTag() == .Exception) {
defer value.deinit(ctx);
ctx.dumpError();
const errstr = std.fmt.allocPrint0(allocator, "eval module '{s}' failed", .{filename}) catch return null;
defer allocator.free(errstr);
_ = ctx.throw(.{ .Reference = errstr });
return null;
}
defer allocator.free(murl);
return setModuleMeta(ctx, value, murl, null) catch {
const errstr = std.fmt.allocPrint0(allocator, "eval module '{s}' failed", .{filename}) catch return null;
defer allocator.free(errstr);
_ = ctx.throw(.{ .Reference = errstr });
return null;
};
}
};
fn loadAllMods(comptime mod: type, ctx: *js.JsContext) !void {
inline for (std.meta.declarations(mod)) |decl| {
if (!decl.is_pub) continue;
const field = @field(mod, decl.name);
_ = try js.JsModuleDef.init("builtin:" ++ decl.name, ctx, field);
}
}
fn tourl(allocator: *std.mem.Allocator, file: []const u8) ![:0]const u8 {
const cwd = try std.process.getCwdAlloc(allocator);
defer allocator.free(cwd);
var path = try std.fs.path.resolve(allocator, &[_][]const u8{
cwd, file,
});
defer allocator.free(path);
if (comptime (std.fs.path.sep == '\\')) {
for (path) |*ch| {
if (ch.* == '\\') {
ch.* = '/';
}
}
}
return std.fmt.allocPrint0(allocator, "file:///{s}", .{path});
}
pub fn main() anyerror!void {
@import("./workaround.zig").patch();
const allocator = std.heap.c_allocator;
var args = try std.process.argsAlloc(allocator);
defer std.process.argsFree(allocator, args);
if (args.len < 2) {
return error.NotEnoughArguments;
}
const filename = args[1];
const rooturl = try tourl(allocator, filename);
defer allocator.free(rooturl);
const file = try std.fs.cwd().openFile(filename, .{});
defer file.close();
const contents = try file.readToEndAllocOptions(allocator, 1024 * 1024 * 1024, null, 1, 0);
defer allocator.free(contents);
const rt = js.JsRuntime.init();
var xctx: GlobalContext = .{
.allocator = allocator,
};
rt.setOpaque(&xctx);
defer rt.deinit();
var loader: Loader = .{};
rt.setModuleLoader(&loader.header);
const ctx = try js.JsContext.init(rt);
defer ctx.deinit();
try loadAllMods(@import("./mods.zig"), ctx);
const val = ctx.eval(contents, rooturl, .{ .module = true, .compile = true });
if (val.getNormTag() == .Module) {
_ = try setModuleMeta(ctx, val, rooturl, args[1..]);
const ret = ctx.evalFunction(val);
defer ret.deinit(ctx);
if (ret.getNormTag() == .Exception) {
ctx.dumpError();
}
} else if (val.getNormTag() == .Exception) {
ctx.dumpError();
}
while (rt.pending()) {}
ctx.dumpError();
} | src/main.zig |
pub const WasiHandle = i32;
pub const Char8 = u8;
pub const Char32 = u32;
pub fn WasiPtr(comptime T: type) type {
return [*c]const T;
}
pub fn WasiMutPtr(comptime T: type) type {
return [*c]T;
}
pub const WasiStringBytesPtr = WasiPtr(Char8);
pub const WasiString = extern struct {
ptr: WasiStringBytesPtr,
len: usize,
fn from_slice(slice: []const u8) WasiString {
return WasiString{ .ptr = slice.ptr, .len = slice.len };
}
fn as_slice(wasi_string: WasiString) []const u8 {
return wasi_string.ptr[wasi_string.len];
}
};
pub fn WasiSlice(comptime T: type) type {
return extern struct {
ptr: WasiPtr(T),
len: usize,
fn from_slice(slice: []const u8) WasiSlice {
return WasiSlice{ .ptr = slice.ptr, .len = slice.len };
}
fn as_slice(wasi_slice: WasiSlice) []const u8 {
return wasi_slice.ptr[wasi_slice.len];
}
};
}
pub fn WasiMutSlice(comptime T: type) type {
return extern struct {
ptr: WasiMutPtr(T),
len: usize,
fn from_slice(slice: []u8) WasiMutSlice {
return WasiMutSlice{ .ptr = slice.ptr, .len = slice.len };
}
fn as_slice(wasi_slice: WasiMutSlice) []u8 {
return wasi_slice.ptr[wasi_slice.len];
}
};
}
// ---------------------- Module: [typenames] ----------------------
/// Status codes returned from hostcalls.
pub const FastlyStatus = enum(u32) {
OK = 0,
ERROR = 1,
INVAL = 2,
BADF = 3,
BUFLEN = 4,
UNSUPPORTED = 5,
BADALIGN = 6,
HTTPINVALID = 7,
HTTPUSER = 8,
HTTPINCOMPLETE = 9,
NONE = 10,
HTTPHEADTOOLARGE = 11,
HTTPINVALIDSTATUS = 12,
};
/// A tag indicating HTTP protocol versions.
pub const HttpVersion = enum(u32) {
HTTP_09 = 0,
HTTP_10 = 1,
HTTP_11 = 2,
H_2 = 3,
H_3 = 4,
};
/// HTTP status codes.
pub const HttpStatus = u16;
pub const BodyWriteEnd = enum(u32) {
BACK = 0,
FRONT = 1,
};
/// A handle to an HTTP request or response body.
pub const BodyHandle = WasiHandle;
/// A handle to an HTTP request.
pub const RequestHandle = WasiHandle;
/// A handle to an HTTP response.
pub const ResponseHandle = WasiHandle;
/// A handle to a currently-pending asynchronous HTTP request.
pub const PendingRequestHandle = WasiHandle;
/// A handle to a logging endpoint.
pub const EndpointHandle = WasiHandle;
/// A handle to an Edge Dictionary.
pub const DictionaryHandle = WasiHandle;
/// A "multi-value" cursor.
pub const MultiValueCursor = u32;
/// -1 represents "finished", non-negative represents a $multi_value_cursor:
pub const MultiValueCursorResult = i64;
/// An override for response caching behavior.
pub const CacheOverrideTag = u32;
pub const CACHE_OVERRIDE_TAG_NONE: CacheOverrideTag = 0x1;
pub const CACHE_OVERRIDE_TAG_PASS: CacheOverrideTag = 0x2;
pub const CACHE_OVERRIDE_TAG_TTL: CacheOverrideTag = 0x4;
pub const CACHE_OVERRIDE_TAG_STALE_WHILE_REVALIDATE: CacheOverrideTag = 0x8;
pub const CACHE_OVERRIDE_TAG_PCI: CacheOverrideTag = 0x10;
pub const NumBytes = usize;
pub const HeaderCount = u32;
pub const IsDone = u32;
pub const DoneIdx = u32;
// ---------------------- Module: [fastly_abi] ----------------------
pub const FastlyAbi = struct {
pub extern "fastly_abi" fn init(
abi_version: u64,
) callconv(.C) FastlyStatus;
};
// ---------------------- Module: [fastly_dictionary] ----------------------
pub const FastlyDictionary = struct {
pub extern "fastly_dictionary" fn open(
name_ptr: WasiPtr(Char8),
name_len: usize,
result_ptr: WasiMutPtr(DictionaryHandle),
) callconv(.C) FastlyStatus;
pub extern "fastly_dictionary" fn get(
h: DictionaryHandle,
key_ptr: WasiPtr(Char8),
key_len: usize,
value: WasiMutPtr(Char8),
value_max_len: usize,
result_ptr: WasiMutPtr(NumBytes),
) callconv(.C) FastlyStatus;
};
// ---------------------- Module: [fastly_geo] ----------------------
pub const FastlyGeo = struct {
pub extern "fastly_geo" fn lookup(
addr_octets: WasiPtr(Char8),
addr_len: usize,
buf: WasiMutPtr(Char8),
buf_len: usize,
nwritten_out: WasiMutPtr(usize),
) callconv(.C) FastlyStatus;
};
// ---------------------- Module: [fastly_http_body] ----------------------
pub const FastlyHttpBody = struct {
pub extern "fastly_http_body" fn append(
dest: BodyHandle,
src: BodyHandle,
) callconv(.C) FastlyStatus;
pub extern "fastly_http_body" fn new(
result_ptr: WasiMutPtr(BodyHandle),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_body" fn read(
h: BodyHandle,
buf: WasiMutPtr(u8),
buf_len: usize,
result_ptr: WasiMutPtr(NumBytes),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_body" fn write(
h: BodyHandle,
buf_ptr: WasiPtr(u8),
buf_len: usize,
end: BodyWriteEnd,
result_ptr: WasiMutPtr(NumBytes),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_body" fn close(
h: BodyHandle,
) callconv(.C) FastlyStatus;
};
// ---------------------- Module: [fastly_http_req] ----------------------
pub const FastlyHttpReq = struct {
pub extern "fastly_http_req" fn body_downstream_get(
result_0_ptr: WasiMutPtr(RequestHandle),
result_1_ptr: WasiMutPtr(BodyHandle),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn cache_override_set(
h: RequestHandle,
tag: CacheOverrideTag,
ttl: u32,
stale_while_revalidate: u32,
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn cache_override_v2_set(
h: RequestHandle,
tag: CacheOverrideTag,
ttl: u32,
stale_while_revalidate: u32,
sk_ptr: WasiPtr(u8),
sk_len: usize,
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn downstream_client_ip_addr(
addr_octets_out: WasiMutPtr(Char8),
result_ptr: WasiMutPtr(NumBytes),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn downstream_tls_cipher_openssl_name(
cipher_out: WasiMutPtr(Char8),
cipher_max_len: usize,
nwritten_out: WasiMutPtr(usize),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn downstream_tls_protocol(
protocol_out: WasiMutPtr(Char8),
protocol_max_len: usize,
nwritten_out: WasiMutPtr(usize),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn downstream_tls_client_hello(
chello_out: WasiMutPtr(Char8),
chello_max_len: usize,
nwritten_out: WasiMutPtr(usize),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn new(
result_ptr: WasiMutPtr(RequestHandle),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn header_names_get(
h: RequestHandle,
buf: WasiMutPtr(Char8),
buf_len: usize,
cursor: MultiValueCursor,
ending_cursor_out: WasiMutPtr(MultiValueCursorResult),
nwritten_out: WasiMutPtr(usize),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn original_header_names_get(
buf: WasiMutPtr(Char8),
buf_len: usize,
cursor: MultiValueCursor,
ending_cursor_out: WasiMutPtr(MultiValueCursorResult),
nwritten_out: WasiMutPtr(usize),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn original_header_count(
result_ptr: WasiMutPtr(HeaderCount),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn header_value_get(
h: RequestHandle,
name_ptr: WasiPtr(u8),
name_len: usize,
value: WasiMutPtr(Char8),
value_max_len: usize,
nwritten_out: WasiMutPtr(usize),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn header_values_get(
h: RequestHandle,
name_ptr: WasiPtr(u8),
name_len: usize,
buf: WasiMutPtr(Char8),
buf_len: usize,
cursor: MultiValueCursor,
ending_cursor_out: WasiMutPtr(MultiValueCursorResult),
nwritten_out: WasiMutPtr(usize),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn header_values_set(
h: RequestHandle,
name_ptr: WasiPtr(u8),
name_len: usize,
values_ptr: WasiPtr(Char8),
values_len: usize,
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn header_insert(
h: RequestHandle,
name_ptr: WasiPtr(u8),
name_len: usize,
value_ptr: WasiPtr(u8),
value_len: usize,
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn header_append(
h: RequestHandle,
name_ptr: WasiPtr(u8),
name_len: usize,
value_ptr: WasiPtr(u8),
value_len: usize,
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn header_remove(
h: RequestHandle,
name_ptr: WasiPtr(u8),
name_len: usize,
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn method_get(
h: RequestHandle,
buf: WasiMutPtr(Char8),
buf_len: usize,
nwritten_out: WasiMutPtr(usize),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn method_set(
h: RequestHandle,
method_ptr: WasiPtr(Char8),
method_len: usize,
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn uri_get(
h: RequestHandle,
buf: WasiMutPtr(Char8),
buf_len: usize,
nwritten_out: WasiMutPtr(usize),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn uri_set(
h: RequestHandle,
uri_ptr: WasiPtr(Char8),
uri_len: usize,
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn version_get(
h: RequestHandle,
result_ptr: WasiMutPtr(HttpVersion),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn version_set(
h: RequestHandle,
version: HttpVersion,
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn send(
h: RequestHandle,
b: BodyHandle,
backend_ptr: WasiPtr(Char8),
backend_len: usize,
result_0_ptr: WasiMutPtr(ResponseHandle),
result_1_ptr: WasiMutPtr(BodyHandle),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn send_async(
h: RequestHandle,
b: BodyHandle,
backend_ptr: WasiPtr(Char8),
backend_len: usize,
result_ptr: WasiMutPtr(PendingRequestHandle),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn send_async_streaming(
h: RequestHandle,
b: BodyHandle,
backend_ptr: WasiPtr(Char8),
backend_len: usize,
result_ptr: WasiMutPtr(PendingRequestHandle),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn pending_req_poll(
h: PendingRequestHandle,
result_0_ptr: WasiMutPtr(IsDone),
result_1_ptr: WasiMutPtr(ResponseHandle),
result_2_ptr: WasiMutPtr(BodyHandle),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn pending_req_wait(
h: PendingRequestHandle,
result_0_ptr: WasiMutPtr(ResponseHandle),
result_1_ptr: WasiMutPtr(BodyHandle),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn pending_req_select(
hs_ptr: WasiPtr(PendingRequestHandle),
hs_len: usize,
result_0_ptr: WasiMutPtr(DoneIdx),
result_1_ptr: WasiMutPtr(ResponseHandle),
result_2_ptr: WasiMutPtr(BodyHandle),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_req" fn close(
h: RequestHandle,
) callconv(.C) FastlyStatus;
};
// ---------------------- Module: [fastly_http_resp] ----------------------
pub const FastlyHttpResp = struct {
pub extern "fastly_http_resp" fn new(
result_ptr: WasiMutPtr(ResponseHandle),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_resp" fn header_names_get(
h: ResponseHandle,
buf: WasiMutPtr(Char8),
buf_len: usize,
cursor: MultiValueCursor,
ending_cursor_out: WasiMutPtr(MultiValueCursorResult),
nwritten_out: WasiMutPtr(usize),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_resp" fn header_value_get(
h: ResponseHandle,
name_ptr: WasiPtr(u8),
name_len: usize,
value: WasiMutPtr(Char8),
value_max_len: usize,
nwritten_out: WasiMutPtr(usize),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_resp" fn header_values_get(
h: ResponseHandle,
name_ptr: WasiPtr(u8),
name_len: usize,
buf: WasiMutPtr(Char8),
buf_len: usize,
cursor: MultiValueCursor,
ending_cursor_out: WasiMutPtr(MultiValueCursorResult),
nwritten_out: WasiMutPtr(usize),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_resp" fn header_values_set(
h: ResponseHandle,
name_ptr: WasiPtr(u8),
name_len: usize,
values_ptr: WasiPtr(Char8),
values_len: usize,
) callconv(.C) FastlyStatus;
pub extern "fastly_http_resp" fn header_insert(
h: ResponseHandle,
name_ptr: WasiPtr(u8),
name_len: usize,
value_ptr: WasiPtr(u8),
value_len: usize,
) callconv(.C) FastlyStatus;
pub extern "fastly_http_resp" fn header_append(
h: ResponseHandle,
name_ptr: WasiPtr(u8),
name_len: usize,
value_ptr: WasiPtr(u8),
value_len: usize,
) callconv(.C) FastlyStatus;
pub extern "fastly_http_resp" fn header_remove(
h: ResponseHandle,
name_ptr: WasiPtr(u8),
name_len: usize,
) callconv(.C) FastlyStatus;
pub extern "fastly_http_resp" fn version_get(
h: ResponseHandle,
result_ptr: WasiMutPtr(HttpVersion),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_resp" fn version_set(
h: ResponseHandle,
version: HttpVersion,
) callconv(.C) FastlyStatus;
pub extern "fastly_http_resp" fn send_downstream(
h: ResponseHandle,
b: BodyHandle,
streaming: u32,
) callconv(.C) FastlyStatus;
pub extern "fastly_http_resp" fn status_get(
h: ResponseHandle,
result_ptr: WasiMutPtr(HttpStatus),
) callconv(.C) FastlyStatus;
pub extern "fastly_http_resp" fn status_set(
h: ResponseHandle,
status: HttpStatus,
) callconv(.C) FastlyStatus;
pub extern "fastly_http_resp" fn close(
h: ResponseHandle,
) callconv(.C) FastlyStatus;
};
// ---------------------- Module: [fastly_log] ----------------------
pub const FastlyLog = struct {
pub extern "fastly_log" fn endpoint_get(
name_ptr: WasiPtr(u8),
name_len: usize,
result_ptr: WasiMutPtr(EndpointHandle),
) callconv(.C) FastlyStatus;
pub extern "fastly_log" fn write(
h: EndpointHandle,
msg_ptr: WasiPtr(u8),
msg_len: usize,
result_ptr: WasiMutPtr(NumBytes),
) callconv(.C) FastlyStatus;
};
// ---------------------- Module: [fastly_uap] ----------------------
pub const FastlyUap = struct {
pub extern "fastly_uap" fn parse(
user_agent_ptr: WasiPtr(Char8),
user_agent_len: usize,
family: WasiMutPtr(Char8),
family_len: usize,
family_nwritten_out: WasiMutPtr(usize),
major: WasiMutPtr(Char8),
major_len: usize,
major_nwritten_out: WasiMutPtr(usize),
minor: WasiMutPtr(Char8),
minor_len: usize,
minor_nwritten_out: WasiMutPtr(usize),
patch: WasiMutPtr(Char8),
patch_len: usize,
patch_nwritten_out: WasiMutPtr(usize),
) callconv(.C) FastlyStatus;
}; | src/zigly/wasm.zig |
const gen3 = @import("../gen3.zig");
const rom = @import("../rom.zig");
const std = @import("std");
const io = std.io;
const mem = std.mem;
// TODO: Replace with Replacing/Escaping streams
pub const en_us = [_]rom.encoding.Char{
.{ " ", "\x00" },
.{ "À", "\x01" },
.{ "Á", "\x02" },
.{ "Â", "\x03" },
.{ "Ç", "\x04" },
.{ "È", "\x05" },
.{ "É", "\x06" },
.{ "Ê", "\x07" },
.{ "Ë", "\x08" },
.{ "Ì", "\x09" },
.{ "Î", "\x0B" },
.{ "Ï", "\x0C" },
.{ "Ò", "\x0D" },
.{ "Ó", "\x0E" },
.{ "Ô", "\x0F" },
.{ "Œ", "\x10" },
.{ "Ù", "\x11" },
.{ "Ú", "\x12" },
.{ "Û", "\x13" },
.{ "Ñ", "\x14" },
.{ "ß", "\x15" },
.{ "à", "\x16" },
.{ "á", "\x17" },
.{ "ç", "\x19" },
.{ "è", "\x1A" },
.{ "é", "\x1B" },
.{ "ê", "\x1C" },
.{ "ë", "\x1D" },
.{ "ì", "\x1E" },
.{ "î", "\x20" },
.{ "ï", "\x21" },
.{ "ò", "\x22" },
.{ "ó", "\x23" },
.{ "ô", "\x24" },
.{ "œ", "\x25" },
.{ "ù", "\x26" },
.{ "ú", "\x27" },
.{ "û", "\x28" },
.{ "ñ", "\x29" },
.{ "º", "\x2A" },
.{ "ª", "\x2B" },
.{ "{SUPER_ER}", "\x2C" },
.{ "&", "\x2D" },
.{ "+", "\x2E" },
.{ "{LV}", "\x34" },
.{ "=", "\x35" },
.{ ";", "\x36" },
.{ "¿", "\x51" },
.{ "¡", "\x52" },
.{ "{PK}", "\x53" },
.{ "{PKMN}", "\x53\x54" },
.{ "{POKEBLOCK}", "\x55\x56\x57\x58\x59" },
.{ "Í", "\x5A" },
.{ "%", "\x5B" },
.{ "(", "\x5C" },
.{ ")", "\x5D" },
.{ "â", "\x68" },
.{ "í", "\x6F" },
.{ "{UNK_SPACER}", "\x77" },
.{ "{UP_ARROW}", "\x79" },
.{ "{DOWN_ARROW}", "\x7A" },
.{ "{LEFT_ARROW}", "\x7B" },
.{ "{RIGHT_ARROW}", "\x7C" },
.{ "{SUPER_E}", "\x84" },
.{ "<", "\x85" },
.{ ">", "\x86" },
.{ "{SUPER_RE}", "\xA0" },
.{ "0", "\xA1" },
.{ "1", "\xA2" },
.{ "2", "\xA3" },
.{ "3", "\xA4" },
.{ "4", "\xA5" },
.{ "5", "\xA6" },
.{ "6", "\xA7" },
.{ "7", "\xA8" },
.{ "8", "\xA9" },
.{ "9", "\xAA" },
.{ "!", "\xAB" },
.{ "?", "\xAC" },
.{ ".", "\xAD" },
.{ "-", "\xAE" },
.{ "·", "\xAF" },
.{ "…", "\xB0" },
.{ "“", "\xB1" },
.{ "”", "\xB2" },
.{ "‘", "\xB3" },
.{ "'", "\xB4" },
.{ "♂", "\xB5" },
.{ "♀", "\xB6" },
.{ "¥", "\xB7" },
.{ ",", "\xB8" },
.{ "×", "\xB9" },
.{ "/", "\xBA" },
.{ "A", "\xBB" },
.{ "B", "\xBC" },
.{ "C", "\xBD" },
.{ "D", "\xBE" },
.{ "E", "\xBF" },
.{ "F", "\xC0" },
.{ "G", "\xC1" },
.{ "H", "\xC2" },
.{ "I", "\xC3" },
.{ "J", "\xC4" },
.{ "K", "\xC5" },
.{ "L", "\xC6" },
.{ "M", "\xC7" },
.{ "N", "\xC8" },
.{ "O", "\xC9" },
.{ "P", "\xCA" },
.{ "Q", "\xCB" },
.{ "R", "\xCC" },
.{ "S", "\xCD" },
.{ "T", "\xCE" },
.{ "U", "\xCF" },
.{ "V", "\xD0" },
.{ "W", "\xD1" },
.{ "X", "\xD2" },
.{ "Y", "\xD3" },
.{ "Z", "\xD4" },
.{ "a", "\xD5" },
.{ "b", "\xD6" },
.{ "c", "\xD7" },
.{ "d", "\xD8" },
.{ "e", "\xD9" },
.{ "f", "\xDA" },
.{ "g", "\xDB" },
.{ "h", "\xDC" },
.{ "i", "\xDD" },
.{ "j", "\xDE" },
.{ "k", "\xDF" },
.{ "l", "\xE0" },
.{ "m", "\xE1" },
.{ "n", "\xE2" },
.{ "o", "\xE3" },
.{ "p", "\xE4" },
.{ "q", "\xE5" },
.{ "r", "\xE6" },
.{ "s", "\xE7" },
.{ "t", "\xE8" },
.{ "u", "\xE9" },
.{ "v", "\xEA" },
.{ "w", "\xEB" },
.{ "x", "\xEC" },
.{ "y", "\xED" },
.{ "z", "\xEE" },
.{ "▶", "\xEF" },
.{ ":", "\xF0" },
.{ "Ä", "\xF1" },
.{ "Ö", "\xF2" },
.{ "Ü", "\xF3" },
.{ "ä", "\xF4" },
.{ "ö", "\xF5" },
.{ "ü", "\xF6" },
.{ "\\l", "\xFA" },
.{ "\\p", "\xFB" },
.{ "{PAUSE 0x0F}", "\xFC\x08\x0F" },
.{ "{PAUSE 0x39}", "\xFC\x08\x39" },
.{ "{PLAY_BGM}", "\xFC\x0B" },
.{ "{TALL_PLUS}", "\xFC\x0C\xFB" },
.{ "{PLAYER}", "\xFD\x01" },
.{ "{STR_VAR_1}", "\xFD\x02" },
.{ "{STR_VAR_2}", "\xFD\x03" },
.{ "{STR_VAR_3}", "\xFD\x04" },
.{ "{KUN}", "\xFD\x05" },
.{ "{RIVAL}", "\xFD\x06" },
.{ "{VERSION}", "\xFD\x07" },
.{ "{AQUA}", "\xFD\x08" },
.{ "{MAGMA}", "\xFD\x09" },
.{ "{ARCHIE}", "\xFD\x0A" },
.{ "{MAXIE}", "\xFD\x0B" },
.{ "{KYOGRE}", "\xFD\x0C" },
.{ "{GROUdON}", "\xFD\x0D" },
.{ "\n", "\xFE" },
.{ "$", "\xFF" },
};
test "en_us" {
try rom.encoding.testCharMap(&en_us, "HELLO WORLD", "\xC2\xBF\xC6\xC6\xC9\x00\xD1\xC9\xCC\xC6\xBE");
try rom.encoding.testCharMap(&en_us, "{PK}{PKMN}", "\x53\x53\x54");
}
pub fn encode(lang: gen3.Language, reader: anytype, out: []u8) !void {
const map = switch (lang) {
.en_us => &en_us,
};
var fos = io.fixedBufferStream(out);
try rom.encoding.encodeEx(map, 0, reader, fos.writer());
try fos.writer().writeByte(0xff);
}
pub fn decode(lang: gen3.Language, str: []const u8, writer: anytype) !void {
const map = switch (lang) {
.en_us => &en_us,
};
const end = mem.indexOfScalar(u8, str, 0xff) orelse str.len;
try rom.encoding.encode(map, 1, str[0..end], writer);
} | src/core/gen3/encodings.zig |
const std = @import("std");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const testing = std.testing;
const Node = struct {
x: u32,
y: u32,
width: u32,
};
pub const Error = error{
/// Atlas cannot fit the desired region. You must enlarge the atlas.
AtlasFull,
};
/// A region within the texture atlas. These can be acquired using the
/// "reserve" function. A region reservation is required to write data.
pub const Region = struct {
x: u32,
y: u32,
width: u32,
height: u32,
pub fn getUVData(region: Region, atlas_float_size: f32) UVData {
return .{
.bottom_left = .{ @intToFloat(f32, region.x) / atlas_float_size, (atlas_float_size - @intToFloat(f32, region.y + region.height)) / atlas_float_size },
.width_and_height = .{ @intToFloat(f32, region.width) / atlas_float_size, @intToFloat(f32, region.height) / atlas_float_size },
};
}
};
pub const UVData = struct {
bottom_left: @Vector(2, f32),
width_and_height: @Vector(2, f32),
};
pub fn Atlas(comptime T: type) type {
return struct {
/// Data is the raw texture data.
data: []T,
/// Width and height of the atlas texture. The current implementation is
/// always square so this is both the width and the height.
size: u32 = 0,
/// The nodes (rectangles) of available space.
nodes: std.ArrayListUnmanaged(Node) = .{},
const Self = @This();
pub fn init(alloc: Allocator, size: u32) !Self {
var result = Self{
.data = try alloc.alloc(T, size * size),
.size = size,
.nodes = .{},
};
// TODO: figure out optimal prealloc based on real world usage
try result.nodes.ensureUnusedCapacity(alloc, 64);
// This sets up our initial state
result.clear();
return result;
}
pub fn deinit(self: *Self, alloc: Allocator) void {
self.nodes.deinit(alloc);
alloc.free(self.data);
self.* = undefined;
}
/// Reserve a region within the atlas with the given width and height.
///
/// May allocate to add a new rectangle into the internal list of rectangles.
/// This will not automatically enlarge the texture if it is full.
pub fn reserve(self: *Self, alloc: Allocator, width: u32, height: u32) !Region {
// x, y are populated within :best_idx below
var region: Region = .{ .x = 0, .y = 0, .width = width, .height = height };
// Find the location in our nodes list to insert the new node for this region.
var best_idx: usize = best_idx: {
var best_height: u32 = std.math.maxInt(u32);
var best_width: u32 = best_height;
var chosen: ?usize = null;
var i: usize = 0;
while (i < self.nodes.items.len) : (i += 1) {
// Check if our region fits within this node.
const y = self.fit(i, width, height) orelse continue;
const node = self.nodes.items[i];
if ((y + height) < best_height or
((y + height) == best_height and
(node.width > 0 and node.width < best_width)))
{
chosen = i;
best_width = node.width;
best_height = y + height;
region.x = node.x;
region.y = y;
}
}
// If we never found a chosen index, the atlas cannot fit our region.
break :best_idx chosen orelse return Error.AtlasFull;
};
// Insert our new node for this rectangle at the exact best index
try self.nodes.insert(alloc, best_idx, .{
.x = region.x,
.y = region.y + height,
.width = width,
});
// Optimize our rectangles
var i: usize = best_idx + 1;
while (i < self.nodes.items.len) : (i += 1) {
const node = &self.nodes.items[i];
const prev = self.nodes.items[i - 1];
if (node.x < (prev.x + prev.width)) {
const shrink = prev.x + prev.width - node.x;
node.x += shrink;
node.width -|= shrink;
if (node.width <= 0) {
_ = self.nodes.orderedRemove(i);
i -= 1;
continue;
}
}
break;
}
self.merge();
return region;
}
/// Attempts to fit a rectangle of width x height into the node at idx.
/// The return value is the y within the texture where the rectangle can be
/// placed. The x is the same as the node.
fn fit(self: Self, idx: usize, width: u32, height: u32) ?u32 {
// If the added width exceeds our texture size, it doesn't fit.
const node = self.nodes.items[idx];
if ((node.x + width) > (self.size - 1)) return null;
// Go node by node looking for space that can fit our width.
var y = node.y;
var i = idx;
var width_left = width;
while (width_left > 0) : (i += 1) {
const n = self.nodes.items[i];
if (n.y > y) y = n.y;
// If the added height exceeds our texture size, it doesn't fit.
if ((y + height) > (self.size - 1)) return null;
width_left -|= n.width;
}
return y;
}
/// Merge adjacent nodes with the same y value.
fn merge(self: *Self) void {
var i: usize = 0;
while (i < self.nodes.items.len - 1) {
const node = &self.nodes.items[i];
const next = self.nodes.items[i + 1];
if (node.y == next.y) {
node.width += next.width;
_ = self.nodes.orderedRemove(i + 1);
continue;
}
i += 1;
}
}
/// Set the data associated with a reserved region. The data is expected
/// to fit exactly within the region.
pub fn set(self: *Self, reg: Region, data: []const T) void {
assert(reg.x < (self.size - 1));
assert((reg.x + reg.width) <= (self.size - 1));
assert(reg.y < (self.size - 1));
assert((reg.y + reg.height) <= (self.size - 1));
var i: u32 = 0;
while (i < reg.height) : (i += 1) {
const tex_offset = ((reg.y + i) * self.size) + reg.x;
const data_offset = i * reg.width;
std.mem.copy(
T,
self.data[tex_offset..],
data[data_offset .. data_offset + reg.width],
);
}
}
// Grow the texture to the new size, preserving all previously written data.
pub fn grow(self: *Self, alloc: Allocator, size_new: u32) Allocator.Error!void {
assert(size_new >= self.size);
if (size_new == self.size) return;
// Preserve our old values so we can copy the old data
const data_old = self.data;
const size_old = self.size;
self.data = try alloc.alloc(T, size_new * size_new);
defer alloc.free(data_old); // Only defer after new data succeeded
self.size = size_new; // Only set size after new alloc succeeded
std.mem.set(T, self.data, std.mem.zeroes(T));
self.set(.{
.x = 0, // don't bother skipping border so we can avoid strides
.y = 1, // skip the first border row
.width = size_old,
.height = size_old - 2, // skip the last border row
}, data_old[size_old..]);
// Add our new rectangle for our added righthand space
try self.nodes.append(alloc, .{
.x = size_old - 1,
.y = 1,
.width = size_new - size_old,
});
}
// Empty the atlas. This doesn't reclaim any previously allocated memory.
pub fn clear(self: *Self) void {
std.mem.set(T, self.data, std.mem.zeroes(T));
self.nodes.clearRetainingCapacity();
// Add our initial rectangle. This is the size of the full texture
// and is the initial rectangle we fit our regions in. We keep a 1px border
// to avoid artifacting when sampling the texture.
self.nodes.appendAssumeCapacity(.{ .x = 1, .y = 1, .width = self.size - 2 });
}
};
}
test "exact fit" {
const alloc = testing.allocator;
var atlas = try Atlas(u32).init(alloc, 34); // +2 for 1px border
defer atlas.deinit(alloc);
_ = try atlas.reserve(alloc, 32, 32);
try testing.expectError(Error.AtlasFull, atlas.reserve(alloc, 1, 1));
}
test "doesnt fit" {
const alloc = testing.allocator;
var atlas = try Atlas(f32).init(alloc, 32);
defer atlas.deinit(alloc);
// doesn't fit due to border
try testing.expectError(Error.AtlasFull, atlas.reserve(alloc, 32, 32));
}
test "fit multiple" {
const alloc = testing.allocator;
var atlas = try Atlas(u16).init(alloc, 32);
defer atlas.deinit(alloc);
_ = try atlas.reserve(alloc, 15, 30);
_ = try atlas.reserve(alloc, 15, 30);
try testing.expectError(Error.AtlasFull, atlas.reserve(alloc, 1, 1));
}
test "writing data" {
const alloc = testing.allocator;
var atlas = try Atlas(u64).init(alloc, 32);
defer atlas.deinit(alloc);
const reg = try atlas.reserve(alloc, 2, 2);
atlas.set(reg, &[_]u64{ 1, 2, 3, 4 });
// 33 because of the 1px border and so on
try testing.expectEqual(@as(u64, 1), atlas.data[33]);
try testing.expectEqual(@as(u64, 2), atlas.data[34]);
try testing.expectEqual(@as(u64, 3), atlas.data[65]);
try testing.expectEqual(@as(u64, 4), atlas.data[66]);
}
test "grow" {
const alloc = testing.allocator;
var atlas = try Atlas(u32).init(alloc, 4); // +2 for 1px border
defer atlas.deinit(alloc);
const reg = try atlas.reserve(alloc, 2, 2);
try testing.expectError(Error.AtlasFull, atlas.reserve(alloc, 1, 1));
// Write some data so we can verify that growing doesn't mess it up
atlas.set(reg, &[_]u32{ 1, 2, 3, 4 });
try testing.expectEqual(@as(u32, 1), atlas.data[5]);
try testing.expectEqual(@as(u32, 2), atlas.data[6]);
try testing.expectEqual(@as(u32, 3), atlas.data[9]);
try testing.expectEqual(@as(u32, 4), atlas.data[10]);
// Expand by exactly 1 should fit our new 1x1 block.
try atlas.grow(alloc, atlas.size + 1);
_ = try atlas.reserve(alloc, 1, 1);
// Ensure our data is still set. Not the offsets change due to size.
try testing.expectEqual(@as(u32, 1), atlas.data[atlas.size + 1]);
try testing.expectEqual(@as(u32, 2), atlas.data[atlas.size + 2]);
try testing.expectEqual(@as(u32, 3), atlas.data[atlas.size * 2 + 1]);
try testing.expectEqual(@as(u32, 4), atlas.data[atlas.size * 2 + 2]);
} | examples/gkurve/atlas.zig |
const std = @import("std");
const os = std.os;
const io = std.io;
/// ReadMode defines the read behaivour when using raw mode
pub const ReadMode = enum {
blocking,
nonblocking,
};
pub fn enableRawMode(handle: os.system.fd_t, blocking: ReadMode) !RawTerm {
// var original_termios = try os.tcgetattr(handle);
var original_termios = try os.tcgetattr(handle);
var termios = original_termios;
// https://viewsourcecode.org/snaptoken/kilo/02.enteringRawMode.html
// All of this are bitflags, so we do NOT and then AND to disable
// ICRNL (iflag) : fix CTRL-M (carriage returns)
// IXON (iflag) : disable Ctrl-S and Ctrl-Q
// OPOST (oflag) : turn off all output processing
// ECHO (lflag) : disable prints every key to terminal
// ICANON (lflag): disable to reads byte per byte instead of line (or when user press enter)
// IEXTEN (lflag): disable Ctrl-V
// ISIG (lflag) : disable Ctrl-C and Ctrl-Z
// Miscellaneous flags (most modern terminal already have them disabled)
// BRKINT, INPCK, ISTRIP and CS8
termios.iflag &= ~(os.system.BRKINT | os.system.ICRNL | os.system.INPCK | os.system.ISTRIP | os.system.IXON);
termios.oflag &= ~(os.system.OPOST);
termios.cflag |= (os.system.CS8);
termios.lflag &= ~(os.system.ECHO | os.system.ICANON | os.system.IEXTEN | os.system.ISIG);
switch (blocking) {
// Wait until it reads at least one byte
.blocking => termios.cc[os.system.V.MIN] = 1,
// Don't wait
.nonblocking => termios.cc[os.system.V.MIN] = 0,
}
// Wait 100 miliseconds at maximum.
termios.cc[os.system.V.TIME] = 1;
// apply changes
try os.tcsetattr(handle, .FLUSH, termios);
return RawTerm{
.orig_termios = original_termios,
.handle = handle,
};
}
/// A raw terminal representation, you can enter terminal raw mode
/// using this struct. Raw mode is essential to create a TUI.
pub const RawTerm = struct {
orig_termios: os.termios,
/// The OS-specific file descriptor or file handle.
handle: os.system.fd_t,
const Self = @This();
/// Returns to the previous terminal state
pub fn disableRawMode(self: *Self) !void {
try os.tcsetattr(self.handle, .FLUSH, self.orig_termios);
}
};
/// Returned by `getSize()`
pub const TermSize = struct {
width: u16,
height: u16,
};
/// Get the terminal size, use `fd` equals to 0 use stdin
pub fn getSize(fd: ?std.os.fd_t) !TermSize {
var ws: std.os.system.winsize = undefined;
// https://github.com/ziglang/zig/blob/master/lib/std/os/linux/errno/generic.zig
const err = std.os.linux.ioctl(fd, os.system.T.IOCGWINSZ, @ptrToInt(&ws));
if (std.os.errno(err) != .SUCCESS) {
return error.IoctlError;
}
return TermSize{
.width = ws.ws_col,
.height = ws.ws_row,
};
}
test "entering stdin raw mode" {
const stdin = io.getStdIn();
var term = try enableRawMode(stdin.handle, .blocking); // stdin.handle is the same as os.STDIN_FILENO
defer term.disableRawMode() catch {};
} | src/term.zig |
const std = @import("std");
const builtin = @import("builtin");
const testing = std.testing;
const root = @import("root");
pub const UnicodeMode = enum { ansi, wide, unspecified };
// WORKAROUND: https://github.com/ziglang/zig/issues/7979
// using root.UNICODE causes an erroneous dependency loop, so I'm hardcoding to .wide for now
pub const unicode_mode = UnicodeMode.wide;
//pub const unicode_mode : UnicodeMode = if (@hasDecl(root, "UNICODE")) (if (root.UNICODE) .wide else .ansi) else .unspecified;
pub const L = std.unicode.utf8ToUtf16LeStringLiteral;
pub usingnamespace switch (unicode_mode) {
.ansi => struct {
pub const TCHAR = u8;
pub fn _T(comptime str: []const u8) *const [str.len:0]u8 { return str; }
},
.wide => struct {
pub const TCHAR = u16;
pub const _T = L;
},
.unspecified => if (builtin.is_test) struct { } else struct {
pub const TCHAR = @compileError("'TCHAR' requires that UNICODE be set to true or false in the root module");
pub const _T = @compileError("'_T' requires that UNICODE be set to true or false in the root module");
},
};
pub const Arch = enum { X86, X64, Arm64 };
pub const arch: Arch = switch (builtin.target.cpu.arch) {
.i386 => .X86,
.x86_64 => .X64,
.arm, .armeb => .Arm64,
else => @compileError("unable to determine win32 arch"),
};
// TODO: this should probably be in the standard lib somewhere?
pub const Guid = extern union {
Ints: extern struct {
a: u32,
b: u16,
c: u16,
d: [8]u8,
},
Bytes: [16]u8,
const big_endian_hex_offsets = [16] u6 {0, 2, 4, 6, 9, 11, 14, 16, 19, 21, 24, 26, 28, 30, 32, 34};
const little_endian_hex_offsets = [16] u6 {
6, 4, 2, 0,
11, 9,
16, 14,
19, 21, 24, 26, 28, 30, 32, 34};
const hex_offsets = switch (builtin.target.cpu.arch.endian()) {
.Big => big_endian_hex_offsets,
.Little => little_endian_hex_offsets,
};
pub fn initString(s: []const u8) Guid {
var guid = Guid { .Bytes = undefined };
for (hex_offsets) |hex_offset, i| {
//guid.Bytes[i] = decodeHexByte(s[offset..offset+2]);
guid.Bytes[i] = decodeHexByte([2]u8 { s[hex_offset], s[hex_offset+1] });
}
return guid;
}
};
comptime { std.debug.assert(@sizeOf(Guid) == 16); }
// TODO: is this in the standard lib somewhere?
fn hexVal(c: u8) u4 {
if (c <= '9') return @intCast(u4, c - '0');
if (c >= 'a') return @intCast(u4, c + 10 - 'a');
return @intCast(u4, c + 10 - 'A');
}
// TODO: is this in the standard lib somewhere?
fn decodeHexByte(hex: [2]u8) u8 {
return @intCast(u8, hexVal(hex[0])) << 4 | hexVal(hex[1]);
}
test "Guid" {
try testing.expect(std.mem.eql(u8,
switch (builtin.target.cpu.arch.endian()) {
.Big => "\x01\x23\x45\x67\x89\xAB\xEF\x10\x32\x54\x76\x98\xba\xdc\xfe\x91",
.Little => "\x67\x45\x23\x01\xAB\x89\x10\xEF\x32\x54\x76\x98\xba\xdc\xfe\x91"
},
&Guid.initString("01234567-89AB-EF10-3254-7698badcfe91").Bytes));
}
pub const PropertyKey = extern struct {
fmtid: Guid,
pid: u32,
pub fn init(fmtid: []const u8, pid: u32) PropertyKey {
return .{
.fmtid = Guid.initString(fmtid),
.pid = pid,
};
}
};
pub fn FAILED(hr: @import("foundation.zig").HRESULT) bool {
return hr < 0;
}
pub fn SUCCEEDED(hr: @import("foundation.zig").HRESULT) bool {
return hr >= 0;
}
// These constants were removed from the metadata to allow each projection
// to define them however they like (see https://github.com/microsoft/win32metadata/issues/530)
pub const FALSE : @import("foundation.zig").BOOL = 0;
pub const TRUE : @import("foundation.zig").BOOL = 1;
/// Converts comptime values to the given type.
/// Note that this function is called at compile time rather than converting constant values earlier at code generation time.
/// The reason for doing it a compile time is because genzig.zig generates all constants as they are encountered which can
/// be before it knows the constant's type definition, so we delay the convession to compile-time where the compiler knows
/// all type definition.
pub fn typedConst(comptime T: type, comptime value: anytype) T {
return typedConst2(T, T, value);
}
pub fn typedConst2(comptime ReturnType: type, comptime SwitchType: type, comptime value: anytype) ReturnType {
const target_type_error = @as([]const u8, "typedConst cannot convert to " ++ @typeName(ReturnType));
const value_type_error = @as([]const u8, "typedConst cannot convert " ++ @typeName(@TypeOf(value)) ++ " to " ++ @typeName(ReturnType));
switch (@typeInfo(SwitchType)) {
.Int => |target_type_info| {
if (value >= std.math.maxInt(SwitchType)) {
if (target_type_info.signedness == .signed) {
const UnsignedT = @Type(std.builtin.TypeInfo { .Int = .{ .signedness = .unsigned, .bits = target_type_info.bits }});
return @bitCast(SwitchType, @as(UnsignedT, value));
}
}
return value;
},
.Pointer => |target_type_info| switch (target_type_info.size) {
.One, .Many, .C => {
switch (@typeInfo(@TypeOf(value))) {
.ComptimeInt, .Int => {
const usize_value = if (value >= 0) value else @bitCast(usize, @as(isize, value));
return @intToPtr(ReturnType, usize_value);
},
else => @compileError(value_type_error),
}
},
else => target_type_error,
},
.Optional => |target_type_info| switch(@typeInfo(target_type_info.child)) {
.Pointer => return typedConst2(ReturnType, target_type_info.child, value),
else => target_type_error,
},
.Enum => |_| switch(@typeInfo(@TypeOf(value))) {
.Int => return @intToEnum(ReturnType, value),
else => target_type_error,
},
else => @compileError(target_type_error),
}
}
test "typedConst" {
try testing.expectEqual(@bitCast(usize, @as(isize, -1)), @ptrToInt(typedConst(?*opaque{}, -1)));
try testing.expectEqual(@bitCast(usize, @as(isize, -12)), @ptrToInt(typedConst(?*opaque{}, -12)));
try testing.expectEqual(@as(u32, 0xffffffff), typedConst(u32, 0xffffffff));
try testing.expectEqual(@bitCast(i32, @as(u32, 0x80000000)), typedConst(i32, 0x80000000));
} | win32/zig.zig |
const std = @import("std");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator;
const meta_size = 2 * @sizeOf(usize);
const min_payload_size = meta_size;
const min_frame_size = meta_size + min_payload_size;
const jumbo_index = 0;
const page_index = 1;
pub const ZeeAllocDefaults = ZeeAlloc(Config{});
pub const Config = struct {
/// ZeeAlloc will request a multiple of `page_size` from the backing allocator.
/// **Must** be a power of two.
page_size: usize = std.math.max(std.mem.page_size, 65536), // 64K ought to be enough for everybody
validation: Validation = .External,
jumbo_match_strategy: JumboMatchStrategy = .Closest,
buddy_strategy: BuddyStrategy = .Fast,
shrink_strategy: ShrinkStrategy = .Defer,
pub const JumboMatchStrategy = enum {
/// Use the frame that wastes the least space
/// Scans the entire jumbo freelist, which is slower but keeps memory pretty tidy
Closest,
/// Use only exact matches
/// -75 bytes vs `.Closest`
/// Similar performance to Closest if allocation sizes are consistent throughout lifetime
Exact,
/// Use the first frame that fits
/// -75 bytes vs `.Closest`
/// Initially faster to allocate but causes major fragmentation issues
First,
};
pub const BuddyStrategy = enum {
/// Return the raw free frame immediately
/// Generally faster because it does not recombine or resplit frames,
/// but it also requires more underlying memory
Fast,
/// Recombine with free buddies to reclaim storage
/// +153 bytes vs `.Fast`
/// More efficient use of existing memory at the cost of cycles and bytes
Coalesce,
};
pub const ShrinkStrategy = enum {
/// Return a smaller view into the same frame
/// Faster because it ignores shrink, but never reclaims space until freed
Defer,
/// Split the frame into smallest usable chunk
/// +112 bytes vs `.Defer`
/// Better at reclaiming non-jumbo memory, but never reclaims jumbo until freed
Chunkify,
};
pub const Validation = enum {
/// Enable all validations, including library internals
Dev,
/// Only validate external boundaries — e.g. `realloc` or `free`
External,
/// Turn off all validations — pretend this library is `--release-small`
Unsafe,
fn useInternal(comptime self: Validation) bool {
if (builtin.mode == .Debug) {
return true;
}
return self == .Dev;
}
fn useExternal(comptime self: Validation) bool {
return switch (builtin.mode) {
.Debug => true,
.ReleaseSafe => self == .Dev or self == .External,
else => false,
};
}
fn assertInternal(comptime self: Validation, ok: bool) void {
@setRuntimeSafety(comptime self.useInternal());
if (!ok) unreachable;
}
fn assertExternal(comptime self: Validation, ok: bool) void {
@setRuntimeSafety(comptime self.useExternal());
if (!ok) unreachable;
}
};
};
pub fn ZeeAlloc(comptime conf: Config) type {
std.debug.assert(conf.page_size >= std.mem.page_size);
std.debug.assert(std.math.isPowerOfTwo(conf.page_size));
const inv_bitsize_ref = page_index + std.math.log2_int(usize, conf.page_size);
const size_buckets = inv_bitsize_ref - std.math.log2_int(usize, min_frame_size) + 1; // + 1 jumbo list
return struct {
const Self = @This();
const config = conf;
// Synthetic representation -- should not be created directly, but instead carved out of []u8 bytes
const Frame = packed struct {
const alignment = 2 * @sizeOf(usize);
const allocated_signal = @intToPtr(*Frame, std.math.maxInt(usize));
next: ?*Frame,
frame_size: usize,
// We can't embed arbitrarily sized arrays in a struct so stick a placeholder here
payload: [min_payload_size]u8,
fn isCorrectSize(memsize: usize) bool {
return memsize >= min_frame_size and (memsize % conf.page_size == 0 or std.math.isPowerOfTwo(memsize));
}
pub fn init(raw_bytes: []u8) *Frame {
@setRuntimeSafety(comptime conf.validation.useInternal());
const node = @ptrCast(*Frame, raw_bytes.ptr);
node.frame_size = raw_bytes.len;
node.validate() catch unreachable;
return node;
}
pub fn restoreAddr(addr: usize) *Frame {
@setRuntimeSafety(comptime conf.validation.useInternal());
const node = @intToPtr(*Frame, addr);
node.validate() catch unreachable;
return node;
}
pub fn restorePayload(payload: [*]u8) !*Frame {
@setRuntimeSafety(comptime conf.validation.useInternal());
const node = @fieldParentPtr(Frame, "payload", @ptrCast(*[min_payload_size]u8, payload));
try node.validate();
return node;
}
pub fn validate(self: *Frame) !void {
if (@ptrToInt(self) % alignment != 0) {
return error.UnalignedMemory;
}
if (!Frame.isCorrectSize(self.frame_size)) {
return error.UnalignedMemory;
}
}
pub fn isAllocated(self: *Frame) bool {
return self.next == allocated_signal;
}
pub fn markAllocated(self: *Frame) void {
self.next = allocated_signal;
}
pub fn payloadSize(self: *Frame) usize {
@setRuntimeSafety(comptime conf.validation.useInternal());
return self.frame_size - meta_size;
}
pub fn payloadSlice(self: *Frame, start: usize, end: usize) []u8 {
@setRuntimeSafety(comptime conf.validation.useInternal());
conf.validation.assertInternal(start <= end);
conf.validation.assertInternal(end <= self.payloadSize());
const ptr = @ptrCast([*]u8, &self.payload);
return ptr[start..end];
}
};
const FreeList = packed struct {
first: ?*Frame,
pub fn init() FreeList {
return FreeList{ .first = null };
}
pub fn root(self: *FreeList) *Frame {
// Due to packed struct layout, FreeList.first == Frame.next
// This enables more graceful iteration without needing a back reference.
// Since this is not a full frame, accessing any other field will corrupt memory.
// Thar be dragons 🐉
return @ptrCast(*Frame, self);
}
pub fn prepend(self: *FreeList, node: *Frame) void {
node.next = self.first;
self.first = node;
}
pub fn remove(self: *FreeList, target: *Frame) !void {
var iter = self.root();
while (iter.next) |next| : (iter = next) {
if (next == target) {
_ = self.removeAfter(iter);
return;
}
}
return error.ElementNotFound;
}
pub fn removeAfter(self: *FreeList, ref: *Frame) *Frame {
const next_node = ref.next.?;
ref.next = next_node.next;
return next_node;
}
};
/// The definitive™ way of using `ZeeAlloc`
pub const wasm_allocator = &_wasm.allocator;
var _wasm = init(&wasm_page_allocator);
backing_allocator: *Allocator,
free_lists: [size_buckets]FreeList = [_]FreeList{FreeList.init()} ** size_buckets,
allocator: Allocator = Allocator{
.allocFn = alloc,
.resizeFn = resize,
},
pub fn init(backing_allocator: *Allocator) Self {
return Self{ .backing_allocator = backing_allocator };
}
fn allocNode(self: *Self, memsize: usize) !*Frame {
@setRuntimeSafety(comptime conf.validation.useInternal());
const alloc_size = unsafeAlignForward(memsize + meta_size);
const rawData = try self.backing_allocator.allocFn(self.backing_allocator, alloc_size, conf.page_size, 0, 0);
return Frame.init(rawData);
}
fn findFreeNode(self: *Self, memsize: usize) ?*Frame {
@setRuntimeSafety(comptime conf.validation.useInternal());
var search_size = self.padToFrameSize(memsize);
while (true) : (search_size *= 2) {
const i = self.freeListIndex(search_size);
var free_list = &self.free_lists[i];
var closest_match_prev: ?*Frame = null;
var closest_match_size: usize = std.math.maxInt(usize);
var iter = free_list.root();
while (iter.next) |next| : (iter = next) {
switch (conf.jumbo_match_strategy) {
.Exact => {
if (next.frame_size == search_size) {
return free_list.removeAfter(iter);
}
},
.Closest => {
if (next.frame_size == search_size) {
return free_list.removeAfter(iter);
} else if (next.frame_size > search_size and next.frame_size < closest_match_size) {
closest_match_prev = iter;
closest_match_size = next.frame_size;
}
},
.First => {
if (next.frame_size >= search_size) {
return free_list.removeAfter(iter);
}
},
}
}
if (closest_match_prev) |prev| {
return free_list.removeAfter(prev);
}
if (i <= page_index) {
return null;
}
}
}
fn chunkify(self: *Self, node: *Frame, target_size: usize, len_align: u29) usize {
@setCold(config.shrink_strategy != .Defer);
@setRuntimeSafety(comptime conf.validation.useInternal());
conf.validation.assertInternal(target_size <= node.payloadSize());
if (node.frame_size <= conf.page_size) {
const target_frame_size = self.padToFrameSize(target_size);
var sub_frame_size = node.frame_size / 2;
while (sub_frame_size >= target_frame_size) : (sub_frame_size /= 2) {
const start = node.payloadSize() - sub_frame_size;
const sub_frame_data = node.payloadSlice(start, node.payloadSize());
const sub_node = Frame.init(sub_frame_data);
self.freeListOfSize(sub_frame_size).prepend(sub_node);
node.frame_size = sub_frame_size;
}
}
return std.mem.alignAllocLen(node.payloadSize(), target_size, len_align);
}
fn free(self: *Self, target: *Frame) void {
@setCold(true);
@setRuntimeSafety(comptime conf.validation.useInternal());
var node = target;
if (conf.buddy_strategy == .Coalesce) {
while (node.frame_size < conf.page_size) : (node.frame_size *= 2) {
// 16: [0, 16], [32, 48]
// 32: [0, 32], [64, 96]
const node_addr = @ptrToInt(node);
const buddy_addr = node_addr ^ node.frame_size;
const buddy = Frame.restoreAddr(buddy_addr);
if (buddy.isAllocated() or buddy.frame_size != node.frame_size) {
break;
}
self.freeListOfSize(buddy.frame_size).remove(buddy) catch unreachable;
// Use the lowest address as the new root
node = Frame.restoreAddr(node_addr & buddy_addr);
}
}
self.freeListOfSize(node.frame_size).prepend(node);
}
// https://github.com/ziglang/zig/issues/2426
fn unsafeCeilPowerOfTwo(comptime T: type, value: T) T {
@setRuntimeSafety(comptime conf.validation.useInternal());
if (value <= 2) return value;
const Shift = comptime std.math.Log2Int(T);
return @as(T, 1) << @intCast(Shift, @bitSizeOf(T) - @clz(T, value - 1));
}
fn unsafeLog2Int(comptime T: type, x: T) std.math.Log2Int(T) {
@setRuntimeSafety(comptime conf.validation.useInternal());
conf.validation.assertInternal(x != 0);
return @intCast(std.math.Log2Int(T), @bitSizeOf(T) - 1 - @clz(T, x));
}
fn unsafeAlignForward(size: usize) usize {
@setRuntimeSafety(comptime conf.validation.useInternal());
const forward = size + (conf.page_size - 1);
return forward & ~(conf.page_size - 1);
}
fn padToFrameSize(self: *Self, memsize: usize) usize {
@setRuntimeSafety(comptime conf.validation.useInternal());
const meta_memsize = std.math.max(memsize + meta_size, min_frame_size);
return std.math.min(unsafeCeilPowerOfTwo(usize, meta_memsize), unsafeAlignForward(meta_memsize));
// More byte-efficient of this:
// const meta_memsize = memsize + meta_size;
// if (meta_memsize <= min_frame_size) {
// return min_frame_size;
// } else if (meta_memsize < conf.page_size) {
// return ceilPowerOfTwo(usize, meta_memsize);
// } else {
// return std.mem.alignForward(meta_memsize, conf.page_size);
// }
}
fn freeListOfSize(self: *Self, frame_size: usize) *FreeList {
@setRuntimeSafety(comptime conf.validation.useInternal());
const i = self.freeListIndex(frame_size);
return &self.free_lists[i];
}
fn freeListIndex(self: *Self, frame_size: usize) usize {
@setRuntimeSafety(comptime conf.validation.useInternal());
conf.validation.assertInternal(Frame.isCorrectSize(frame_size));
return inv_bitsize_ref - std.math.min(inv_bitsize_ref, unsafeLog2Int(usize, frame_size));
// More byte-efficient of this:
// if (frame_size > conf.page_size) {
// return jumbo_index;
// } else if (frame_size <= min_frame_size) {
// return self.free_lists.len - 1;
// } else {
// return inv_bitsize_ref - unsafeLog2Int(usize, frame_size);
// }
}
fn alloc(allocator: *Allocator, n: usize, ptr_align: u29, len_align: u29, ret_addr: usize) Allocator.Error![]u8 {
const self = @fieldParentPtr(Self, "allocator", allocator);
if (ptr_align > min_frame_size) {
return error.OutOfMemory;
}
const node = self.findFreeNode(n) orelse try self.allocNode(n);
node.markAllocated();
const len = self.chunkify(node, n, len_align);
return node.payloadSlice(0, len);
}
fn resize(allocator: *Allocator, buf: []u8, buf_align: u29, new_size: usize, len_align: u29, ret_addr: usize) Allocator.Error!usize {
const self = @fieldParentPtr(Self, "allocator", allocator);
@setRuntimeSafety(comptime conf.validation.useExternal());
const node = Frame.restorePayload(buf.ptr) catch unreachable;
conf.validation.assertExternal(node.isAllocated());
if (new_size == 0) {
self.free(node);
return 0;
} else if (new_size > node.payloadSize()) {
return error.OutOfMemory;
} else switch (conf.shrink_strategy) {
.Defer => return new_size,
.Chunkify => return self.chunkify(node, new_size, len_align),
}
}
fn debugCount(self: *Self, index: usize) usize {
var count: usize = 0;
var iter = self.free_lists[index].first;
while (iter) |node| : (iter = node.next) {
count += 1;
}
return count;
}
fn debugCountAll(self: *Self) usize {
var count: usize = 0;
for (self.free_lists) |_, i| {
count += self.debugCount(i);
}
return count;
}
fn debugDump(self: *Self) void {
for (self.free_lists) |_, i| {
std.debug.warn("{}: {}\n", i, self.debugCount(i));
}
}
};
}
fn assertIf(comptime run_assert: bool, ok: bool) void {
@setRuntimeSafety(run_assert);
if (!ok) unreachable;
}
var wasm_page_allocator = init: {
if (builtin.cpu.arch != .wasm32) {
@compileError("wasm allocator is only available for wasm32 arch");
}
// std.heap.WasmPageAllocator is designed for reusing pages
// We never free, so this lets us stay super small
const WasmPageAllocator = struct {
fn alloc(allocator: *Allocator, n: usize, alignment: u29, len_align: u29, ret_addr: usize) Allocator.Error![]u8 {
const is_debug = builtin.mode == .Debug;
@setRuntimeSafety(is_debug);
assertIf(is_debug, n % std.mem.page_size == 0); // Should only be allocating page size chunks
assertIf(is_debug, alignment % std.mem.page_size == 0); // Should only align to page_size increments
const requested_page_count = @intCast(u32, n / std.mem.page_size);
const prev_page_count = @wasmMemoryGrow(0, requested_page_count);
if (prev_page_count < 0) {
return error.OutOfMemory;
}
const start_ptr = @intToPtr([*]u8, @intCast(usize, prev_page_count) * std.mem.page_size);
return start_ptr[0..n];
}
};
break :init Allocator{
.allocFn = WasmPageAllocator.alloc,
.resizeFn = undefined, // Shouldn't be shrinking / freeing
};
};
pub const ExportC = struct {
allocator: *std.mem.Allocator,
malloc: bool = true,
free: bool = true,
calloc: bool = false,
realloc: bool = false,
pub fn run(comptime conf: ExportC) void {
const Funcs = struct {
fn malloc(size: usize) callconv(.C) ?*c_void {
if (size == 0) {
return null;
}
//const result = conf.allocator.alloc(u8, size) catch return null;
const result = conf.allocator.allocFn(conf.allocator, size, 1, 1, 0) catch return null;
return result.ptr;
}
fn calloc(num_elements: usize, element_size: usize) callconv(.C) ?*c_void {
const size = num_elements *% element_size;
const c_ptr = @call(.{ .modifier = .never_inline }, malloc, .{size});
if (c_ptr) |ptr| {
const p = @ptrCast([*]u8, ptr);
@memset(p, 0, size);
}
return c_ptr;
}
fn realloc(c_ptr: ?*c_void, new_size: usize) callconv(.C) ?*c_void {
if (new_size == 0) {
@call(.{ .modifier = .never_inline }, free, .{c_ptr});
return null;
} else if (c_ptr) |ptr| {
// Use a synthetic slice
const p = @ptrCast([*]u8, ptr);
const result = conf.allocator.realloc(p[0..1], new_size) catch return null;
return @ptrCast(*c_void, result.ptr);
} else {
return @call(.{ .modifier = .never_inline }, malloc, .{new_size});
}
}
fn free(c_ptr: ?*c_void) callconv(.C) void {
if (c_ptr) |ptr| {
// Use a synthetic slice. zee_alloc will free via corresponding metadata.
const p = @ptrCast([*]u8, ptr);
//conf.allocator.free(p[0..1]);
_ = conf.allocator.resizeFn(conf.allocator, p[0..1], 0, 0, 0, 0) catch unreachable;
}
}
};
if (conf.malloc) {
@export(Funcs.malloc, .{ .name = "malloc" });
}
if (conf.calloc) {
@export(Funcs.calloc, .{ .name = "calloc" });
}
if (conf.realloc) {
@export(Funcs.realloc, .{ .name = "realloc" });
}
if (conf.free) {
@export(Funcs.free, .{ .name = "free" });
}
}
};
// Tests
const testing = std.testing;
test "ZeeAlloc helpers" {
var buf: [0]u8 = undefined;
var fixed_buffer_allocator = std.heap.FixedBufferAllocator.init(buf[0..]);
var zee_alloc = ZeeAllocDefaults.init(&fixed_buffer_allocator.allocator);
const page_size = ZeeAllocDefaults.config.page_size;
// freeListIndex
{
testing.expectEqual(zee_alloc.freeListIndex(page_size), page_index);
testing.expectEqual(zee_alloc.freeListIndex(page_size / 2), page_index + 1);
testing.expectEqual(zee_alloc.freeListIndex(page_size / 4), page_index + 2);
}
// padToFrameSize
{
testing.expectEqual(zee_alloc.padToFrameSize(page_size - meta_size), page_size);
testing.expectEqual(zee_alloc.padToFrameSize(page_size), 2 * page_size);
testing.expectEqual(zee_alloc.padToFrameSize(page_size - meta_size + 1), 2 * page_size);
testing.expectEqual(zee_alloc.padToFrameSize(2 * page_size), 3 * page_size);
}
}
test "ZeeAlloc internals" {
var buf: [1000000]u8 = undefined;
// node count makes sense
{
var fixed_buffer_allocator = std.heap.FixedBufferAllocator.init(buf[0..]);
var zee_alloc = ZeeAllocDefaults.init(&fixed_buffer_allocator.allocator);
testing.expectEqual(zee_alloc.debugCountAll(), 0);
var small1 = try zee_alloc.allocator.create(u8);
var prev_free_nodes = zee_alloc.debugCountAll();
testing.expect(prev_free_nodes > 0);
var small2 = try zee_alloc.allocator.create(u8);
testing.expectEqual(zee_alloc.debugCountAll(), prev_free_nodes - 1);
prev_free_nodes = zee_alloc.debugCountAll();
var big1 = try zee_alloc.allocator.alloc(u8, 127 * 1024);
testing.expectEqual(zee_alloc.debugCountAll(), prev_free_nodes);
zee_alloc.allocator.free(big1);
testing.expectEqual(zee_alloc.debugCountAll(), prev_free_nodes + 1);
testing.expectEqual(zee_alloc.debugCount(jumbo_index), 1);
}
// BuddyStrategy = Coalesce
{
var fixed_buffer_allocator = std.heap.FixedBufferAllocator.init(buf[0..]);
var zee_alloc = ZeeAlloc(Config{ .buddy_strategy = .Coalesce }).init(&fixed_buffer_allocator.allocator);
var small = try zee_alloc.allocator.create(u8);
testing.expect(zee_alloc.debugCountAll() > 1);
zee_alloc.allocator.destroy(small);
testing.expectEqual(zee_alloc.debugCountAll(), 1);
}
// realloc reuses frame if possible
{
var fixed_buffer_allocator = std.heap.FixedBufferAllocator.init(buf[0..]);
var zee_alloc = ZeeAllocDefaults.init(&fixed_buffer_allocator.allocator);
const orig = try zee_alloc.allocator.alloc(u8, 1);
const addr = orig.ptr;
var i: usize = 2;
while (i <= min_payload_size) : (i += 1) {
var re = try zee_alloc.allocator.realloc(orig, i);
testing.expectEqual(re.ptr, addr);
}
}
// allocated_signal
{
var fixed_buffer_allocator = std.heap.FixedBufferAllocator.init(buf[0..]);
var zee_alloc = ZeeAllocDefaults.init(&fixed_buffer_allocator.allocator);
const payload = try zee_alloc.allocator.alloc(u8, 1);
const frame = try ZeeAllocDefaults.Frame.restorePayload(payload.ptr);
testing.expect(frame.isAllocated());
zee_alloc.allocator.free(payload);
testing.expect(!frame.isAllocated());
}
}
// -- functional tests from std/heap.zig
fn testAllocator(allocator: *std.mem.Allocator) !void {
var slice = try allocator.alloc(*i32, 100);
testing.expectEqual(slice.len, 100);
for (slice) |*item, i| {
item.* = try allocator.create(i32);
item.*.* = @intCast(i32, i);
}
slice = try allocator.realloc(slice, 20000);
testing.expectEqual(slice.len, 20000);
for (slice[0..100]) |item, i| {
testing.expectEqual(item.*, @intCast(i32, i));
allocator.destroy(item);
}
slice = allocator.shrink(slice, 50);
testing.expectEqual(slice.len, 50);
slice = allocator.shrink(slice, 25);
testing.expectEqual(slice.len, 25);
slice = allocator.shrink(slice, 0);
testing.expectEqual(slice.len, 0);
slice = try allocator.realloc(slice, 10);
testing.expectEqual(slice.len, 10);
allocator.free(slice);
}
fn testAllocatorAligned(allocator: *Allocator, comptime alignment: u29) !void {
// initial
var slice = try allocator.alignedAlloc(u8, alignment, 10);
testing.expectEqual(slice.len, 10);
// grow
slice = try allocator.realloc(slice, 100);
testing.expectEqual(slice.len, 100);
// shrink
slice = allocator.shrink(slice, 10);
testing.expectEqual(slice.len, 10);
// go to zero
slice = allocator.shrink(slice, 0);
testing.expectEqual(slice.len, 0);
// realloc from zero
slice = try allocator.realloc(slice, 100);
testing.expectEqual(slice.len, 100);
// shrink with shrink
slice = allocator.shrink(slice, 10);
testing.expectEqual(slice.len, 10);
// shrink to zero
slice = allocator.shrink(slice, 0);
testing.expectEqual(slice.len, 0);
}
fn testAllocatorLargeAlignment(allocator: *Allocator) Allocator.Error!void {
//Maybe a platform's page_size is actually the same as or
// very near usize?
// TODO: support ultra wide alignment (bigger than page_size)
//if (std.mem.page_size << 2 > std.math.maxInt(usize)) return;
//const USizeShift = @IntType(false, std.math.log2(usize.bit_count));
//const large_align = u29(std.mem.page_size << 2);
const USizeShift = @IntType(false, std.math.log2(usize.bit_count));
const large_align: u29 = std.mem.page_size;
var align_mask: usize = undefined;
_ = @shlWithOverflow(usize, ~@as(usize, 0), @as(USizeShift, @ctz(usize, large_align)), &align_mask);
var slice = try allocator.alignedAlloc(u8, large_align, 500);
testing.expectEqual(@ptrToInt(slice.ptr) & align_mask, @ptrToInt(slice.ptr));
slice = allocator.shrink(slice, 100);
testing.expectEqual(@ptrToInt(slice.ptr) & align_mask, @ptrToInt(slice.ptr));
slice = try allocator.realloc(slice, 5000);
testing.expectEqual(@ptrToInt(slice.ptr) & align_mask, @ptrToInt(slice.ptr));
slice = allocator.shrink(slice, 10);
testing.expectEqual(@ptrToInt(slice.ptr) & align_mask, @ptrToInt(slice.ptr));
slice = try allocator.realloc(slice, 20000);
testing.expectEqual(@ptrToInt(slice.ptr) & align_mask, @ptrToInt(slice.ptr));
allocator.free(slice);
}
fn testAllocatorAlignedShrink(allocator: *Allocator) Allocator.Error!void {
var debug_buffer: [1000]u8 = undefined;
const debug_allocator = &std.heap.FixedBufferAllocator.init(&debug_buffer).allocator;
const alloc_size = std.mem.page_size * 2 + 50;
var slice = try allocator.alignedAlloc(u8, 16, alloc_size);
defer allocator.free(slice);
var stuff_to_free = std.ArrayList([]align(16) u8).init(debug_allocator);
// On Windows, VirtualAlloc returns addresses aligned to a 64K boundary,
// which is 16 pages, hence the 32. This test may require to increase
// the size of the allocations feeding the `allocator` parameter if they
// fail, because of this high over-alignment we want to have.
while (@ptrToInt(slice.ptr) == std.mem.alignForward(@ptrToInt(slice.ptr), std.mem.page_size * 32)) {
try stuff_to_free.append(slice);
slice = try allocator.alignedAlloc(u8, 16, alloc_size);
}
while (stuff_to_free.popOrNull()) |item| {
allocator.free(item);
}
slice[0] = 0x12;
slice[60] = 0x34;
// realloc to a smaller size but with a larger alignment
slice = try allocator.alignedRealloc(slice, std.mem.page_size, alloc_size / 2);
testing.expectEqual(slice[0], 0x12);
testing.expectEqual(slice[60], 0x34);
}
test "ZeeAlloc with FixedBufferAllocator" {
var buf: [1000000]u8 = undefined;
var fixed_buffer_allocator = std.heap.FixedBufferAllocator.init(buf[0..]);
var zee_alloc = ZeeAllocDefaults.init(&fixed_buffer_allocator.allocator);
try testAllocator(&zee_alloc.allocator);
// try testAllocatorAligned(&zee_alloc.allocator, 8);
// try testAllocatorLargeAlignment(&zee_alloc.allocator);
// try testAllocatorAlignedShrink(&zee_alloc.allocator);
}
test "ZeeAlloc with PageAllocator" {
var zee_alloc = ZeeAllocDefaults.init(std.heap.page_allocator);
try testAllocator(&zee_alloc.allocator);
try testAllocatorAligned(&zee_alloc.allocator, 8);
// try testAllocatorLargeAlignment(&zee_alloc.allocator);
// try testAllocatorAlignedShrink(&zee_alloc.allocator);
} | src/main.zig |
const std = @import("std");
const testing = std.testing;
const expect = testing.expect;
const expectError = testing.expectError;
test "dereference pointer" {
comptime try testDerefPtr();
try testDerefPtr();
}
fn testDerefPtr() !void {
var x: i32 = 1234;
var y = &x;
y.* += 1;
try expect(x == 1235);
}
test "pointer arithmetic" {
var ptr: [*]const u8 = "abcd";
try expect(ptr[0] == 'a');
ptr += 1;
try expect(ptr[0] == 'b');
ptr += 1;
try expect(ptr[0] == 'c');
ptr += 1;
try expect(ptr[0] == 'd');
ptr += 1;
try expect(ptr[0] == 0);
ptr -= 1;
try expect(ptr[0] == 'd');
ptr -= 1;
try expect(ptr[0] == 'c');
ptr -= 1;
try expect(ptr[0] == 'b');
ptr -= 1;
try expect(ptr[0] == 'a');
}
test "double pointer parsing" {
comptime try expect(PtrOf(PtrOf(i32)) == **i32);
}
fn PtrOf(comptime T: type) type {
return *T;
}
test "implicit cast single item pointer to C pointer and back" {
var y: u8 = 11;
var x: [*c]u8 = &y;
var z: *u8 = x;
z.* += 1;
try expect(y == 12);
}
test "initialize const optional C pointer to null" {
const a: ?[*c]i32 = null;
try expect(a == null);
comptime try expect(a == null);
}
test "assigning integer to C pointer" {
var x: i32 = 0;
var y: i32 = 1;
var ptr: [*c]u8 = 0;
var ptr2: [*c]u8 = x;
var ptr3: [*c]u8 = 1;
var ptr4: [*c]u8 = y;
try expect(ptr == ptr2);
try expect(ptr3 == ptr4);
try expect(ptr3 > ptr and ptr4 > ptr2 and y > x);
try expect(1 > ptr and y > ptr2 and 0 < ptr3 and x < ptr4);
}
test "C pointer comparison and arithmetic" {
const S = struct {
fn doTheTest() !void {
var ptr1: [*c]u32 = 0;
var ptr2 = ptr1 + 10;
try expect(ptr1 == 0);
try expect(ptr1 >= 0);
try expect(ptr1 <= 0);
// expect(ptr1 < 1);
// expect(ptr1 < one);
// expect(1 > ptr1);
// expect(one > ptr1);
try expect(ptr1 < ptr2);
try expect(ptr2 > ptr1);
try expect(ptr2 >= 40);
try expect(ptr2 == 40);
try expect(ptr2 <= 40);
ptr2 -= 10;
try expect(ptr1 == ptr2);
}
};
try S.doTheTest();
comptime try S.doTheTest();
} | test/behavior/pointers.zig |
const root = @import("root");
const std = @import("std");
const config = @import("config.zig");
const io = std.io;
const os = std.os;
const system = os.system;
const assert = std.debug.assert;
const expect = std.testing.expect;
const print = std.debug.print;
const tcflag = system.tcflag_t;
const Allocator = *std.mem.Allocator;
pub const ESC: u8 = '\x1B';
pub const SEQ: u8 = '[';
pub const CLEAR_SCREEN = "\x1b[2J";
pub const CURSOR_HOME = "\x1b[H";
pub const CURSOR_HIDE = "\x1b[?25l";
pub const CURSOR_SHOW = "\x1b[?25h";
pub const RESET_MODE = "\x1b[0m";
pub const BRIGHT_MODE = "\x1b[1m";
pub const DIM_MODE = "\x1b[2m";
pub const UNDERSCORE_MODE = "\x1b[4m";
pub const BLINK_MODE = "\x1b[5m";
pub const REVERSE_MODE = "\x1b[7m";
pub const HIDDEN_MODE = "\x1b[8m";
pub const RESET_WRAP_MODE = "\x1b[?7l";
// Errors
const OOM = "Out of memory error";
const BO = "Buffer overflow error";
pub const Position = struct {
x: usize, y: usize,
};
pub fn bufWrite(data: []const u8, buf: []u8, index: usize) usize {
var di: usize = 0;
var bi: usize = index;
while(di < data.len and bi < buf.len) {
buf[bi] = data[di];
di += 1;
bi += 1;
}
return bi;
}
pub fn bufFillScreen(data: []const u8, buf: []u8, index: usize, width: usize, height: usize) usize {
var di: usize = 0;
var bi: usize = index;
var x: usize = 0;
var y: usize = 0;
var clear = false;
assert(buf.len > bi + width);
while (di < data.len and y < height) {
if (x < width) {
if (data[di] == '\n') {
clear = true;
}
if (clear) {
buf[bi] = ' ';
} else {
buf[bi] = data[di];
di+=1;
}
bi += 1;
x += 1;
} else {
y += 1;
if(clear or data[di] == '\n') {
clear = false;
x = 0;
}
di += 1;
}
}
while (y < height) : (y+=1) {
while (x < width) : (x+=1) {
buf[bi] = ' ';
bi+=1;
}
x = 0;
}
assert(buf.len > bi + width - x);
// clear tail of last line
while (x < width) {
buf[bi] = ' ';
bi += 1;
x += 1;
}
return bi;
}
pub fn bufWriteByte(byte: u8, buf: []u8, index: usize) usize {
buf[index] = byte;
return index + 1;
}
pub fn bufWriteRepeat(char: u8, count: usize, buf: []u8, index: usize) usize {
assert(buf.len >= index + count);
var i: usize = 0;
while(i < count) : (i+=1) {
buf[index + i] = char;
}
return index + i;
}
pub fn write(data: []const u8) void {
_ = io.getStdOut().writer().write(data) catch @panic("StdOut write(data) failed!");
}
pub fn writeByte(byte: u8) void {
_ = io.getStdOut().writer().writeByte(byte) catch @panic("StdOut write failed!");
}
pub fn bufCursor(pos: Position, buf: []u8, index: usize) usize {
assert(buf.len > index);
const written = std.fmt.bufPrint(buf[index..], "\x1b[{d};{d}H", .{ pos.y + 1, pos.x + 1}) catch @panic(BO);
return index + written.len;
}
pub fn setCursor(pos: Position, allocator: Allocator) void {
const out = std.fmt.allocPrint(allocator, "\x1b[{d};{d}H", .{ pos.y + 1, pos.x + 1}) catch @panic(OOM);
defer allocator.free(out);
write(out);
}
var orig_mode: system.termios = undefined;
/// timeout for read(): x/10 seconds, null means wait forever for input
pub fn rawMode(timeout: ?u8) void {
orig_mode = os.tcgetattr(os.STDIN_FILENO) catch |err| {
print("Error: {s}\n", .{err});
@panic("tcgetattr failed!");
};
var raw = orig_mode;
assert(&raw != &orig_mode); // ensure raw is a copy
raw.iflag &= ~(@as(tcflag, system.BRKINT) | @as(tcflag, system.ICRNL) | @as(tcflag, system.INPCK)
| @as(tcflag, system.ISTRIP) | @as(tcflag, system.IXON));
//raw.oflag &= ~(@as(tcflag, system.OPOST)); // turn of \n => \n\r
raw.cflag |= (@as(tcflag, system.CS8));
raw.lflag &= ~(@as(tcflag, system.ECHO) | @as(tcflag, system.ICANON) | @as(tcflag, system.IEXTEN) | @as(tcflag, system.ISIG));
if(timeout != null) {
raw.cc[system.V.MIN] = 0; // add timeout for read()
raw.cc[system.V.TIME] = timeout.?;// x/10 seconds
}
os.tcsetattr(os.STDIN_FILENO, .FLUSH, raw) catch |err| {
print("Error: {s}\n", .{err});
@panic("tcsetattr failed!");
};
}
pub fn cookedMode() void {
os.tcsetattr(os.STDIN_FILENO, .FLUSH, orig_mode) catch |err| {
print("Error: {s}\n", .{err});
@panic("tcsetattr failed!");
};
}
pub fn updateWindowSize() bool {
const ws = getWindowSize(io.getStdOut()) catch @panic("getWindowSize failed!");
const height = @as(*const u16, &ws.ws_row).*;
const width = @as(*const u16, &ws.ws_col).*;
var changed = false;
if (height != config.height) {
changed = true;
config.height = height;
}
if (width != config.width) {
changed = true;
config.width = width;
}
return changed;
}
fn getWindowSize(fd: std.fs.File) !os.linux.winsize {
while (true) {
var size: os.linux.winsize = undefined;
const TIOCGWINSZ = 0x5413;
switch (os.errno(system.ioctl(fd.handle, TIOCGWINSZ, @ptrToInt(&size)))) {
.SUCCESS => return size,
.INTR => continue,
.BADF => unreachable,
.FAULT => unreachable,
.INVAL => return error.Unsupported,
.NOTTY => return error.Unsupported,
else => |err| return os.unexpectedErrno(err),
}
}
}
const stdin = std.io.getStdIn();
pub fn readKey() config.KeyCode {
var buf: [4]u8 = undefined;
const len = stdin.reader().read(&buf) catch |err| {
print("StdIn read() failed! error: {s}", .{err});
return config.KeyCode{ .data = buf, .len = 0 };
};
return config.KeyCode{ .data = buf, .len = len };
}
pub fn nonBlock() void {
const fl = os.fcntl(os.STDIN_FILENO, os.F.GETFL, 0) catch |err| {
print("Error: {s}\n", .{err});
@panic("fcntl(STDIN_FILENO, GETFL, 0) failed!");
};
_ = os.fcntl(os.STDIN_FILENO, os.F.SETFL, fl | os.O.NONBLOCK) catch |err| {
print("Error: {s}\n", .{err});
@panic("fcntl(STDIN_FILENO, SETFL, fl | NONBLOCK) failed!");
};
}
test "bufOptional" {
var buf = [_]u8{' ', ' '};
try expect(bufOptional(null, &buf, 0) == 0);
const index = bufOptional(090, &buf, 0);
try expect(index == 2);
try expect(equals("90", &buf));
}
/// writes the string version of given number, if number is null writes nothing.
inline fn bufOptional(number: ?u8, buf: []u8, index: usize) usize {
if (number == null) return index;
const result = std.fmt.bufPrint(buf[index..], "{d}", .{ number.? }) catch @panic(OOM);
return index + result.len;
}
/// return the string version of given number, if number is null: "" is returned.
/// Please call allocator.free(<returned_variable>) after usage.
inline fn optional(number: ?u8, allocator: Allocator) []u8 {
if (number == null) return "";
return std.fmt.allocPrint(allocator, "{d}", .{ number.? }) catch @panic(OOM);
}
test "optional" {
const test_allocator = std.testing.allocator;
try expect(optional(null, test_allocator).len == 0);
const opt = optional(007, test_allocator);
defer test_allocator.free(opt);
try expect(equals("7", opt));
}
fn equals(a: []const u8, b: []const u8) bool {
return std.mem.eql(u8, a, b);
}
pub const Mode = enum(u8) { reset = '0', bright = '1', dim = '2', underscore = '4', blink = '5',
reverse = '7', hidden = '8' };
pub const Color = enum(u8) { black = '0', red = '1', green = '2', yellow = '3', blue = '4',
magenta = '5', cyan = '6', white = '7' };
pub const Scope = enum(u8) { foreground = '3', background = '4', light_foreground = '9' };
const MODES = 'm';
pub fn bufMode(mode: Mode, buf: []u8, index: usize) usize {
buf[index] = ESC;
buf[index + 1] = SEQ;
buf[index + 2] = mode;
buf[index + 3] = MODES;
return index + 3;
}
pub fn setMode(mode: Mode, allocator: Allocator) void {
write(std.fmt.allocPrint(allocator, "\x1b[{d}m", .{ @enumToInt(mode) - '0' }) catch @panic(OOM));
}
pub fn bufAttributeMode(mode: ?Mode, scope: ?Scope, color: ?Color, buf: []u8, index: usize) usize {
assert(buf.len > 2);
var i = index;
buf[i] = ESC; i+=1;
buf[i] = SEQ; i+=1;
if(mode != null) {
buf[i] = @enumToInt(mode.?); i+=1;
if(scope != null and color != null) {
buf[i] = ';'; i+=1;
}
}
if(scope != null and color != null) {
buf[i] = @enumToInt(scope.?); i+=1;
buf[i] = @enumToInt(color.?); i+=1;
}
buf[i] = MODES; i+=1;
return i;
}
pub fn bufAttribute(scope: ?Scope, color: ?Color, buf: []u8, index: usize) usize {
var i = index;
buf[i] = ESC; i+=1;
buf[i] = SEQ; i+=1;
if(scope != null and color != null) {
buf[i] = @enumToInt(scope.?); i+=1;
buf[i] = @enumToInt(color.?); i+=1;
}
buf[i] = MODES; i+=1;
return i;
}
pub fn setAttributeMode(mode: ?Mode, scope: ?Scope, color: ?Color, allocator: Allocator) void {
var out = std.ArrayList(u8).init(allocator);
defer out.deinit();
out.append(ESC) catch @panic(OOM);
out.append(SEQ) catch @panic(OOM);
if(mode != null) {
out.append(@enumToInt(mode.?)) catch @panic(OOM);
if(scope != null and color != null) out.append(';') catch @panic(OOM);
}
if(scope != null and color != null) {
out.append(@enumToInt(scope.?)) catch @panic(OOM);
out.append(@enumToInt(color.?)) catch @panic(OOM);
}
out.append(MODES) catch @panic(OOM);
write(out.items);
}
pub fn bufAttributes(scopeA: ?Scope, colorA: ?Color, scopeB: ?Scope, colorB: ?Color, buf: []u8, index: usize) usize {
var i = bufAttribute(scopeA, colorA, buf, index) - 1; // skip mode here
if(scopeB != null and colorB != null) {
if(scopeA != null and colorA != null) {
buf[i] = ';'; i+=1;
}
buf[i] = @enumToInt(scopeB.?); i+=1;
buf[i] = @enumToInt(colorB.?); i+=1;
}
buf[i] = MODES; i+=1;
return i;
}
pub fn bufAttributesMode(mode: ?Mode, scopeA: ?Scope, colorA: ?Color, scopeB: ?Scope, colorB: ?Color, buf: []u8, index: usize) usize {
var i = bufAttributeMode(mode, scopeA, colorA, buf, index) - 1; // skip mode here
if(scopeB != null and colorB != null) {
buf[i] = @enumToInt(scopeB.?); i+=1;
buf[i] = @enumToInt(colorB.?); i+=1;
}
buf[i] = MODES; i+=1;
return i;
}
pub fn setAttributesMode(mode: ?Mode, scopeA: ?Scope, colorA: ?Color, scopeB: ?Scope, colorB: ?Color, allocator: Allocator) void {
var out = std.ArrayList(u8).init(allocator);
defer out.deinit();
out.append(ESC) catch @panic(OOM);
out.append(SEQ) catch @panic(OOM);
if(mode != null) {
out.append(@enumToInt(mode.?)) catch @panic(OOM);
if((scopeA != null and colorA != null) or (scopeB != null and colorB != null))
out.append(';') catch @panic(OOM);
}
if(scopeA != null and colorA != null) {
out.append(@enumToInt(scopeA.?)) catch @panic(OOM);
out.append(@enumToInt(colorA.?)) catch @panic(OOM);
if(scopeB != null and colorB != null) out.append(';') catch @panic(OOM);
}
if(scopeB != null and colorB != null) {
out.append(@enumToInt(scopeB.?)) catch @panic(OOM);
out.append(@enumToInt(colorB.?)) catch @panic(OOM);
}
out.append(MODES) catch @panic(OOM);
write(out.items);
} | libs/term.zig |
const std = @import("std");
const allocators = @import("allocators.zig");
const languages = @import("languages.zig");
const processor = @import("processor.zig");
const lua = @import("lua.zig");
const zlib = @import("zlib.zig");
const help_common = @embedFile("help-common.txt");
const help_verbose = @embedFile("help-verbose.txt");
const help_options = @embedFile("help-options.txt");
const help_exitcodes = @embedFile("help-exitcodes.txt");
var arg_arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const arg_alloc = arg_arena.allocator();
const global_alloc = allocators.global_arena.allocator();
const temp_alloc = allocators.temp_arena.allocator();
var option_verbose = false;
var option_quiet = false;
var option_test = false;
var option_show_version = false;
var option_show_help = false;
var option_verbose_help = false;
var option_recursive = false;
var option_dry_run = false;
var option_break_on_fail = false;
var depfile_path: ?[]const u8 = null;
var input_paths = std.ArrayList([]const u8).init(global_alloc);
var extensions = std.StringHashMap(void).init(global_alloc);
const ExitCode = packed struct {
unknown: bool = false,
bad_arg: bool = false,
bad_input: bool = false,
_: u5 = 0,
};
var exit_code = ExitCode{};
pub fn main() void {
run() catch {
if (@errorReturnTrace()) |trace| std.debug.dumpStackTrace(trace.*);
exit_code.unknown = true;
};
std.process.exit(@bitCast(u8, exit_code));
}
fn run() !void {
var args = std.process.args();
_ = try args.next(arg_alloc); // skip path to exe
while (try args.next(arg_alloc)) |arg| {
try processArg(arg, &args);
}
arg_arena.deinit();
if (option_test) {
return;
}
if (!option_show_help and !option_show_version and input_paths.items.len == 0) {
option_show_help = true;
option_show_version = true;
exit_code.bad_arg = true;
}
const stdout = std.io.getStdOut().writer();
if (option_show_version) {
_ = try stdout.write("LIMP 0.2.1 Copyright (C) 2011-2022 <NAME>\n");
try stdout.print("{s}\n", .{lua.c.LUA_COPYRIGHT});
try stdout.print("zlib {s} Copyright (C) 1995-2017 <NAME> and <NAME>\n", .{zlib.c.ZLIB_VERSION});
}
if (option_show_help) {
if (option_show_version) {
_ = try stdout.write("\n");
}
_ = try stdout.write(help_common);
if (option_verbose_help) {
_ = try stdout.write(help_verbose);
}
_ = try stdout.write(help_options);
if (option_verbose_help) {
_ = try stdout.write(help_exitcodes);
}
}
try languages.initDefaults();
try languages.load(option_verbose);
if (extensions.count() == 0) {
var it = languages.langs.keyIterator();
while (it.next()) |ext| {
if (ext.*.len > 0 and !std.mem.eql(u8, ext.*, "!!")) {
try extensions.put(ext.*, {});
}
}
}
var cwd = std.fs.cwd();
for (input_paths.items) |input_path| {
processInput(input_path, &cwd, true);
if (shouldStopProcessing()) break;
}
}
fn processInput(path: []const u8, within_dir: *std.fs.Dir, explicitly_requested: bool) void {
if (!processDir(path, within_dir)) processFile(path, within_dir, explicitly_requested);
}
fn processDir(path: []const u8, within_dir: *std.fs.Dir) bool {
return processDirInner(path, within_dir) catch |err| {
printUnexpectedPathError("searching directory", path, within_dir, err);
return true;
};
}
fn processDirInner(path: []const u8, within_dir: *std.fs.Dir) !bool {
var dir = within_dir.openDir(path, .{ .iterate = true }) catch |err| switch (err) {
error.NotDir => return false,
error.FileNotFound => {
printPathError("Directory or file not found", path, within_dir);
return true;
},
else => return err,
};
defer dir.close();
if (option_verbose) {
var real_path_buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined;
const real_path = within_dir.realpath(path, &real_path_buffer) catch path;
try std.io.getStdOut().writer().print("{s}: Searching for files...\n", .{real_path});
}
var iter = dir.iterate();
while (try iter.next()) |entry| {
switch (entry.kind) {
std.fs.Dir.Entry.Kind.File => {
processFile(entry.name, &dir, false);
},
std.fs.Dir.Entry.Kind.Directory => {
if (option_recursive) {
processInput(entry.name, &dir, false);
}
},
std.fs.Dir.Entry.Kind.SymLink => {
var symlink_buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined;
if (dir.readLink(entry.name, &symlink_buffer)) |new_path| {
if (option_recursive) {
processInput(new_path, &dir, false);
} else {
processFile(new_path, &dir, false);
}
} else |err| {
printUnexpectedPathError("reading link", entry.name, &dir, err);
}
},
else => {},
}
if (shouldStopProcessing()) return true;
}
return true;
}
fn processFile(path: []const u8, within_dir: *std.fs.Dir, explicitly_requested: bool) void {
processFileInner(path, within_dir, explicitly_requested) catch |err| {
printUnexpectedPathError("processing file", path, within_dir, err);
};
}
fn processFileInner(path: []const u8, within_dir: *std.fs.Dir, explicitly_requested: bool) !void {
var ext_lower_buf: [128]u8 = undefined;
var extension = std.fs.path.extension(path);
if (extension.len > 1 and extension[0] == '.') {
extension = extension[1..];
}
if (extension.len <= ext_lower_buf.len) {
extension = std.ascii.lowerString(&ext_lower_buf, extension);
}
if (!explicitly_requested and (extension.len == 0 or !extensions.contains(extension))) {
return;
}
allocators.temp_arena.reset(5 << 2) catch {};
var old_file_contents = within_dir.readFileAlloc(temp_alloc, path, 1 << 30) catch |err| {
switch (err) {
error.FileNotFound => {
if (explicitly_requested) {
printPathError("Not a file or directory", path, within_dir);
}
return;
},
else => {
printUnexpectedPathError("loading file", path, within_dir, err);
return;
},
}
};
const real_path = within_dir.realpathAlloc(temp_alloc, path) catch path;
var proc = processor.Processor.init(languages.get(extension), languages.getLimp());
try proc.parse(real_path, old_file_contents);
if (proc.isProcessable()) {
if (std.fs.path.dirname(real_path)) |dir| {
try std.os.chdir(dir);
}
switch (try proc.process()) {
.ignore => {
exit_code.bad_input = true;
},
.modified => {
if (option_dry_run) {
printPathStatus("Out of date", path, within_dir);
} else {
if (!option_quiet) {
printPathStatus("Rewriting", path, within_dir);
}
var af = try within_dir.atomicFile(path, .{});
defer af.deinit();
try proc.write(af.file.writer());
try af.finish();
}
},
.up_to_date => {
if (!option_quiet) {
printPathStatus("Up to date", path, within_dir);
}
},
}
// for (proc.parsed_sections.items) |section| {
// try section.debug();
// }
} else if (explicitly_requested) {
printPathStatus("Nothing to process", path, within_dir);
}
}
fn printPathStatus(detail: []const u8, path: []const u8, within_dir: *std.fs.Dir) void {
var real_path_buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined;
const real_path = within_dir.realpath(path, &real_path_buffer) catch path;
std.io.getStdOut().writer().print("{s}: {s}\n", .{ real_path, detail }) catch {};
exit_code.unknown = true;
}
fn printPathError(detail: []const u8, path: []const u8, within_dir: *std.fs.Dir) void {
var real_path_buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined;
const real_path = within_dir.realpath(path, &real_path_buffer) catch path;
std.io.getStdErr().writer().print("{s}: {s}\n", .{ real_path, detail }) catch {};
exit_code.unknown = true;
}
fn printUnexpectedPathError(where: []const u8, path: []const u8, within_dir: *std.fs.Dir, err: anyerror) void {
var real_path_buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined;
const real_path = within_dir.realpath(path, &real_path_buffer) catch path;
std.io.getStdErr().writer().print("{s}: Unexpected error {s}: {}\n", .{ real_path, where, err }) catch {};
exit_code.unknown = true;
}
fn shouldStopProcessing() bool {
return option_break_on_fail and (exit_code.unknown or exit_code.bad_input);
}
var check_option_args = true;
fn processArg(arg: []u8, args: *std.process.ArgIterator) !void {
if (check_option_args and arg.len > 0 and arg[0] == '-') {
if (arg.len > 1) {
if (arg[1] == '-') {
try processLongOption(arg, args);
} else {
for (arg[1..]) |c| try processShortOption(c, args);
}
return;
}
}
var path = try global_alloc.dupe(u8, arg);
try input_paths.append(path);
}
fn processLongOption(arg: []u8, args: *std.process.ArgIterator) !void {
if (arg.len == 2) {
check_option_args = false;
} else if (std.mem.eql(u8, arg, "--dry-run")) {
option_dry_run = true;
} else if (std.mem.eql(u8, arg, "--break-on-fail")) {
option_break_on_fail = true;
} else if (std.mem.eql(u8, arg, "--recursive")) {
option_recursive = true;
} else if (std.mem.eql(u8, arg, "--help")) {
option_show_help = true;
option_verbose_help = true;
} else if (std.mem.eql(u8, arg, "--version")) {
option_show_version = true;
} else if (std.mem.eql(u8, arg, "--test")) {
option_test = true;
} else if (std.mem.eql(u8, arg, "--verbose")) {
option_verbose = true;
} else if (std.mem.eql(u8, arg, "--quiet")) {
option_quiet = true;
} else if (std.mem.eql(u8, arg, "--extensions")) {
if (try args.next(arg_alloc)) |list| {
try processExtensionList(list);
} else {
_ = try std.io.getStdErr().writer().write("Expected extension list after --extensions\n");
exit_code.bad_arg = true;
}
} else if (std.mem.startsWith(u8, arg, "--extensions=")) {
try processExtensionList(arg["--extensions=".len..]);
} else if (std.mem.eql(u8, arg, "--depfile")) {
if (try args.next(global_alloc)) |path| {
depfile_path = path;
} else {
_ = try std.io.getStdErr().writer().write("Expected input directory path after --depfile\n");
exit_code.bad_arg = true;
}
} else if (std.mem.startsWith(u8, arg, "--depfile=")) {
depfile_path = try global_alloc.dupe(u8, arg["--depfile=".len..]);
} else {
try std.io.getStdErr().writer().print("Unrecognized option: {s}\n", .{arg});
exit_code.bad_arg = true;
}
}
fn processShortOption(c: u8, args: *std.process.ArgIterator) !void {
switch (c) {
'R' => option_recursive = true,
'n' => option_dry_run = true,
'b' => option_break_on_fail = true,
'v' => option_verbose = true,
'q' => option_quiet = true,
'V' => option_show_version = true,
'?' => option_show_help = true,
'x' => {
if (try args.next(arg_alloc)) |list| {
try processExtensionList(list);
} else {
_ = try std.io.getStdErr().writer().write("Expected extension list after -x\n");
exit_code.bad_arg = true;
}
},
else => {
var option = [_]u8{c};
try std.io.getStdErr().writer().print("Unrecognized option: -{s}\n", .{option});
exit_code.bad_arg = true;
},
}
}
fn processExtensionList(list: []const u8) !void {
var it = std.mem.split(u8, list, ",");
while (it.next()) |raw_ext| {
var ext = try if (raw_ext.len <= 128) std.ascii.allocLowerString(global_alloc, raw_ext) else global_alloc.dupe(u8, raw_ext);
try extensions.put(ext, {});
}
} | limp/main.zig |
const chipz = @import("chipz");
const std = @import("std");
const test_allocator = std.testing.allocator;
const expect_equal = std.testing.expectEqual;
const expect_equal_slices = std.testing.expectEqualSlices;
const expect = std.testing.expect;
test "clear screen" {
var emu = chipz.ChipZ.init(test_allocator);
emu.memory[1] = 0xE0;
emu.display[4][4] = true;
emu.cycle();
expect_equal(emu.display[4][4], false);
}
test "jump" {
var emu = chipz.ChipZ.init(test_allocator);
emu.memory[0] = 0x11;
emu.cycle();
expect_equal(emu.program_counter, 0x100);
}
test "set vx nn and add x nn" {
var emu = chipz.ChipZ.init(test_allocator);
emu.memory[0] = 0x6A;
emu.memory[1] = 0x12;
emu.memory[2] = 0x7A;
emu.memory[3] = 0x01;
emu.cycle();
expect_equal(emu.registers[0xA], 0x12);
emu.cycle();
expect_equal(emu.registers[0xA], 0x13);
}
test "set I" {
var emu = chipz.ChipZ.init(test_allocator);
emu.memory[0] = 0xA6;
emu.memory[1] = 0x66;
emu.cycle();
expect_equal(emu.index_register, 0x666);
}
test "display simple" {
var emu = chipz.ChipZ.init(test_allocator);
//setting up instruction
// drawing 3 height sprite at 0,0
emu.memory[0] = 0xD0;
emu.memory[1] = 0x03;
emu.memory[2] = 0xD0;
emu.memory[3] = 0x03;
// setting up sprite
emu.memory[0x200] = 0x3C;
emu.memory[0x201] = 0xC3;
emu.memory[0x202] = 0xFF;
emu.index_register = 0x200;
emu.cycle();
// 00111100
// 11000011
// 11111111
expect_equal(emu.display[0][0], false);
expect_equal(emu.display[1][0], false);
expect_equal(emu.display[2][0], true);
expect_equal(emu.display[3][0], true);
expect_equal(emu.display[4][0], true);
expect_equal(emu.display[5][0], true);
expect_equal(emu.display[6][0], false);
expect_equal(emu.display[7][0], false);
expect_equal(emu.display[0][1], true);
expect_equal(emu.display[1][1], true);
expect_equal(emu.display[2][1], false);
expect_equal(emu.display[3][1], false);
expect_equal(emu.display[4][1], false);
expect_equal(emu.display[5][1], false);
expect_equal(emu.display[6][1], true);
expect_equal(emu.display[7][1], true);
expect_equal(emu.display[1][2], true);
expect_equal(emu.display[2][2], true);
expect_equal(emu.display[3][2], true);
expect_equal(emu.display[4][2], true);
expect_equal(emu.display[5][2], true);
expect_equal(emu.display[6][2], true);
expect_equal(emu.display[7][2], true);
expect_equal(emu.registers[0xF], 0);
emu.cycle();
expect_equal(emu.display[0][0], false);
expect_equal(emu.display[1][0], false);
expect_equal(emu.display[2][0], false);
expect_equal(emu.display[3][0], false);
expect_equal(emu.display[4][0], false);
expect_equal(emu.display[5][0], false);
expect_equal(emu.display[6][0], false);
expect_equal(emu.display[7][0], false);
expect_equal(emu.display[0][1], false);
expect_equal(emu.display[1][1], false);
expect_equal(emu.display[2][1], false);
expect_equal(emu.display[3][1], false);
expect_equal(emu.display[4][1], false);
expect_equal(emu.display[5][1], false);
expect_equal(emu.display[6][1], false);
expect_equal(emu.display[7][1], false);
expect_equal(emu.display[1][2], false);
expect_equal(emu.display[2][2], false);
expect_equal(emu.display[3][2], false);
expect_equal(emu.display[4][2], false);
expect_equal(emu.display[5][2], false);
expect_equal(emu.display[6][2], false);
expect_equal(emu.display[7][2], false);
expect_equal(emu.registers[0xF], 1);
}
test "BCD conversion" {
var emu = chipz.ChipZ.init(test_allocator);
var program = [_]u8{0xF0, 0x33};
emu.load_program(&program);
emu.index_register = 0x500;
emu.registers[0] = 0x9C;
emu.cycle();
expect_equal(@intCast(u8, 6), emu.memory[0x502]);
expect_equal(@intCast(u8, 5), emu.memory[0x501]);
expect_equal(@intCast(u8, 1), emu.memory[0x500]);
}
test "bestcoder_rom" {
var emu = chipz.ChipZ.init(test_allocator);
var file_program = @embedFile("../demo_files/bc_test.ch8");
var program = [_]u8{0} ** file_program.len;
for (file_program) | byte, index | {
program[index] = byte;
}
emu.load_program(&program);
var index : usize = 0;
while (index < 500) : (index += 1) {
emu.cycle();
}
const ExpectedCoords = struct {
y: usize,
x: usize
};
const expected = [_]ExpectedCoords{
ExpectedCoords{ .y= 21, .x= 11},
ExpectedCoords{ .y= 22, .x= 11},
ExpectedCoords{ .y= 23, .x= 11},
ExpectedCoords{ .y= 24, .x= 11},
ExpectedCoords{ .y= 30, .x= 11},
ExpectedCoords{ .y= 31, .x= 11},
ExpectedCoords{ .y= 32, .x= 11},
ExpectedCoords{ .y= 33, .x= 11},
ExpectedCoords{ .y= 37, .x= 11},
ExpectedCoords{ .y= 42, .x= 11},
ExpectedCoords{ .y= 21, .x= 12},
ExpectedCoords{ .y= 25, .x= 12},
ExpectedCoords{ .y= 29, .x= 12},
ExpectedCoords{ .y= 34, .x= 12},
ExpectedCoords{ .y= 37, .x= 12},
ExpectedCoords{ .y= 38, .x= 12},
ExpectedCoords{ .y= 42, .x= 12},
ExpectedCoords{ .y= 21, .x= 13},
ExpectedCoords{ .y= 25, .x= 13},
ExpectedCoords{ .y= 29, .x= 13},
ExpectedCoords{ .y= 34, .x= 13},
ExpectedCoords{ .y= 37, .x= 13},
ExpectedCoords{ .y= 39, .x= 13},
ExpectedCoords{ .y= 42, .x= 13},
ExpectedCoords{ .y= 21, .x= 14},
ExpectedCoords{ .y= 22, .x= 14},
ExpectedCoords{ .y= 23, .x= 14},
ExpectedCoords{ .y= 24, .x= 14},
ExpectedCoords{ .y= 29, .x= 14},
ExpectedCoords{ .y= 34, .x= 14},
ExpectedCoords{ .y= 37, .x= 14},
ExpectedCoords{ .y= 40, .x= 14},
ExpectedCoords{ .y= 42, .x= 14},
ExpectedCoords{ .y= 21, .x= 15},
ExpectedCoords{ .y= 25, .x= 15},
ExpectedCoords{ .y= 29, .x= 15},
ExpectedCoords{ .y= 34, .x= 15},
ExpectedCoords{ .y= 37, .x= 15},
ExpectedCoords{ .y= 41, .x= 15},
ExpectedCoords{ .y= 42, .x= 15},
ExpectedCoords{ .y= 21, .x= 16},
ExpectedCoords{ .y= 25, .x= 16},
ExpectedCoords{ .y= 29, .x= 16},
ExpectedCoords{ .y= 34, .x= 16},
ExpectedCoords{ .y= 37, .x= 16},
ExpectedCoords{ .y= 42, .x= 16},
ExpectedCoords{ .y= 21, .x= 17},
ExpectedCoords{ .y= 25, .x= 17},
ExpectedCoords{ .y= 29, .x= 17},
ExpectedCoords{ .y= 34, .x= 17},
ExpectedCoords{ .y= 37, .x= 17},
ExpectedCoords{ .y= 42, .x= 17},
ExpectedCoords{ .y= 21, .x= 18},
ExpectedCoords{ .y= 22, .x= 18},
ExpectedCoords{ .y= 23, .x= 18},
ExpectedCoords{ .y= 24, .x= 18},
ExpectedCoords{ .y= 30, .x= 18},
ExpectedCoords{ .y= 31, .x= 18},
ExpectedCoords{ .y= 32, .x= 18},
ExpectedCoords{ .y= 33, .x= 18},
ExpectedCoords{ .y= 37, .x= 18},
ExpectedCoords{ .y= 42, .x= 18},
ExpectedCoords{ .y= 2, .x= 24},
ExpectedCoords{ .y= 3, .x= 24},
ExpectedCoords{ .y= 17, .x= 24},
ExpectedCoords{ .y= 18, .x= 24},
ExpectedCoords{ .y= 32, .x= 24},
ExpectedCoords{ .y= 37, .x= 24},
ExpectedCoords{ .y= 38, .x= 24},
ExpectedCoords{ .y= 39, .x= 24},
ExpectedCoords{ .y= 49, .x= 24},
ExpectedCoords{ .y= 2, .x= 25},
ExpectedCoords{ .y= 4, .x= 25},
ExpectedCoords{ .y= 17, .x= 25},
ExpectedCoords{ .y= 19, .x= 25},
ExpectedCoords{ .y= 32, .x= 25},
ExpectedCoords{ .y= 37, .x= 25},
ExpectedCoords{ .y= 49, .x= 25},
ExpectedCoords{ .y= 2, .x= 26},
ExpectedCoords{ .y= 4, .x= 26},
ExpectedCoords{ .y= 7, .x= 26},
ExpectedCoords{ .y= 9, .x= 26},
ExpectedCoords{ .y= 17, .x= 26},
ExpectedCoords{ .y= 19, .x= 26},
ExpectedCoords{ .y= 23, .x= 26},
ExpectedCoords{ .y= 24, .x= 26},
ExpectedCoords{ .y= 28, .x= 26},
ExpectedCoords{ .y= 29, .x= 26},
ExpectedCoords{ .y= 32, .x= 26},
ExpectedCoords{ .y= 33, .x= 26},
ExpectedCoords{ .y= 37, .x= 26},
ExpectedCoords{ .y= 43, .x= 26},
ExpectedCoords{ .y= 49, .x= 26},
ExpectedCoords{ .y= 53, .x= 26},
ExpectedCoords{ .y= 54, .x= 26},
ExpectedCoords{ .y= 2, .x= 27},
ExpectedCoords{ .y= 3, .x= 27},
ExpectedCoords{ .y= 7, .x= 27},
ExpectedCoords{ .y= 9, .x= 27},
ExpectedCoords{ .y= 17, .x= 27},
ExpectedCoords{ .y= 18, .x= 27},
ExpectedCoords{ .y= 22, .x= 27},
ExpectedCoords{ .y= 24, .x= 27},
ExpectedCoords{ .y= 27, .x= 27},
ExpectedCoords{ .y= 32, .x= 27},
ExpectedCoords{ .y= 37, .x= 27},
ExpectedCoords{ .y= 42, .x= 27},
ExpectedCoords{ .y= 44, .x= 27},
ExpectedCoords{ .y= 48, .x= 27},
ExpectedCoords{ .y= 49, .x= 27},
ExpectedCoords{ .y= 52, .x= 27},
ExpectedCoords{ .y= 54, .x= 27},
ExpectedCoords{ .y= 58, .x= 27},
ExpectedCoords{ .y= 59, .x= 27},
ExpectedCoords{ .y= 2, .x= 28},
ExpectedCoords{ .y= 4, .x= 28},
ExpectedCoords{ .y= 7, .x= 28},
ExpectedCoords{ .y= 8, .x= 28},
ExpectedCoords{ .y= 9, .x= 28},
ExpectedCoords{ .y= 17, .x= 28},
ExpectedCoords{ .y= 19, .x= 28},
ExpectedCoords{ .y= 22, .x= 28},
ExpectedCoords{ .y= 23, .x= 28},
ExpectedCoords{ .y= 28, .x= 28},
ExpectedCoords{ .y= 32, .x= 28},
ExpectedCoords{ .y= 37, .x= 28},
ExpectedCoords{ .y= 42, .x= 28},
ExpectedCoords{ .y= 44, .x= 28},
ExpectedCoords{ .y= 47, .x= 28},
ExpectedCoords{ .y= 49, .x= 28},
ExpectedCoords{ .y= 52, .x= 28},
ExpectedCoords{ .y= 53, .x= 28},
ExpectedCoords{ .y= 58, .x= 28},
ExpectedCoords{ .y= 2, .x= 29},
ExpectedCoords{ .y= 4, .x= 29},
ExpectedCoords{ .y= 9, .x= 29},
ExpectedCoords{ .y= 17, .x= 29},
ExpectedCoords{ .y= 19, .x= 29},
ExpectedCoords{ .y= 22, .x= 29},
ExpectedCoords{ .y= 29, .x= 29},
ExpectedCoords{ .y= 32, .x= 29},
ExpectedCoords{ .y= 37, .x= 29},
ExpectedCoords{ .y= 42, .x= 29},
ExpectedCoords{ .y= 44, .x= 29},
ExpectedCoords{ .y= 47, .x= 29},
ExpectedCoords{ .y= 49, .x= 29},
ExpectedCoords{ .y= 52, .x= 29},
ExpectedCoords{ .y= 58, .x= 29},
ExpectedCoords{ .y= 2, .x= 30},
ExpectedCoords{ .y= 3, .x= 30},
ExpectedCoords{ .y= 9, .x= 30},
ExpectedCoords{ .y= 17, .x= 30},
ExpectedCoords{ .y= 18, .x= 30},
ExpectedCoords{ .y= 23, .x= 30},
ExpectedCoords{ .y= 24, .x= 30},
ExpectedCoords{ .y= 27, .x= 30},
ExpectedCoords{ .y= 28, .x= 30},
ExpectedCoords{ .y= 33, .x= 30},
ExpectedCoords{ .y= 34, .x= 30},
ExpectedCoords{ .y= 37, .x= 30},
ExpectedCoords{ .y= 38, .x= 30},
ExpectedCoords{ .y= 39, .x= 30},
ExpectedCoords{ .y= 43, .x= 30},
ExpectedCoords{ .y= 48, .x= 30},
ExpectedCoords{ .y= 49, .x= 30},
ExpectedCoords{ .y= 53, .x= 30},
ExpectedCoords{ .y= 54, .x= 30},
ExpectedCoords{ .y= 58, .x= 30},
ExpectedCoords{ .y= 60, .x= 30},
ExpectedCoords{ .y= 7, .x= 31},
ExpectedCoords{ .y= 8, .x= 31},
ExpectedCoords{ .y= 9, .x= 31},
};
for(expected) |coords| {
expect(emu.display[coords.y][coords.x]);
}
} | tests/tests.zig |
const std = @import("./index.zig");
const debug = std.debug;
/// Given the first byte of a UTF-8 codepoint,
/// returns a number 1-4 indicating the total length of the codepoint in bytes.
/// If this byte does not match the form of a UTF-8 start byte, returns Utf8InvalidStartByte.
pub fn utf8ByteSequenceLength(first_byte: u8) !u3 {
if (first_byte < 0b10000000) return u3(1);
if (first_byte & 0b11100000 == 0b11000000) return u3(2);
if (first_byte & 0b11110000 == 0b11100000) return u3(3);
if (first_byte & 0b11111000 == 0b11110000) return u3(4);
return error.Utf8InvalidStartByte;
}
/// Decodes the UTF-8 codepoint encoded in the given slice of bytes.
/// bytes.len must be equal to utf8ByteSequenceLength(bytes[0]) catch unreachable.
/// If you already know the length at comptime, you can call one of
/// utf8Decode2,utf8Decode3,utf8Decode4 directly instead of this function.
pub fn utf8Decode(bytes: []const u8) !u32 {
return switch (bytes.len) {
1 => u32(bytes[0]),
2 => utf8Decode2(bytes),
3 => utf8Decode3(bytes),
4 => utf8Decode4(bytes),
else => unreachable,
};
}
pub fn utf8Decode2(bytes: []const u8) !u32 {
debug.assert(bytes.len == 2);
debug.assert(bytes[0] & 0b11100000 == 0b11000000);
var value: u32 = bytes[0] & 0b00011111;
if (bytes[1] & 0b11000000 != 0b10000000) return error.Utf8ExpectedContinuation;
value <<= 6;
value |= bytes[1] & 0b00111111;
if (value < 0x80) return error.Utf8OverlongEncoding;
return value;
}
pub fn utf8Decode3(bytes: []const u8) !u32 {
debug.assert(bytes.len == 3);
debug.assert(bytes[0] & 0b11110000 == 0b11100000);
var value: u32 = bytes[0] & 0b00001111;
if (bytes[1] & 0b11000000 != 0b10000000) return error.Utf8ExpectedContinuation;
value <<= 6;
value |= bytes[1] & 0b00111111;
if (bytes[2] & 0b11000000 != 0b10000000) return error.Utf8ExpectedContinuation;
value <<= 6;
value |= bytes[2] & 0b00111111;
if (value < 0x800) return error.Utf8OverlongEncoding;
if (0xd800 <= value and value <= 0xdfff) return error.Utf8EncodesSurrogateHalf;
return value;
}
pub fn utf8Decode4(bytes: []const u8) !u32 {
debug.assert(bytes.len == 4);
debug.assert(bytes[0] & 0b11111000 == 0b11110000);
var value: u32 = bytes[0] & 0b00000111;
if (bytes[1] & 0b11000000 != 0b10000000) return error.Utf8ExpectedContinuation;
value <<= 6;
value |= bytes[1] & 0b00111111;
if (bytes[2] & 0b11000000 != 0b10000000) return error.Utf8ExpectedContinuation;
value <<= 6;
value |= bytes[2] & 0b00111111;
if (bytes[3] & 0b11000000 != 0b10000000) return error.Utf8ExpectedContinuation;
value <<= 6;
value |= bytes[3] & 0b00111111;
if (value < 0x10000) return error.Utf8OverlongEncoding;
if (value > 0x10FFFF) return error.Utf8CodepointTooLarge;
return value;
}
pub fn utf8ValidateSlice(s: []const u8) bool {
var i: usize = 0;
while (i < s.len) {
if (utf8ByteSequenceLength(s[i])) |cp_len| {
if (i + cp_len > s.len) {
return false;
}
if (utf8Decode(s[i..i+cp_len])) |_| {} else |_| { return false; }
i += cp_len;
} else |err| {
return false;
}
}
return true;
}
/// Utf8View iterates the code points of a utf-8 encoded string.
///
/// ```
/// var utf8 = (try std.unicode.Utf8View.init("hi there")).iterator();
/// while (utf8.nextCodepointSlice()) |codepoint| {
/// std.debug.warn("got codepoint {}\n", codepoint);
/// }
/// ```
pub const Utf8View = struct {
bytes: []const u8,
pub fn init(s: []const u8) !Utf8View {
if (!utf8ValidateSlice(s)) {
return error.InvalidUtf8;
}
return initUnchecked(s);
}
pub fn initUnchecked(s: []const u8) Utf8View {
return Utf8View {
.bytes = s,
};
}
pub fn initComptime(comptime s: []const u8) Utf8View {
if (comptime init(s)) |r| {
return r;
} else |err| switch (err) {
error.InvalidUtf8 => {
@compileError("invalid utf8");
unreachable;
}
}
}
pub fn iterator(s: &const Utf8View) Utf8Iterator {
return Utf8Iterator {
.bytes = s.bytes,
.i = 0,
};
}
};
const Utf8Iterator = struct {
bytes: []const u8,
i: usize,
pub fn nextCodepointSlice(it: &Utf8Iterator) ?[]const u8 {
if (it.i >= it.bytes.len) {
return null;
}
const cp_len = utf8ByteSequenceLength(it.bytes[it.i]) catch unreachable;
it.i += cp_len;
return it.bytes[it.i-cp_len..it.i];
}
pub fn nextCodepoint(it: &Utf8Iterator) ?u32 {
const slice = it.nextCodepointSlice() ?? return null;
const r = switch (slice.len) {
1 => u32(slice[0]),
2 => utf8Decode2(slice),
3 => utf8Decode3(slice),
4 => utf8Decode4(slice),
else => unreachable,
};
return r catch unreachable;
}
};
test "utf8 iterator on ascii" {
const s = Utf8View.initComptime("abc");
var it1 = s.iterator();
debug.assert(std.mem.eql(u8, "a", ??it1.nextCodepointSlice()));
debug.assert(std.mem.eql(u8, "b", ??it1.nextCodepointSlice()));
debug.assert(std.mem.eql(u8, "c", ??it1.nextCodepointSlice()));
debug.assert(it1.nextCodepointSlice() == null);
var it2 = s.iterator();
debug.assert(??it2.nextCodepoint() == 'a');
debug.assert(??it2.nextCodepoint() == 'b');
debug.assert(??it2.nextCodepoint() == 'c');
debug.assert(it2.nextCodepoint() == null);
}
test "utf8 view bad" {
// Compile-time error.
// const s3 = Utf8View.initComptime("\xfe\xf2");
const s = Utf8View.init("hel\xadlo");
if (s) |_| { unreachable; } else |err| { debug.assert(err == error.InvalidUtf8); }
}
test "utf8 view ok" {
const s = Utf8View.initComptime("東京市");
var it1 = s.iterator();
debug.assert(std.mem.eql(u8, "東", ??it1.nextCodepointSlice()));
debug.assert(std.mem.eql(u8, "京", ??it1.nextCodepointSlice()));
debug.assert(std.mem.eql(u8, "市", ??it1.nextCodepointSlice()));
debug.assert(it1.nextCodepointSlice() == null);
var it2 = s.iterator();
debug.assert(??it2.nextCodepoint() == 0x6771);
debug.assert(??it2.nextCodepoint() == 0x4eac);
debug.assert(??it2.nextCodepoint() == 0x5e02);
debug.assert(it2.nextCodepoint() == null);
}
test "bad utf8 slice" {
debug.assert(utf8ValidateSlice("abc"));
debug.assert(!utf8ValidateSlice("abc\xc0"));
debug.assert(!utf8ValidateSlice("abc\xc0abc"));
debug.assert(utf8ValidateSlice("abc\xdf\xbf"));
}
test "valid utf8" {
testValid("\x00", 0x0);
testValid("\x20", 0x20);
testValid("\x7f", 0x7f);
testValid("\xc2\x80", 0x80);
testValid("\xdf\xbf", 0x7ff);
testValid("\xe0\xa0\x80", 0x800);
testValid("\xe1\x80\x80", 0x1000);
testValid("\xef\xbf\xbf", 0xffff);
testValid("\xf0\x90\x80\x80", 0x10000);
testValid("\xf1\x80\x80\x80", 0x40000);
testValid("\xf3\xbf\xbf\xbf", 0xfffff);
testValid("\xf4\x8f\xbf\xbf", 0x10ffff);
}
test "invalid utf8 continuation bytes" {
// unexpected continuation
testError("\x80", error.Utf8InvalidStartByte);
testError("\xbf", error.Utf8InvalidStartByte);
// too many leading 1's
testError("\xf8", error.Utf8InvalidStartByte);
testError("\xff", error.Utf8InvalidStartByte);
// expected continuation for 2 byte sequences
testError("\xc2", error.UnexpectedEof);
testError("\xc2\x00", error.Utf8ExpectedContinuation);
testError("\xc2\xc0", error.Utf8ExpectedContinuation);
// expected continuation for 3 byte sequences
testError("\xe0", error.UnexpectedEof);
testError("\xe0\x00", error.UnexpectedEof);
testError("\xe0\xc0", error.UnexpectedEof);
testError("\xe0\xa0", error.UnexpectedEof);
testError("\xe0\xa0\x00", error.Utf8ExpectedContinuation);
testError("\xe0\xa0\xc0", error.Utf8ExpectedContinuation);
// expected continuation for 4 byte sequences
testError("\xf0", error.UnexpectedEof);
testError("\xf0\x00", error.UnexpectedEof);
testError("\xf0\xc0", error.UnexpectedEof);
testError("\xf0\x90\x00", error.UnexpectedEof);
testError("\xf0\x90\xc0", error.UnexpectedEof);
testError("\xf0\x90\x80\x00", error.Utf8ExpectedContinuation);
testError("\xf0\x90\x80\xc0", error.Utf8ExpectedContinuation);
}
test "overlong utf8 codepoint" {
testError("\xc0\x80", error.Utf8OverlongEncoding);
testError("\xc1\xbf", error.Utf8OverlongEncoding);
testError("\xe0\x80\x80", error.Utf8OverlongEncoding);
testError("\xe0\x9f\xbf", error.Utf8OverlongEncoding);
testError("\xf0\x80\x80\x80", error.Utf8OverlongEncoding);
testError("\xf0\x8f\xbf\xbf", error.Utf8OverlongEncoding);
}
test "misc invalid utf8" {
// codepoint out of bounds
testError("\xf4\x90\x80\x80", error.Utf8CodepointTooLarge);
testError("\xf7\xbf\xbf\xbf", error.Utf8CodepointTooLarge);
// surrogate halves
testValid("\xed\x9f\xbf", 0xd7ff);
testError("\xed\xa0\x80", error.Utf8EncodesSurrogateHalf);
testError("\xed\xbf\xbf", error.Utf8EncodesSurrogateHalf);
testValid("\xee\x80\x80", 0xe000);
}
fn testError(bytes: []const u8, expected_err: error) void {
if (testDecode(bytes)) |_| {
unreachable;
} else |err| {
debug.assert(err == expected_err);
}
}
fn testValid(bytes: []const u8, expected_codepoint: u32) void {
debug.assert((testDecode(bytes) catch unreachable) == expected_codepoint);
}
fn testDecode(bytes: []const u8) !u32 {
const length = try utf8ByteSequenceLength(bytes[0]);
if (bytes.len < length) return error.UnexpectedEof;
debug.assert(bytes.len == length);
return utf8Decode(bytes);
} | std/unicode.zig |
const std = @import("std");
const process = std.process;
const debug = @import("debug.zig");
const vm = @import("vm.zig");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const Chunk = @import("chunk.zig").Chunk;
const OpCode = @import("chunk.zig").OpCode;
pub fn main() anyerror!void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = &gpa.allocator;
try vm.init(allocator);
defer vm.deinit();
var arg_it = process.args();
const exe_name = try arg_it.next(allocator).?;
defer allocator.free(exe_name);
const path_arg = arg_it.next(allocator);
if (path_arg == null) {
try repl(allocator);
} else {
const path = try path_arg.?;
defer allocator.free(path);
if (arg_it.skip()) {
std.debug.warn("Usage:\n {} [path]\n", .{exe_name});
return error.InvalidArgs;
}
try runFile(allocator, path);
}
}
fn repl(gpa: *Allocator) !void {
var line_buffer = ArrayList(u8).init(gpa);
defer line_buffer.deinit();
const stdin = std.io.getStdIn().reader();
const stdout = std.io.getStdOut().writer();
while (true) {
_ = try stdout.write("> ");
stdin.readUntilDelimiterArrayList(&line_buffer, '\n', 16 * 1024) catch |e| {
_ = try stdout.write("\n");
return e;
};
if (std.mem.eql(u8, line_buffer.items, "exit")) {
return;
}
vm.interpret(line_buffer.items) catch |e| {
if (e == vm.InterpretError.Compilation) {
// TODO
} else if (e == vm.InterpretError.Runtime) {
// TODO
} else {
return e;
}
};
}
}
fn runFile(gpa: *Allocator, file_path: []const u8) !void {
var source_code = try readFile(gpa, file_path);
defer gpa.free(source_code);
try vm.interpret(source_code);
}
fn readFile(gpa: *Allocator, file_path: []const u8) ![]const u8 {
var file = try std.fs.cwd().openFile(file_path, .{});
defer file.close();
var reader = file.reader();
var source_code = try reader.readAllAlloc(gpa, 1024 * 1024 * 1024);
return source_code;
} | src/main.zig |
const sg = @import("gfx.zig");
// helper function to convert "anything" to a Range struct
pub fn asRange(val: anytype) Range {
const type_info = @typeInfo(@TypeOf(val));
switch (type_info) {
.Pointer => {
switch (type_info.Pointer.size) {
.One => return .{ .ptr = val, .size = @sizeOf(type_info.Pointer.child) },
.Slice => return .{ .ptr = val.ptr, .size = @sizeOf(type_info.Pointer.child) * val.len },
else => @compileError("FIXME: Pointer type!"),
}
},
.Struct, .Array => {
return .{ .ptr = &val, .size = @sizeOf(@TypeOf(val)) };
},
else => {
@compileError("Cannot convert to range!");
}
}
}
pub const Range = extern struct {
ptr: ?*const c_void = null,
size: usize = 0,
};
pub const Mat4 = extern struct {
m: [4][4]f32 = [_][4]f32{[_]f32{ 0.0 }**4}**4,
};
pub const Vertex = extern struct {
x: f32 = 0.0,
y: f32 = 0.0,
z: f32 = 0.0,
normal: u32 = 0,
u: u16 = 0,
v: u16 = 0,
color: u32 = 0,
};
pub const ElementRange = extern struct {
base_element: u32 = 0,
num_elements: u32 = 0,
__pad: [3]u32 = [_]u32{0} ** 3,
};
pub const SizesItem = extern struct {
num: u32 = 0,
size: u32 = 0,
__pad: [3]u32 = [_]u32{0} ** 3,
};
pub const Sizes = extern struct {
vertices: SizesItem = .{ },
indices: SizesItem = .{ },
};
pub const BufferItem = extern struct {
buffer: Range = .{ },
data_size: usize = 0,
shape_offset: usize = 0,
};
pub const Buffer = extern struct {
valid: bool = false,
vertices: BufferItem = .{ },
indices: BufferItem = .{ },
};
pub const Plane = extern struct {
width: f32 = 0.0,
depth: f32 = 0.0,
tiles: u16 = 0,
color: u32 = 0,
random_colors: bool = false,
merge: bool = false,
transform: Mat4 = .{ },
};
pub const Box = extern struct {
width: f32 = 0.0,
height: f32 = 0.0,
depth: f32 = 0.0,
tiles: u16 = 0,
color: u32 = 0,
random_colors: bool = false,
merge: bool = false,
transform: Mat4 = .{ },
};
pub const Sphere = extern struct {
radius: f32 = 0.0,
slices: u16 = 0,
stacks: u16 = 0,
color: u32 = 0,
random_colors: bool = false,
merge: bool = false,
transform: Mat4 = .{ },
};
pub const Cylinder = extern struct {
radius: f32 = 0.0,
height: f32 = 0.0,
slices: u16 = 0,
stacks: u16 = 0,
color: u32 = 0,
random_colors: bool = false,
merge: bool = false,
transform: Mat4 = .{ },
};
pub const Torus = extern struct {
radius: f32 = 0.0,
ring_radius: f32 = 0.0,
sides: u16 = 0,
rings: u16 = 0,
color: u32 = 0,
random_colors: bool = false,
merge: bool = false,
transform: Mat4 = .{ },
};
pub extern fn sshape_build_plane([*c]const Buffer, [*c]const Plane) Buffer;
pub inline fn buildPlane(buf: Buffer, params: Plane) Buffer {
return sshape_build_plane(&buf, ¶ms);
}
pub extern fn sshape_build_box([*c]const Buffer, [*c]const Box) Buffer;
pub inline fn buildBox(buf: Buffer, params: Box) Buffer {
return sshape_build_box(&buf, ¶ms);
}
pub extern fn sshape_build_sphere([*c]const Buffer, [*c]const Sphere) Buffer;
pub inline fn buildSphere(buf: Buffer, params: Sphere) Buffer {
return sshape_build_sphere(&buf, ¶ms);
}
pub extern fn sshape_build_cylinder([*c]const Buffer, [*c]const Cylinder) Buffer;
pub inline fn buildCylinder(buf: Buffer, params: Cylinder) Buffer {
return sshape_build_cylinder(&buf, ¶ms);
}
pub extern fn sshape_build_torus([*c]const Buffer, [*c]const Torus) Buffer;
pub inline fn buildTorus(buf: Buffer, params: Torus) Buffer {
return sshape_build_torus(&buf, ¶ms);
}
pub extern fn sshape_plane_sizes(u32) Sizes;
pub inline fn planeSizes(tiles: u32) Sizes {
return sshape_plane_sizes(tiles);
}
pub extern fn sshape_box_sizes(u32) Sizes;
pub inline fn boxSizes(tiles: u32) Sizes {
return sshape_box_sizes(tiles);
}
pub extern fn sshape_sphere_sizes(u32, u32) Sizes;
pub inline fn sphereSizes(slices: u32, stacks: u32) Sizes {
return sshape_sphere_sizes(slices, stacks);
}
pub extern fn sshape_cylinder_sizes(u32, u32) Sizes;
pub inline fn cylinderSizes(slices: u32, stacks: u32) Sizes {
return sshape_cylinder_sizes(slices, stacks);
}
pub extern fn sshape_torus_sizes(u32, u32) Sizes;
pub inline fn torusSizes(sides: u32, rings: u32) Sizes {
return sshape_torus_sizes(sides, rings);
}
pub extern fn sshape_element_range([*c]const Buffer) ElementRange;
pub inline fn elementRange(buf: Buffer) ElementRange {
return sshape_element_range(&buf);
}
pub extern fn sshape_vertex_buffer_desc([*c]const Buffer) sg.BufferDesc;
pub inline fn vertexBufferDesc(buf: Buffer) sg.BufferDesc {
return sshape_vertex_buffer_desc(&buf);
}
pub extern fn sshape_index_buffer_desc([*c]const Buffer) sg.BufferDesc;
pub inline fn indexBufferDesc(buf: Buffer) sg.BufferDesc {
return sshape_index_buffer_desc(&buf);
}
pub extern fn sshape_buffer_layout_desc() sg.BufferLayoutDesc;
pub inline fn bufferLayoutDesc() sg.BufferLayoutDesc {
return sshape_buffer_layout_desc();
}
pub extern fn sshape_position_attr_desc() sg.VertexAttrDesc;
pub inline fn positionAttrDesc() sg.VertexAttrDesc {
return sshape_position_attr_desc();
}
pub extern fn sshape_normal_attr_desc() sg.VertexAttrDesc;
pub inline fn normalAttrDesc() sg.VertexAttrDesc {
return sshape_normal_attr_desc();
}
pub extern fn sshape_texcoord_attr_desc() sg.VertexAttrDesc;
pub inline fn texcoordAttrDesc() sg.VertexAttrDesc {
return sshape_texcoord_attr_desc();
}
pub extern fn sshape_color_attr_desc() sg.VertexAttrDesc;
pub inline fn colorAttrDesc() sg.VertexAttrDesc {
return sshape_color_attr_desc();
}
pub extern fn sshape_color_4f(f32, f32, f32, f32) u32;
pub inline fn color4f(r: f32, g: f32, b: f32, a: f32) u32 {
return sshape_color_4f(r, g, b, a);
}
pub extern fn sshape_color_3f(f32, f32, f32) u32;
pub inline fn color3f(r: f32, g: f32, b: f32) u32 {
return sshape_color_3f(r, g, b);
}
pub extern fn sshape_color_4b(u8, u8, u8, u8) u32;
pub inline fn color4b(r: u8, g: u8, b: u8, a: u8) u32 {
return sshape_color_4b(r, g, b, a);
}
pub extern fn sshape_color_3b(u8, u8, u8) u32;
pub inline fn color3b(r: u8, g: u8, b: u8) u32 {
return sshape_color_3b(r, g, b);
}
pub extern fn sshape_mat4([*c]const f32) Mat4;
pub inline fn mat4(m: *const f32) Mat4 {
return sshape_mat4(m);
}
pub extern fn sshape_mat4_transpose([*c]const f32) Mat4;
pub inline fn mat4Transpose(m: *const f32) Mat4 {
return sshape_mat4_transpose(m);
} | src/sokol/shape.zig |
const std = @import("std");
const wayland = @import("wayland.zig");
pub const Object = opaque {};
pub const Message = extern struct {
name: [*:0]const u8,
signature: [*:0]const u8,
types: ?[*]const ?*const Interface,
};
pub const Interface = extern struct {
name: [*:0]const u8,
version: c_int,
method_count: c_int,
methods: ?[*]const Message,
event_count: c_int,
events: ?[*]const Message,
};
pub const Array = extern struct {
size: usize,
alloc: usize,
data: *c_void,
};
/// A 24.8 signed fixed-point number.
pub const Fixed = extern enum(i32) {
_,
pub fn toInt(f: Fixed) i24 {
return @truncate(i24, @enumToInt(f) >> 8);
}
pub fn fromInt(i: i24) Fixed {
return @intToEnum(Fixed, @as(i32, i) << 8);
}
pub fn toDouble(f: Fixed) f64 {
return @intToFloat(f64, @enumToInt(f)) / 256;
}
pub fn fromDouble(d: f64) Fixed {
return @intToEnum(Fixed, @floatToInt(i32, d * 256));
}
};
pub const Argument = extern union {
i: i32,
u: u32,
f: Fixed,
s: ?[*:0]const u8,
o: ?*Object,
n: u32,
a: ?*Array,
h: std.os.fd_t,
};
pub fn Dispatcher(comptime Obj: type, comptime Data: type) type {
const client = @hasDecl(Obj, "Event");
const Payload = if (client) Obj.Event else Obj.Request;
return struct {
pub fn dispatcher(
implementation: ?*const c_void,
object: if (client) *wayland.client.wl.Proxy else *wayland.server.wl.Resource,
opcode: u32,
message: *const Message,
args: [*]Argument,
) callconv(.C) c_int {
inline for (@typeInfo(Payload).Union.fields) |payload_field, payload_num| {
if (payload_num == opcode) {
var payload_data: payload_field.field_type = undefined;
inline for (@typeInfo(payload_field.field_type).Struct.fields) |f, i| {
if (@typeInfo(f.field_type) == .Enum) {
@field(payload_data, f.name) = @intToEnum(f.field_type, args[i].i);
} else {
@field(payload_data, f.name) = switch (@sizeOf(f.field_type)) {
4 => @bitCast(f.field_type, args[i].u),
8 => @intToPtr(f.field_type, @ptrToInt(args[i].s)),
else => unreachable,
};
}
}
@ptrCast(fn (*Obj, Payload, Data) void, implementation)(
@ptrCast(*Obj, object),
@unionInit(Payload, payload_field.name, payload_data),
@intToPtr(Data, @ptrToInt(object.getUserData())),
);
return 0;
}
}
unreachable;
}
};
}
test "Fixed" {
const testing = std.testing;
{
const initial: f64 = 10.5301837;
const val = Fixed.fromDouble(initial);
testing.expectWithinMargin(initial, val.toDouble(), 1 / 256.);
testing.expectEqual(@as(i24, 10), val.toInt());
}
{
const val = Fixed.fromInt(10);
testing.expectEqual(@as(f64, 10.0), val.toDouble());
testing.expectEqual(@as(i24, 10), val.toInt());
}
} | src/common_core.zig |
const bssl = @import("bearssl");
// brssl ta
var TA0_DN = [_]u8 {
0x30, 0x14, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0C,
0x09, 0x6C, 0x6F, 0x63, 0x61, 0x6C, 0x68, 0x6F, 0x73, 0x74
};
var TA0_RSA_N = [_]u8 {
0xBA, 0x68, 0x49, 0x23, 0xBF, 0xD1, 0xF2, 0x63, 0x42, 0x5D, 0x45, 0x0E,
0xDE, 0xAF, 0x26, 0x30, 0x64, 0xA6, 0x32, 0x15, 0x78, 0x1B, 0x00, 0x95,
0x1D, 0x21, 0x61, 0xF1, 0x8A, 0x0F, 0xA2, 0x85, 0x02, 0xA6, 0xAA, 0x76,
0xAA, 0xA9, 0x26, 0xA9, 0xCC, 0x0E, 0x6D, 0x76, 0x1C, 0x4C, 0x39, 0x03,
0x47, 0x32, 0x51, 0xC2, 0x69, 0xCC, 0x9A, 0x29, 0x79, 0x1A, 0x93, 0x1F,
0x5C, 0x3D, 0x8D, 0x31, 0x1D, 0x73, 0xCA, 0x94, 0x9D, 0xD4, 0x28, 0x36,
0xA1, 0xF4, 0x04, 0x2E, 0x4D, 0xDD, 0xED, 0xC9, 0x9A, 0x1D, 0x19, 0x58,
0xC8, 0x79, 0x21, 0x5C, 0x37, 0x97, 0x6E, 0x43, 0x49, 0xF6, 0xD2, 0xDD,
0x98, 0x9A, 0x48, 0x25, 0x9C, 0x3C, 0x3A, 0xFA, 0x6C, 0xD0, 0xF7, 0x2B,
0x6A, 0x53, 0xCD, 0x25, 0x59, 0xD8, 0xF6, 0xF9, 0xA5, 0xC1, 0x15, 0x9E,
0xB9, 0x64, 0x11, 0xC5, 0xA8, 0x0A, 0x3B, 0xF5, 0x99, 0x26, 0x6D, 0xF4,
0xF4, 0x3C, 0xF0, 0xEF, 0x26, 0x40, 0x67, 0xD3, 0x59, 0x90, 0x96, 0xFD,
0x11, 0xCD, 0x19, 0x98, 0xC5, 0x9D, 0xD0, 0xA6, 0x04, 0x9E, 0x79, 0x02,
0x77, 0x5C, 0xDB, 0x09, 0x7C, 0x77, 0x05, 0x36, 0xF9, 0x29, 0x30, 0x58,
0x1A, 0xBF, 0x43, 0x01, 0xBF, 0xEA, 0x56, 0x88, 0x03, 0x20, 0xAE, 0xF3,
0x77, 0x57, 0x7C, 0xBE, 0x38, 0xAB, 0x31, 0x3A, 0x3F, 0xCC, 0x03, 0x63,
0x30, 0x10, 0x6C, 0x7F, 0xBE, 0xC2, 0x4D, 0x49, 0xC4, 0xD6, 0x6D, 0xB3,
0xB6, 0xBF, 0x56, 0xA9, 0xF0, 0x16, 0x4D, 0xE9, 0x30, 0x2B, 0xAE, 0x60,
0xDB, 0x01, 0x9B, 0x79, 0xCD, 0x5F, 0x52, 0x52, 0x23, 0xE6, 0xA3, 0x1A,
0x64, 0xDC, 0xED, 0x62, 0xF8, 0xDE, 0x2D, 0x18, 0x57, 0x12, 0x09, 0x66,
0xDB, 0xD3, 0x52, 0x03, 0x51, 0xF6, 0xC6, 0x0C, 0x66, 0xDB, 0x38, 0xED,
0x03, 0x12, 0x53, 0xA1
};
var TA0_RSA_E = [_]u8 {
0x01, 0x00, 0x01
};
pub const TAs = [_]bssl.c.br_x509_trust_anchor {
.{
.dn = .{
.data = &TA0_DN[0],
.len = TA0_DN.len
},
.flags = 0,
.pkey = .{
.key_type = bssl.c.BR_KEYTYPE_RSA,
.key = .{
.rsa = .{
.n = &TA0_RSA_N[0], .nlen = TA0_RSA_N.len,
.e = &TA0_RSA_E[0], .elen = TA0_RSA_E.len,
}
}
}
}
};
// brssl chain
var CERT0 = [_]u8 {
0x30, 0x82, 0x02, 0xE5, 0x30, 0x82, 0x01, 0xCD, 0xA0, 0x03, 0x02, 0x01,
0x02, 0x02, 0x09, 0x00, 0xC2, 0x1D, 0x8E, 0xCD, 0x64, 0x5C, 0x97, 0x68,
0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01,
0x0B, 0x05, 0x00, 0x30, 0x14, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55,
0x04, 0x03, 0x0C, 0x09, 0x6C, 0x6F, 0x63, 0x61, 0x6C, 0x68, 0x6F, 0x73,
0x74, 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x31, 0x31, 0x32, 0x32, 0x35, 0x32,
0x30, 0x33, 0x34, 0x35, 0x34, 0x5A, 0x17, 0x0D, 0x32, 0x32, 0x30, 0x31,
0x32, 0x34, 0x32, 0x30, 0x33, 0x34, 0x35, 0x34, 0x5A, 0x30, 0x14, 0x31,
0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0C, 0x09, 0x6C, 0x6F,
0x63, 0x61, 0x6C, 0x68, 0x6F, 0x73, 0x74, 0x30, 0x82, 0x01, 0x22, 0x30,
0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01,
0x05, 0x00, 0x03, 0x82, 0x01, 0x0F, 0x00, 0x30, 0x82, 0x01, 0x0A, 0x02,
0x82, 0x01, 0x01, 0x00, 0xBA, 0x68, 0x49, 0x23, 0xBF, 0xD1, 0xF2, 0x63,
0x42, 0x5D, 0x45, 0x0E, 0xDE, 0xAF, 0x26, 0x30, 0x64, 0xA6, 0x32, 0x15,
0x78, 0x1B, 0x00, 0x95, 0x1D, 0x21, 0x61, 0xF1, 0x8A, 0x0F, 0xA2, 0x85,
0x02, 0xA6, 0xAA, 0x76, 0xAA, 0xA9, 0x26, 0xA9, 0xCC, 0x0E, 0x6D, 0x76,
0x1C, 0x4C, 0x39, 0x03, 0x47, 0x32, 0x51, 0xC2, 0x69, 0xCC, 0x9A, 0x29,
0x79, 0x1A, 0x93, 0x1F, 0x5C, 0x3D, 0x8D, 0x31, 0x1D, 0x73, 0xCA, 0x94,
0x9D, 0xD4, 0x28, 0x36, 0xA1, 0xF4, 0x04, 0x2E, 0x4D, 0xDD, 0xED, 0xC9,
0x9A, 0x1D, 0x19, 0x58, 0xC8, 0x79, 0x21, 0x5C, 0x37, 0x97, 0x6E, 0x43,
0x49, 0xF6, 0xD2, 0xDD, 0x98, 0x9A, 0x48, 0x25, 0x9C, 0x3C, 0x3A, 0xFA,
0x6C, 0xD0, 0xF7, 0x2B, 0x6A, 0x53, 0xCD, 0x25, 0x59, 0xD8, 0xF6, 0xF9,
0xA5, 0xC1, 0x15, 0x9E, 0xB9, 0x64, 0x11, 0xC5, 0xA8, 0x0A, 0x3B, 0xF5,
0x99, 0x26, 0x6D, 0xF4, 0xF4, 0x3C, 0xF0, 0xEF, 0x26, 0x40, 0x67, 0xD3,
0x59, 0x90, 0x96, 0xFD, 0x11, 0xCD, 0x19, 0x98, 0xC5, 0x9D, 0xD0, 0xA6,
0x04, 0x9E, 0x79, 0x02, 0x77, 0x5C, 0xDB, 0x09, 0x7C, 0x77, 0x05, 0x36,
0xF9, 0x29, 0x30, 0x58, 0x1A, 0xBF, 0x43, 0x01, 0xBF, 0xEA, 0x56, 0x88,
0x03, 0x20, 0xAE, 0xF3, 0x77, 0x57, 0x7C, 0xBE, 0x38, 0xAB, 0x31, 0x3A,
0x3F, 0xCC, 0x03, 0x63, 0x30, 0x10, 0x6C, 0x7F, 0xBE, 0xC2, 0x4D, 0x49,
0xC4, 0xD6, 0x6D, 0xB3, 0xB6, 0xBF, 0x56, 0xA9, 0xF0, 0x16, 0x4D, 0xE9,
0x30, 0x2B, 0xAE, 0x60, 0xDB, 0x01, 0x9B, 0x79, 0xCD, 0x5F, 0x52, 0x52,
0x23, 0xE6, 0xA3, 0x1A, 0x64, 0xDC, 0xED, 0x62, 0xF8, 0xDE, 0x2D, 0x18,
0x57, 0x12, 0x09, 0x66, 0xDB, 0xD3, 0x52, 0x03, 0x51, 0xF6, 0xC6, 0x0C,
0x66, 0xDB, 0x38, 0xED, 0x03, 0x12, 0x53, 0xA1, 0x02, 0x03, 0x01, 0x00,
0x01, 0xA3, 0x3A, 0x30, 0x38, 0x30, 0x14, 0x06, 0x03, 0x55, 0x1D, 0x11,
0x04, 0x0D, 0x30, 0x0B, 0x82, 0x09, 0x6C, 0x6F, 0x63, 0x61, 0x6C, 0x68,
0x6F, 0x73, 0x74, 0x30, 0x0B, 0x06, 0x03, 0x55, 0x1D, 0x0F, 0x04, 0x04,
0x03, 0x02, 0x07, 0x80, 0x30, 0x13, 0x06, 0x03, 0x55, 0x1D, 0x25, 0x04,
0x0C, 0x30, 0x0A, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03,
0x01, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01,
0x01, 0x0B, 0x05, 0x00, 0x03, 0x82, 0x01, 0x01, 0x00, 0x93, 0x42, 0x46,
0x46, 0xAC, 0xEB, 0xAD, 0x31, 0xB7, 0x36, 0x81, 0xEF, 0xD4, 0x91, 0x70,
0xE4, 0xCC, 0x0F, 0xB7, 0x0A, 0x3E, 0x62, 0xD5, 0xB7, 0x6B, 0x99, 0x32,
0x3D, 0x49, 0x2F, 0x26, 0xD6, 0xE4, 0x60, 0xCA, 0x87, 0x7F, 0xFD, 0xDF,
0x6F, 0x1C, 0xB5, 0xE2, 0x16, 0x5D, 0xAC, 0xD1, 0x39, 0x87, 0xD1, 0x28,
0x94, 0xB9, 0xCF, 0xCA, 0xF2, 0xD3, 0xAE, 0xE5, 0x0F, 0x1A, 0x3A, 0x1C,
0x6D, 0x78, 0xEE, 0xD1, 0xFB, 0x99, 0x45, 0xBA, 0xCF, 0x40, 0x39, 0x89,
0xF6, 0x5F, 0x18, 0xFB, 0x00, 0xFD, 0xB2, 0x82, 0x27, 0xA3, 0x62, 0x42,
0xD9, 0x2B, 0x31, 0x20, 0x71, 0x8D, 0x4C, 0xC7, 0xBC, 0x44, 0xC2, 0xA0,
0x92, 0x94, 0x11, 0x11, 0x18, 0x60, 0x4F, 0xD0, 0x02, 0x8B, 0x0F, 0x26,
0x62, 0x53, 0x2A, 0x25, 0x9D, 0x53, 0x7A, 0x13, 0x72, 0x11, 0xFA, 0xD0,
0x07, 0xF9, 0x6D, 0x74, 0x55, 0x6E, 0xAE, 0xCB, 0xB7, 0x71, 0xE0, 0x9F,
0xF8, 0x24, 0xB7, 0x45, 0x64, 0x3A, 0x54, 0x95, 0x74, 0x1A, 0x0C, 0x78,
0x26, 0x20, 0xD9, 0x7A, 0x05, 0x00, 0xEB, 0x24, 0xAE, 0xF1, 0x8A, 0x0E,
0xA6, 0xA9, 0x0E, 0xD3, 0x84, 0x57, 0x74, 0x45, 0x5E, 0x8B, 0xF2, 0xBD,
0x57, 0x78, 0x59, 0x7E, 0x65, 0x73, 0xC9, 0x80, 0x38, 0x63, 0xC9, 0x10,
0x98, 0xC9, 0x8A, 0x62, 0xB7, 0x5D, 0x7D, 0x69, 0x80, 0xDF, 0x15, 0xE9,
0xBE, 0xE6, 0x05, 0xFF, 0x47, 0xB0, 0x52, 0x48, 0x35, 0xBF, 0xDD, 0x6E,
0xEB, 0xBA, 0xB2, 0x18, 0xEB, 0xF7, 0xB9, 0x68, 0x99, 0x56, 0xC4, 0x28,
0x11, 0xCF, 0xE8, 0x14, 0x59, 0x8E, 0x2C, 0x17, 0x41, 0x5F, 0x8E, 0xB4,
0xE1, 0x43, 0xF8, 0xC0, 0xA2, 0xE9, 0xFC, 0x74, 0xF8, 0x46, 0xF7, 0x19,
0xCD, 0xA8, 0x55, 0x6D, 0x4D, 0x1B, 0x23, 0xEE, 0xEF, 0x70, 0xC6, 0x59,
0x14
};
pub const CHAIN = [_]bssl.c.br_x509_certificate {
.{
.data = &CERT0[0],
.data_len = CERT0.len
},
};
// brssl skey
var RSA_P = [_]u8 {
0xF6, 0xFB, 0x18, 0x10, 0xDF, 0xA4, 0x91, 0xFB, 0x21, 0xC8, 0xF7, 0x3A,
0x72, 0xEC, 0xBB, 0xF2, 0x5E, 0xA0, 0xCD, 0x5D, 0xB8, 0x6B, 0x35, 0x7D,
0x57, 0xF1, 0x0E, 0xB8, 0x10, 0x8E, 0x14, 0x59, 0x9A, 0xAC, 0x9A, 0x4B,
0x7B, 0xCA, 0xD7, 0x94, 0x2F, 0x6E, 0xA1, 0xBB, 0x27, 0x6A, 0x27, 0x33,
0x8B, 0xCC, 0xF5, 0x3E, 0x1F, 0xC0, 0x92, 0xD4, 0x79, 0xE2, 0x73, 0xB2,
0x76, 0x9F, 0x40, 0xD9, 0xBE, 0xF1, 0x5F, 0xF1, 0x95, 0x8F, 0x0A, 0xAF,
0x50, 0x31, 0x90, 0x20, 0xE4, 0x8B, 0xF6, 0xD4, 0xB3, 0x10, 0x40, 0x42,
0xFF, 0x32, 0x5D, 0xBA, 0x0C, 0x77, 0xB0, 0xAF, 0xF8, 0x53, 0x45, 0x1B,
0x67, 0xCA, 0x19, 0xCD, 0xC1, 0xC4, 0xE8, 0x37, 0x65, 0x10, 0xAC, 0x50,
0x47, 0xAA, 0x2E, 0xFB, 0x20, 0x1A, 0xE4, 0x9B, 0xEC, 0x79, 0x86, 0xB7,
0xD7, 0x4D, 0x3F, 0xF1, 0xE1, 0x92, 0x01, 0x83
};
var RSA_Q = [_]u8 {
0xC1, 0x36, 0xEB, 0x52, 0x5B, 0x5A, 0x6E, 0xFF, 0x10, 0xE9, 0x87, 0xEC,
0x3B, 0x04, 0x51, 0x20, 0x19, 0xBC, 0x69, 0x63, 0x5B, 0x62, 0xAD, 0xE6,
0x58, 0x7C, 0x26, 0x2B, 0xFC, 0x12, 0x48, 0xDC, 0x0F, 0x9F, 0x13, 0xEE,
0x91, 0xEB, 0x9E, 0xFE, 0x57, 0x57, 0xED, 0x81, 0x31, 0xCC, 0x2A, 0xD6,
0x17, 0xC5, 0xB1, 0x92, 0x8F, 0x9C, 0xEC, 0xA2, 0xF3, 0x58, 0xA9, 0x07,
0x79, 0x39, 0x9A, 0xFE, 0xC9, 0x2E, 0x14, 0x40, 0xA8, 0x79, 0x65, 0xA7,
0x85, 0x54, 0x0C, 0x3C, 0xEB, 0x05, 0xE4, 0x5B, 0xDD, 0x68, 0xC4, 0xB1,
0x79, 0x8D, 0x78, 0x9C, 0xA0, 0x0B, 0xDF, 0x6F, 0xDC, 0x4A, 0x15, 0xE2,
0x48, 0xA8, 0xE4, 0x21, 0x90, 0xFF, 0x8E, 0xC7, 0xE2, 0x48, 0xF8, 0x69,
0x03, 0x40, 0xEA, 0x12, 0x69, 0x07, 0xA4, 0x4B, 0xC1, 0x7A, 0x27, 0x0B,
0x2E, 0x40, 0x93, 0xC0, 0x58, 0xCE, 0x41, 0x0B
};
var RSA_DP = [_]u8 {
0x9B, 0x3A, 0x39, 0x67, 0xF1, 0x87, 0xD7, 0x90, 0x45, 0x2D, 0xAF, 0xE4,
0xF6, 0x72, 0x3F, 0xB6, 0x17, 0x2F, 0x6D, 0xA3, 0xA7, 0xD3, 0x09, 0xED,
0x5B, 0xA6, 0x50, 0x1F, 0xF3, 0x97, 0xB8, 0xC6, 0x90, 0x66, 0x47, 0x1B,
0x86, 0x14, 0x78, 0xE5, 0xD3, 0xE1, 0xEE, 0x98, 0x58, 0x2F, 0x69, 0xB0,
0x05, 0xFF, 0xAD, 0x6B, 0x7C, 0x3D, 0x66, 0x8B, 0x50, 0x87, 0xB9, 0x3B,
0xC3, 0x3E, 0x58, 0x5E, 0x02, 0x9A, 0x66, 0x38, 0xCA, 0x4C, 0xFA, 0xE4,
0x30, 0xBC, 0xD5, 0xDF, 0x36, 0x85, 0x99, 0x7F, 0x19, 0x83, 0xEF, 0x3F,
0xAC, 0x71, 0x15, 0x63, 0x67, 0x8E, 0x9A, 0x68, 0x1E, 0xE5, 0x07, 0x1C,
0x30, 0x61, 0x5F, 0x52, 0x68, 0xA4, 0xBF, 0x66, 0x81, 0x88, 0xB7, 0x24,
0x45, 0xC6, 0x7A, 0x7C, 0xAF, 0x32, 0xF7, 0xD7, 0xE0, 0x0A, 0x89, 0x57,
0x66, 0x64, 0x50, 0xFA, 0x4F, 0x51, 0x9A, 0xCD
};
var RSA_DQ = [_]u8 {
0xBC, 0x78, 0x8D, 0xE3, 0xB0, 0x28, 0xEE, 0xCC, 0xEF, 0xFA, 0x5D, 0x14,
0x1A, 0x1D, 0x83, 0xE5, 0x04, 0x35, 0xBD, 0xB7, 0xA5, 0x95, 0x04, 0x7D,
0x05, 0x23, 0x55, 0x38, 0xE2, 0x92, 0x13, 0x70, 0x55, 0xEC, 0x9E, 0xCC,
0xC0, 0x9A, 0x4E, 0x65, 0x5B, 0x5D, 0xF1, 0xD7, 0x6C, 0x73, 0xF3, 0xF5,
0x13, 0x0B, 0x4C, 0xC3, 0xE2, 0x42, 0xF8, 0xB1, 0x9B, 0x1E, 0x89, 0x03,
0x39, 0x44, 0xEF, 0xE4, 0x48, 0xEA, 0x21, 0xE7, 0x50, 0x6F, 0xDA, 0xB1,
0x26, 0x65, 0x6D, 0xEA, 0x9E, 0x77, 0x08, 0xE2, 0x73, 0x7F, 0x97, 0x1E,
0x67, 0xAB, 0x90, 0x53, 0x77, 0xEB, 0x1C, 0xF1, 0x48, 0xB9, 0x1B, 0xCF,
0xB7, 0x80, 0xC7, 0xC7, 0xD6, 0x60, 0xF3, 0x2E, 0x17, 0x95, 0x86, 0x7B,
0x29, 0x29, 0x51, 0x2A, 0xD4, 0x39, 0x18, 0x12, 0xAD, 0x90, 0x32, 0x35,
0xBD, 0xD0, 0x50, 0x4F, 0xF8, 0x50, 0x79, 0x31
};
var RSA_IQ = [_]u8 {
0x28, 0x10, 0x81, 0xE5, 0x03, 0xFF, 0xAE, 0xC9, 0x3D, 0x01, 0x7B, 0x66,
0xF3, 0xB5, 0xDD, 0xD1, 0xA1, 0xBD, 0x36, 0x3E, 0x64, 0x6A, 0xFA, 0x1A,
0x52, 0x2F, 0x4E, 0xDC, 0xD1, 0x31, 0x2E, 0x26, 0x6C, 0x57, 0x98, 0xF4,
0x13, 0x40, 0xE7, 0x28, 0x45, 0x9A, 0xED, 0x31, 0xA3, 0xEA, 0xF9, 0xDA,
0x8C, 0x7C, 0xD8, 0x66, 0x2D, 0x48, 0x83, 0x8D, 0xD6, 0x06, 0xD1, 0x85,
0x62, 0xD7, 0xA2, 0x45, 0xCA, 0x89, 0x0D, 0x93, 0x05, 0x33, 0xE1, 0x94,
0x99, 0xDF, 0x34, 0xAC, 0xA3, 0x05, 0x5E, 0x89, 0x67, 0xD5, 0xBF, 0x4B,
0x2F, 0x9B, 0x09, 0xA2, 0x8C, 0x0E, 0x6D, 0xCF, 0x7E, 0x7B, 0x1B, 0xE1,
0x79, 0x21, 0xB0, 0x0B, 0x0A, 0xE2, 0x73, 0x28, 0xDE, 0x4C, 0x86, 0xE8,
0x2F, 0xE0, 0x45, 0x89, 0xA9, 0xCB, 0x6D, 0x16, 0xF6, 0x65, 0xFA, 0x74,
0x09, 0x1D, 0xED, 0xEA, 0xC4, 0x9B, 0x51, 0x26
};
pub const RSA = bssl.c.br_rsa_private_key {
.n_bitlen = 2048,
.p = &RSA_P[0], .plen = RSA_P.len,
.q = &RSA_Q[0], .qlen = RSA_Q.len,
.dp = &RSA_DP[0], .dplen = RSA_DP.len,
.dq = &RSA_DQ[0], .dqlen = RSA_DQ.len,
.iq = &RSA_IQ[0], .iqlen = RSA_IQ.len
}; | test/localhost.zig |
const std = @import("std");
const builtin = @import("builtin");
const Builder = std.build.Builder;
const Arch = std.Target.Cpu.Arch;
const CrossTarget = std.zig.CrossTarget;
const deps = @import("deps.zig");
pub fn build(b: *Builder) !void {
// const arch = b.option(Arch, "arch", "The CPU architecture to build for") orelse builtin.target.cpu.arch;
const arch: Arch = .x86_64;
const target = try genTarget(arch);
const kernel = try buildKernel(b, target);
const iso = try buildLimineIso(b, kernel);
const qemu = try runIsoQemu(b, iso, arch);
_ = qemu;
}
fn genTarget(arch: std.Target.Cpu.Arch) !CrossTarget {
var target = CrossTarget{ .cpu_arch = arch, .os_tag = .freestanding, .abi = .none };
switch (arch) {
.x86_64 => {
const features = std.Target.x86.Feature;
target.cpu_features_sub.addFeature(@enumToInt(features.mmx));
target.cpu_features_sub.addFeature(@enumToInt(features.sse));
target.cpu_features_sub.addFeature(@enumToInt(features.sse2));
target.cpu_features_sub.addFeature(@enumToInt(features.avx));
target.cpu_features_sub.addFeature(@enumToInt(features.avx2));
target.cpu_features_add.addFeature(@enumToInt(features.soft_float));
},
else => return error.UnsupportedArchitecture,
}
return target;
}
fn buildKernel(b: *Builder, target: CrossTarget) !*std.build.LibExeObjStep {
const mode = b.standardReleaseOptions();
const kernel = b.addExecutable("kernel", "src/main.zig");
kernel.setTarget(target);
kernel.code_model = switch (target.cpu_arch.?) {
.x86_64 => .kernel,
.aarch64 => .small,
else => return error.UnsupportedArchitecture,
};
kernel.setBuildMode(mode);
deps.addAllTo(kernel);
kernel.setLinkerScriptPath(.{ .path = "src/linker.ld" });
kernel.install();
return kernel;
}
fn buildLimineIso(b: *Builder, kernel: *std.build.LibExeObjStep) !*std.build.RunStep {
const limine_install_executable = switch (builtin.os.tag) {
.linux => "limine-s2deploy",
.windows => "limine-s2deploy.exe",
else => return error.UnsupportedOs,
};
const mkiso_args = &[_][]const u8{
"./mkiso.sh",
"zig-out/bin/kernel",
"src/limine",
"zig-out/iso/root",
"zig-out/iso/limine-barebones.iso",
deps.package_data._limine.directory,
limine_install_executable,
};
const iso_cmd = b.addSystemCommand(mkiso_args);
iso_cmd.step.dependOn(&kernel.install_step.?.step);
const iso_step = b.step("iso", "Generate bootable ISO file");
iso_step.dependOn(&iso_cmd.step);
return iso_cmd;
}
fn runIsoQemu(b: *Builder, iso: *std.build.RunStep, arch: Arch) !*std.build.RunStep {
const qemu_executable = switch (arch) {
.x86_64 => "qemu-system-x86_64",
else => return error.UnsupportedArchitecture,
};
const qemu_iso_args = &[_][]const u8{
qemu_executable,
"-cdrom",
"zig-out/iso/limine-barebones.iso",
};
const qemu_iso_cmd = b.addSystemCommand(qemu_iso_args);
qemu_iso_cmd.step.dependOn(&iso.step);
const qemu_iso_step = b.step("run", "Boot ISO in qemu");
qemu_iso_step.dependOn(&qemu_iso_cmd.step);
return qemu_iso_cmd;
} | build.zig |
const std = @import("std");
const builtin = @import("builtin");
const native_endian = builtin.target.cpu.arch.endian();
const mem = std.mem;
const math = std.math;
const random = std.crypto.random;
const assert = std.debug.assert;
const expectEqual = std.testing.expectEqual;
const expectError = std.testing.expectError;
const expect = std.testing.expect;
// instruction classes
/// ld, ldh, ldb: Load data into a.
pub const LD = 0x00;
/// ldx: Load data into x.
pub const LDX = 0x01;
/// st: Store into scratch memory the value of a.
pub const ST = 0x02;
/// st: Store into scratch memory the value of x.
pub const STX = 0x03;
/// alu: Wrapping arithmetic/bitwise operations on a using the value of k/x.
pub const ALU = 0x04;
/// jmp, jeq, jgt, je, jset: Increment the program counter based on a comparison
/// between k/x and the accumulator.
pub const JMP = 0x05;
/// ret: Return a verdict using the value of k/the accumulator.
pub const RET = 0x06;
/// tax, txa: Register value copying between X and a.
pub const MISC = 0x07;
// Size of data to be loaded from the packet.
/// ld: 32-bit full word.
pub const W = 0x00;
/// ldh: 16-bit half word.
pub const H = 0x08;
/// ldb: Single byte.
pub const B = 0x10;
// Addressing modes used for loads to a/x.
/// #k: The immediate value stored in k.
pub const IMM = 0x00;
/// [k]: The value at offset k in the packet.
pub const ABS = 0x20;
/// [x + k]: The value at offset x + k in the packet.
pub const IND = 0x40;
/// M[k]: The value of the k'th scratch memory register.
pub const MEM = 0x60;
/// #len: The size of the packet.
pub const LEN = 0x80;
/// 4 * ([k] & 0xf): Four times the low four bits of the byte at offset k in the
/// packet. This is used for efficiently loading the header length of an IP
/// packet.
pub const MSH = 0xa0;
/// arc4random: 32-bit integer generated from a CPRNG (see arc4random(3)) loaded into a.
/// EXTENSION. Defined for:
/// - OpenBSD.
pub const RND = 0xc0;
// Modifiers for different instruction classes.
/// Use the value of k for alu operations (add #k).
/// Compare against the value of k for jumps (jeq #k, Lt, Lf).
/// Return the value of k for returns (ret #k).
pub const K = 0x00;
/// Use the value of x for alu operations (add x).
/// Compare against the value of X for jumps (jeq x, Lt, Lf).
pub const X = 0x08;
/// Return the value of a for returns (ret a).
pub const A = 0x10;
// ALU Operations on a using the value of k/x.
// All arithmetic operations are defined to overflow the value of a.
/// add: a = a + k
/// a = a + x.
pub const ADD = 0x00;
/// sub: a = a - k
/// a = a - x.
pub const SUB = 0x10;
/// mul: a = a * k
/// a = a * x.
pub const MUL = 0x20;
/// div: a = a / k
/// a = a / x.
/// Truncated division.
pub const DIV = 0x30;
/// or: a = a | k
/// a = a | x.
pub const OR = 0x40;
/// and: a = a & k
/// a = a & x.
pub const AND = 0x50;
/// lsh: a = a << k
/// a = a << x.
/// a = a << k, a = a << x.
pub const LSH = 0x60;
/// rsh: a = a >> k
/// a = a >> x.
pub const RSH = 0x70;
/// neg: a = -a.
/// Note that this isn't a binary negation, rather the value of `~a + 1`.
pub const NEG = 0x80;
/// mod: a = a % k
/// a = a % x.
/// EXTENSION. Defined for:
/// - Linux.
/// - NetBSD + Minix 3.
/// - FreeBSD and derivitives.
pub const MOD = 0x90;
/// xor: a = a ^ k
/// a = a ^ x.
/// EXTENSION. Defined for:
/// - Linux.
/// - NetBSD + Minix 3.
/// - FreeBSD and derivitives.
pub const XOR = 0xa0;
// Jump operations using a comparison between a and x/k.
/// jmp L: pc += k.
/// No comparison done here.
pub const JA = 0x00;
/// jeq #k, Lt, Lf: pc += (a == k) ? jt : jf.
/// jeq x, Lt, Lf: pc += (a == x) ? jt : jf.
pub const JEQ = 0x10;
/// jgt #k, Lt, Lf: pc += (a > k) ? jt : jf.
/// jgt x, Lt, Lf: pc += (a > x) ? jt : jf.
pub const JGT = 0x20;
/// jge #k, Lt, Lf: pc += (a >= k) ? jt : jf.
/// jge x, Lt, Lf: pc += (a >= x) ? jt : jf.
pub const JGE = 0x30;
/// jset #k, Lt, Lf: pc += (a & k > 0) ? jt : jf.
/// jset x, Lt, Lf: pc += (a & x > 0) ? jt : jf.
pub const JSET = 0x40;
// Miscellaneous operations/register copy.
/// tax: x = a.
pub const TAX = 0x00;
/// txa: a = x.
pub const TXA = 0x80;
/// The 16 registers in the scratch memory store as named enums.
pub const Scratch = enum(u4) { m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15 };
pub const MEMWORDS = 16;
pub const MAXINSNS = switch (builtin.os.tag) {
.linux => 4096,
else => 512,
};
pub const MINBUFSIZE = 32;
pub const MAXBUFSIZE = 1 << 21;
pub const Insn = extern struct {
opcode: u16,
jt: u8,
jf: u8,
k: u32,
/// Implements the `std.fmt.format` API.
/// The formatting is similar to the output of tcpdump -dd.
pub fn format(
self: Insn,
comptime layout: []const u8,
opts: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = opts;
if (comptime layout.len != 0 and layout[0] != 's')
@compileError("Unsupported format specifier for BPF Insn type '" ++ layout ++ "'.");
try std.fmt.format(
writer,
"Insn{{ 0x{X:0<2}, {d}, {d}, 0x{X:0<8} }}",
.{ self.opcode, self.jt, self.jf, self.k },
);
}
const Size = enum(u8) {
word = W,
half_word = H,
byte = B,
};
fn stmt(opcode: u16, k: u32) Insn {
return .{
.opcode = opcode,
.jt = 0,
.jf = 0,
.k = k,
};
}
pub fn ld_imm(value: u32) Insn {
return stmt(LD | IMM, value);
}
pub fn ld_abs(size: Size, offset: u32) Insn {
return stmt(LD | ABS | @enumToInt(size), offset);
}
pub fn ld_ind(size: Size, offset: u32) Insn {
return stmt(LD | IND | @enumToInt(size), offset);
}
pub fn ld_mem(reg: Scratch) Insn {
return stmt(LD | MEM, @enumToInt(reg));
}
pub fn ld_len() Insn {
return stmt(LD | LEN | W, 0);
}
pub fn ld_rnd() Insn {
return stmt(LD | RND | W, 0);
}
pub fn ldx_imm(value: u32) Insn {
return stmt(LDX | IMM, value);
}
pub fn ldx_mem(reg: Scratch) Insn {
return stmt(LDX | MEM, @enumToInt(reg));
}
pub fn ldx_len() Insn {
return stmt(LDX | LEN | W, 0);
}
pub fn ldx_msh(offset: u32) Insn {
return stmt(LDX | MSH | B, offset);
}
pub fn st(reg: Scratch) Insn {
return stmt(ST, @enumToInt(reg));
}
pub fn stx(reg: Scratch) Insn {
return stmt(STX, @enumToInt(reg));
}
const AluOp = enum(u16) {
add = ADD,
sub = SUB,
mul = MUL,
div = DIV,
@"or" = OR,
@"and" = AND,
lsh = LSH,
rsh = RSH,
mod = MOD,
xor = XOR,
};
const Source = enum(u16) {
k = K,
x = X,
};
const KOrX = union(Source) {
k: u32,
x: void,
};
pub fn alu_neg() Insn {
return stmt(ALU | NEG, 0);
}
pub fn alu(op: AluOp, source: KOrX) Insn {
return stmt(
ALU | @enumToInt(op) | @enumToInt(source),
if (source == .k) source.k else 0,
);
}
const JmpOp = enum(u16) {
jeq = JEQ,
jgt = JGT,
jge = JGE,
jset = JSET,
};
pub fn jmp_ja(location: u32) Insn {
return stmt(JMP | JA, location);
}
pub fn jmp(op: JmpOp, source: KOrX, jt: u8, jf: u8) Insn {
return Insn{
.opcode = JMP | @enumToInt(op) | @enumToInt(source),
.jt = jt,
.jf = jf,
.k = if (source == .k) source.k else 0,
};
}
const Verdict = enum(u16) {
k = K,
a = A,
};
const KOrA = union(Verdict) {
k: u32,
a: void,
};
pub fn ret(verdict: KOrA) Insn {
return stmt(
RET | @enumToInt(verdict),
if (verdict == .k) verdict.k else 0,
);
}
pub fn tax() Insn {
return stmt(MISC | TAX, 0);
}
pub fn txa() Insn {
return stmt(MISC | TXA, 0);
}
};
fn opcodeEqual(opcode: u16, insn: Insn) !void {
try expectEqual(opcode, insn.opcode);
}
test "opcodes" {
try opcodeEqual(0x00, Insn.ld_imm(0));
try opcodeEqual(0x20, Insn.ld_abs(.word, 0));
try opcodeEqual(0x28, Insn.ld_abs(.half_word, 0));
try opcodeEqual(0x30, Insn.ld_abs(.byte, 0));
try opcodeEqual(0x40, Insn.ld_ind(.word, 0));
try opcodeEqual(0x48, Insn.ld_ind(.half_word, 0));
try opcodeEqual(0x50, Insn.ld_ind(.byte, 0));
try opcodeEqual(0x60, Insn.ld_mem(.m0));
try opcodeEqual(0x80, Insn.ld_len());
try opcodeEqual(0xc0, Insn.ld_rnd());
try opcodeEqual(0x01, Insn.ldx_imm(0));
try opcodeEqual(0x61, Insn.ldx_mem(.m0));
try opcodeEqual(0x81, Insn.ldx_len());
try opcodeEqual(0xb1, Insn.ldx_msh(0));
try opcodeEqual(0x02, Insn.st(.m0));
try opcodeEqual(0x03, Insn.stx(.m0));
try opcodeEqual(0x04, Insn.alu(.add, .{ .k = 0 }));
try opcodeEqual(0x14, Insn.alu(.sub, .{ .k = 0 }));
try opcodeEqual(0x24, Insn.alu(.mul, .{ .k = 0 }));
try opcodeEqual(0x34, Insn.alu(.div, .{ .k = 0 }));
try opcodeEqual(0x44, Insn.alu(.@"or", .{ .k = 0 }));
try opcodeEqual(0x54, Insn.alu(.@"and", .{ .k = 0 }));
try opcodeEqual(0x64, Insn.alu(.lsh, .{ .k = 0 }));
try opcodeEqual(0x74, Insn.alu(.rsh, .{ .k = 0 }));
try opcodeEqual(0x94, Insn.alu(.mod, .{ .k = 0 }));
try opcodeEqual(0xa4, Insn.alu(.xor, .{ .k = 0 }));
try opcodeEqual(0x84, Insn.alu_neg());
try opcodeEqual(0x0c, Insn.alu(.add, .x));
try opcodeEqual(0x1c, Insn.alu(.sub, .x));
try opcodeEqual(0x2c, Insn.alu(.mul, .x));
try opcodeEqual(0x3c, Insn.alu(.div, .x));
try opcodeEqual(0x4c, Insn.alu(.@"or", .x));
try opcodeEqual(0x5c, Insn.alu(.@"and", .x));
try opcodeEqual(0x6c, Insn.alu(.lsh, .x));
try opcodeEqual(0x7c, Insn.alu(.rsh, .x));
try opcodeEqual(0x9c, Insn.alu(.mod, .x));
try opcodeEqual(0xac, Insn.alu(.xor, .x));
try opcodeEqual(0x05, Insn.jmp_ja(0));
try opcodeEqual(0x15, Insn.jmp(.jeq, .{ .k = 0 }, 0, 0));
try opcodeEqual(0x25, Insn.jmp(.jgt, .{ .k = 0 }, 0, 0));
try opcodeEqual(0x35, Insn.jmp(.jge, .{ .k = 0 }, 0, 0));
try opcodeEqual(0x45, Insn.jmp(.jset, .{ .k = 0 }, 0, 0));
try opcodeEqual(0x1d, Insn.jmp(.jeq, .x, 0, 0));
try opcodeEqual(0x2d, Insn.jmp(.jgt, .x, 0, 0));
try opcodeEqual(0x3d, Insn.jmp(.jge, .x, 0, 0));
try opcodeEqual(0x4d, Insn.jmp(.jset, .x, 0, 0));
try opcodeEqual(0x06, Insn.ret(.{ .k = 0 }));
try opcodeEqual(0x16, Insn.ret(.a));
try opcodeEqual(0x07, Insn.tax());
try opcodeEqual(0x87, Insn.txa());
}
pub const Error = error{
InvalidOpcode,
InvalidOffset,
InvalidLocation,
DivisionByZero,
NoReturn,
};
/// A simple implementation of the BPF virtual-machine.
/// Use this to run/debug programs.
pub fn simulate(
packet: []const u8,
filter: []const Insn,
byte_order: std.builtin.Endian,
) Error!u32 {
assert(filter.len > 0 and filter.len < MAXINSNS);
assert(packet.len < MAXBUFSIZE);
const len = @intCast(u32, packet.len);
var a: u32 = 0;
var x: u32 = 0;
var m = mem.zeroes([MEMWORDS]u32);
var pc: usize = 0;
while (pc < filter.len) : (pc += 1) {
const i = filter[pc];
// Cast to a wider type to protect against overflow.
const k = @as(u64, i.k);
const remaining = filter.len - (pc + 1);
// Do validation/error checking here to compress the second switch.
switch (i.opcode) {
LD | ABS | W => if (k + @sizeOf(u32) - 1 >= packet.len) return error.InvalidOffset,
LD | ABS | H => if (k + @sizeOf(u16) - 1 >= packet.len) return error.InvalidOffset,
LD | ABS | B => if (k >= packet.len) return error.InvalidOffset,
LD | IND | W => if (k + x + @sizeOf(u32) - 1 >= packet.len) return error.InvalidOffset,
LD | IND | H => if (k + x + @sizeOf(u16) - 1 >= packet.len) return error.InvalidOffset,
LD | IND | B => if (k + x >= packet.len) return error.InvalidOffset,
LDX | MSH | B => if (k >= packet.len) return error.InvalidOffset,
ST, STX, LD | MEM, LDX | MEM => if (i.k >= MEMWORDS) return error.InvalidOffset,
JMP | JA => if (remaining <= i.k) return error.InvalidOffset,
JMP | JEQ | K,
JMP | JGT | K,
JMP | JGE | K,
JMP | JSET | K,
JMP | JEQ | X,
JMP | JGT | X,
JMP | JGE | X,
JMP | JSET | X,
=> if (remaining <= i.jt or remaining <= i.jf) return error.InvalidLocation,
else => {},
}
switch (i.opcode) {
LD | IMM => a = i.k,
LD | MEM => a = m[i.k],
LD | LEN | W => a = len,
LD | RND | W => a = random.int(u32),
LD | ABS | W => a = mem.readInt(u32, packet[i.k..][0..@sizeOf(u32)], byte_order),
LD | ABS | H => a = mem.readInt(u16, packet[i.k..][0..@sizeOf(u16)], byte_order),
LD | ABS | B => a = packet[i.k],
LD | IND | W => a = mem.readInt(u32, packet[i.k + x ..][0..@sizeOf(u32)], byte_order),
LD | IND | H => a = mem.readInt(u16, packet[i.k + x ..][0..@sizeOf(u16)], byte_order),
LD | IND | B => a = packet[i.k + x],
LDX | IMM => x = i.k,
LDX | MEM => x = m[i.k],
LDX | LEN | W => x = len,
LDX | MSH | B => x = @as(u32, @truncate(u4, packet[i.k])) << 2,
ST => m[i.k] = a,
STX => m[i.k] = x,
ALU | ADD | K => a +%= i.k,
ALU | SUB | K => a -%= i.k,
ALU | MUL | K => a *%= i.k,
ALU | DIV | K => a = try math.divTrunc(u32, a, i.k),
ALU | OR | K => a |= i.k,
ALU | AND | K => a &= i.k,
ALU | LSH | K => a = math.shl(u32, a, i.k),
ALU | RSH | K => a = math.shr(u32, a, i.k),
ALU | MOD | K => a = try math.mod(u32, a, i.k),
ALU | XOR | K => a ^= i.k,
ALU | ADD | X => a +%= x,
ALU | SUB | X => a -%= x,
ALU | MUL | X => a *%= x,
ALU | DIV | X => a = try math.divTrunc(u32, a, x),
ALU | OR | X => a |= x,
ALU | AND | X => a &= x,
ALU | LSH | X => a = math.shl(u32, a, x),
ALU | RSH | X => a = math.shr(u32, a, x),
ALU | MOD | X => a = try math.mod(u32, a, x),
ALU | XOR | X => a ^= x,
ALU | NEG => a = @bitCast(u32, -%@bitCast(i32, a)),
JMP | JA => pc += i.k,
JMP | JEQ | K => pc += if (a == i.k) i.jt else i.jf,
JMP | JGT | K => pc += if (a > i.k) i.jt else i.jf,
JMP | JGE | K => pc += if (a >= i.k) i.jt else i.jf,
JMP | JSET | K => pc += if (a & i.k > 0) i.jt else i.jf,
JMP | JEQ | X => pc += if (a == x) i.jt else i.jf,
JMP | JGT | X => pc += if (a > x) i.jt else i.jf,
JMP | JGE | X => pc += if (a >= x) i.jt else i.jf,
JMP | JSET | X => pc += if (a & x > 0) i.jt else i.jf,
RET | K => return i.k,
RET | A => return a,
MISC | TAX => x = a,
MISC | TXA => a = x,
else => return error.InvalidOpcode,
}
}
return error.NoReturn;
}
// This program is the BPF form of the tcpdump filter:
//
// tcpdump -dd 'ip host mirror.internode.on.net and tcp port ftp-data'
//
// As of January 2022, mirror.internode.on.net resolves to 172.16.17.32
//
// For reference, here's what it looks like in BPF assembler.
// Note that the jumps are used for TCP/IP layer checks.
//
// ```
// ldh [12] (#proto)
// jeq #0x0800 (ETHERTYPE_IP), L1, fail
// L1: ld [26]
// jeq #172.16.17.32, L2, dest
// dest: ld [30]
// jeq #172.16.17.32, L2, fail
// L2: ldb [23]
// jeq #0x6 (IPPROTO_TCP), L3, fail
// L3: ldh [20]
// jset #0x1fff, fail, plen
// plen: ldx 4 * ([14] & 0xf)
// ldh [x + 14]
// jeq #0x14 (FTP), pass, dstp
// dstp: ldh [x + 16]
// jeq #0x14 (FTP), pass, fail
// pass: ret #0x40000
// fail: ret #0
// ```
const tcpdump_filter = [_]Insn{
Insn.ld_abs(.half_word, 12),
Insn.jmp(.jeq, .{ .k = 0x800 }, 0, 14),
Insn.ld_abs(.word, 26),
Insn.jmp(.jeq, .{ .k = 0x96658703 }, 2, 0),
Insn.ld_abs(.word, 30),
Insn.jmp(.jeq, .{ .k = 0x96658703 }, 0, 10),
Insn.ld_abs(.byte, 23),
Insn.jmp(.jeq, .{ .k = 0x6 }, 0, 8),
Insn.ld_abs(.half_word, 20),
Insn.jmp(.jset, .{ .k = 0x1fff }, 6, 0),
Insn.ldx_msh(14),
Insn.ld_ind(.half_word, 14),
Insn.jmp(.jeq, .{ .k = 0x14 }, 2, 0),
Insn.ld_ind(.half_word, 16),
Insn.jmp(.jeq, .{ .k = 0x14 }, 0, 1),
Insn.ret(.{ .k = 0x40000 }),
Insn.ret(.{ .k = 0 }),
};
// This packet is the output of `ls` on mirror.internode.on.net:/, captured
// using the filter above.
//
// zig fmt: off
const ftp_data = [_]u8{
// ethernet - 14 bytes: IPv4(0x0800) from a4:71:74:ad:4b:f0 -> de:ad:be:ef:f0:0f
0xde, 0xad, 0xbe, 0xef, 0xf0, 0x0f, 0xa4, 0x71, 0x74, 0xad, 0x4b, 0xf0, 0x08, 0x00,
// IPv4 - 20 bytes: TCP data from 172.16.17.32 -> 192.168.1.3
0x45, 0x00, 0x01, 0xf2, 0x70, 0x3b, 0x40, 0x00, 0x37, 0x06, 0xf2, 0xb6,
0x96, 0x65, 0x87, 0x03, 0xc0, 0xa8, 0x01, 0x03,
// TCP - 32 bytes: Source port: 20 (FTP). Payload = 446 bytes
0x00, 0x14, 0x80, 0x6d, 0x35, 0x81, 0x2d, 0x40, 0x4f, 0x8a, 0x29, 0x9e, 0x80, 0x18, 0x00, 0x2e,
0x88, 0x8d, 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x0b, 0x59, 0x5d, 0x09, 0x32, 0x8b, 0x51, 0xa0
} ++
// Raw line-based FTP data - 446 bytes
"lrwxrwxrwx 1 root root 12 Feb 14 2012 debian -> .pub2/debian\r\n" ++
"lrwxrwxrwx 1 root root 15 Feb 14 2012 debian-cd -> .pub2/debian-cd\r\n" ++
"lrwxrwxrwx 1 root root 9 Mar 9 2018 linux -> pub/linux\r\n" ++
"drwxr-xr-X 3 mirror mirror 4096 Sep 20 08:10 pub\r\n" ++
"lrwxrwxrwx 1 root root 12 Feb 14 2012 ubuntu -> .pub2/ubuntu\r\n" ++
"-rw-r--r-- 1 root root 1044 Jan 20 2015 welcome.msg\r\n";
// zig fmt: on
test "tcpdump filter" {
try expectEqual(
@as(u32, 0x40000),
try simulate(ftp_data, &tcpdump_filter, .Big),
);
}
fn expectPass(data: anytype, filter: []Insn) !void {
try expectEqual(
@as(u32, 0),
try simulate(mem.asBytes(data), filter, .Big),
);
}
fn expectFail(expected_error: anyerror, data: anytype, filter: []Insn) !void {
try expectError(
expected_error,
simulate(mem.asBytes(data), filter, native_endian),
);
}
test "simulator coverage" {
const some_data: packed struct {
foo: u32,
bar: u8,
} = .{
.foo = mem.nativeToBig(u32, 0xaabbccdd),
.bar = 0x7f,
};
try expectPass(&some_data, &.{
// ld #10
// ldx #1
// st M[0]
// stx M[1]
// fail if A != 10
Insn.ld_imm(10),
Insn.ldx_imm(1),
Insn.st(.m0),
Insn.stx(.m1),
Insn.jmp(.jeq, .{ .k = 10 }, 1, 0),
Insn.ret(.{ .k = 1 }),
// ld [0]
// fail if A != 0xaabbccdd
Insn.ld_abs(.word, 0),
Insn.jmp(.jeq, .{ .k = 0xaabbccdd }, 1, 0),
Insn.ret(.{ .k = 2 }),
// ldh [0]
// fail if A != 0xaabb
Insn.ld_abs(.half_word, 0),
Insn.jmp(.jeq, .{ .k = 0xaabb }, 1, 0),
Insn.ret(.{ .k = 3 }),
// ldb [0]
// fail if A != 0xaa
Insn.ld_abs(.byte, 0),
Insn.jmp(.jeq, .{ .k = 0xaa }, 1, 0),
Insn.ret(.{ .k = 4 }),
// ld [x + 0]
// fail if A != 0xbbccdd7f
Insn.ld_ind(.word, 0),
Insn.jmp(.jeq, .{ .k = 0xbbccdd7f }, 1, 0),
Insn.ret(.{ .k = 5 }),
// ldh [x + 0]
// fail if A != 0xbbcc
Insn.ld_ind(.half_word, 0),
Insn.jmp(.jeq, .{ .k = 0xbbcc }, 1, 0),
Insn.ret(.{ .k = 6 }),
// ldb [x + 0]
// fail if A != 0xbb
Insn.ld_ind(.byte, 0),
Insn.jmp(.jeq, .{ .k = 0xbb }, 1, 0),
Insn.ret(.{ .k = 7 }),
// ld M[0]
// fail if A != 10
Insn.ld_mem(.m0),
Insn.jmp(.jeq, .{ .k = 10 }, 1, 0),
Insn.ret(.{ .k = 8 }),
// ld #len
// fail if A != 5
Insn.ld_len(),
Insn.jmp(.jeq, .{ .k = @sizeOf(@TypeOf(some_data)) }, 1, 0),
Insn.ret(.{ .k = 9 }),
// ld #0
// ld arc4random()
// fail if A == 0
Insn.ld_imm(0),
Insn.ld_rnd(),
Insn.jmp(.jgt, .{ .k = 0 }, 1, 0),
Insn.ret(.{ .k = 10 }),
// ld #3
// ldx #10
// st M[2]
// txa
// fail if a != x
Insn.ld_imm(3),
Insn.ldx_imm(10),
Insn.st(.m2),
Insn.txa(),
Insn.jmp(.jeq, .x, 1, 0),
Insn.ret(.{ .k = 11 }),
// ldx M[2]
// fail if A <= X
Insn.ldx_mem(.m2),
Insn.jmp(.jgt, .x, 1, 0),
Insn.ret(.{ .k = 12 }),
// ldx #len
// fail if a <= x
Insn.ldx_len(),
Insn.jmp(.jgt, .x, 1, 0),
Insn.ret(.{ .k = 13 }),
// a = 4 * (0x7f & 0xf)
// x = 4 * ([4] & 0xf)
// fail if a != x
Insn.ld_imm(4 * (0x7f & 0xf)),
Insn.ldx_msh(4),
Insn.jmp(.jeq, .x, 1, 0),
Insn.ret(.{ .k = 14 }),
// ld #(u32)-1
// ldx #2
// add #1
// fail if a != 0
Insn.ld_imm(0xffffffff),
Insn.ldx_imm(2),
Insn.alu(.add, .{ .k = 1 }),
Insn.jmp(.jeq, .{ .k = 0 }, 1, 0),
Insn.ret(.{ .k = 15 }),
// sub #1
// fail if a != (u32)-1
Insn.alu(.sub, .{ .k = 1 }),
Insn.jmp(.jeq, .{ .k = 0xffffffff }, 1, 0),
Insn.ret(.{ .k = 16 }),
// add x
// fail if a != 1
Insn.alu(.add, .x),
Insn.jmp(.jeq, .{ .k = 1 }, 1, 0),
Insn.ret(.{ .k = 17 }),
// sub x
// fail if a != (u32)-1
Insn.alu(.sub, .x),
Insn.jmp(.jeq, .{ .k = 0xffffffff }, 1, 0),
Insn.ret(.{ .k = 18 }),
// ld #16
// mul #2
// fail if a != 32
Insn.ld_imm(16),
Insn.alu(.mul, .{ .k = 2 }),
Insn.jmp(.jeq, .{ .k = 32 }, 1, 0),
Insn.ret(.{ .k = 19 }),
// mul x
// fail if a != 64
Insn.alu(.mul, .x),
Insn.jmp(.jeq, .{ .k = 64 }, 1, 0),
Insn.ret(.{ .k = 20 }),
// div #2
// fail if a != 32
Insn.alu(.div, .{ .k = 2 }),
Insn.jmp(.jeq, .{ .k = 32 }, 1, 0),
Insn.ret(.{ .k = 21 }),
// div x
// fail if a != 16
Insn.alu(.div, .x),
Insn.jmp(.jeq, .{ .k = 16 }, 1, 0),
Insn.ret(.{ .k = 22 }),
// or #4
// fail if a != 20
Insn.alu(.@"or", .{ .k = 4 }),
Insn.jmp(.jeq, .{ .k = 20 }, 1, 0),
Insn.ret(.{ .k = 23 }),
// or x
// fail if a != 22
Insn.alu(.@"or", .x),
Insn.jmp(.jeq, .{ .k = 22 }, 1, 0),
Insn.ret(.{ .k = 24 }),
// and #6
// fail if a != 6
Insn.alu(.@"and", .{ .k = 0b110 }),
Insn.jmp(.jeq, .{ .k = 6 }, 1, 0),
Insn.ret(.{ .k = 25 }),
// and x
// fail if a != 2
Insn.alu(.@"and", .x),
Insn.jmp(.jeq, .x, 1, 0),
Insn.ret(.{ .k = 26 }),
// xor #15
// fail if a != 13
Insn.alu(.xor, .{ .k = 0b1111 }),
Insn.jmp(.jeq, .{ .k = 0b1101 }, 1, 0),
Insn.ret(.{ .k = 27 }),
// xor x
// fail if a != 15
Insn.alu(.xor, .x),
Insn.jmp(.jeq, .{ .k = 0b1111 }, 1, 0),
Insn.ret(.{ .k = 28 }),
// rsh #1
// fail if a != 7
Insn.alu(.rsh, .{ .k = 1 }),
Insn.jmp(.jeq, .{ .k = 0b0111 }, 1, 0),
Insn.ret(.{ .k = 29 }),
// rsh x
// fail if a != 1
Insn.alu(.rsh, .x),
Insn.jmp(.jeq, .{ .k = 0b0001 }, 1, 0),
Insn.ret(.{ .k = 30 }),
// lsh #1
// fail if a != 2
Insn.alu(.lsh, .{ .k = 1 }),
Insn.jmp(.jeq, .{ .k = 0b0010 }, 1, 0),
Insn.ret(.{ .k = 31 }),
// lsh x
// fail if a != 8
Insn.alu(.lsh, .x),
Insn.jmp(.jeq, .{ .k = 0b1000 }, 1, 0),
Insn.ret(.{ .k = 32 }),
// mod 6
// fail if a != 2
Insn.alu(.mod, .{ .k = 6 }),
Insn.jmp(.jeq, .{ .k = 2 }, 1, 0),
Insn.ret(.{ .k = 33 }),
// mod x
// fail if a != 0
Insn.alu(.mod, .x),
Insn.jmp(.jeq, .{ .k = 0 }, 1, 0),
Insn.ret(.{ .k = 34 }),
// tax
// neg
// fail if a != (u32)-2
Insn.txa(),
Insn.alu_neg(),
Insn.jmp(.jeq, .{ .k = ~@as(u32, 2) + 1 }, 1, 0),
Insn.ret(.{ .k = 35 }),
// ja #1 (skip the next instruction)
Insn.jmp_ja(1),
Insn.ret(.{ .k = 36 }),
// ld #20
// tax
// fail if a != 20
// fail if a != x
Insn.ld_imm(20),
Insn.tax(),
Insn.jmp(.jeq, .{ .k = 20 }, 1, 0),
Insn.ret(.{ .k = 37 }),
Insn.jmp(.jeq, .x, 1, 0),
Insn.ret(.{ .k = 38 }),
// ld #19
// fail if a == 20
// fail if a == x
// fail if a >= 20
// fail if a >= X
Insn.ld_imm(19),
Insn.jmp(.jeq, .{ .k = 20 }, 0, 1),
Insn.ret(.{ .k = 39 }),
Insn.jmp(.jeq, .x, 0, 1),
Insn.ret(.{ .k = 40 }),
Insn.jmp(.jgt, .{ .k = 20 }, 0, 1),
Insn.ret(.{ .k = 41 }),
Insn.jmp(.jgt, .x, 0, 1),
Insn.ret(.{ .k = 42 }),
// ld #21
// fail if a < 20
// fail if a < x
Insn.ld_imm(21),
Insn.jmp(.jgt, .{ .k = 20 }, 1, 0),
Insn.ret(.{ .k = 43 }),
Insn.jmp(.jgt, .x, 1, 0),
Insn.ret(.{ .k = 44 }),
// ldx #22
// fail if a < 22
// fail if a < x
Insn.ldx_imm(22),
Insn.jmp(.jge, .{ .k = 22 }, 0, 1),
Insn.ret(.{ .k = 45 }),
Insn.jmp(.jge, .x, 0, 1),
Insn.ret(.{ .k = 46 }),
// ld #23
// fail if a >= 22
// fail if a >= x
Insn.ld_imm(23),
Insn.jmp(.jge, .{ .k = 22 }, 1, 0),
Insn.ret(.{ .k = 47 }),
Insn.jmp(.jge, .x, 1, 0),
Insn.ret(.{ .k = 48 }),
// ldx #0b10100
// fail if a & 0b10100 == 0
// fail if a & x == 0
Insn.ldx_imm(0b10100),
Insn.jmp(.jset, .{ .k = 0b10100 }, 1, 0),
Insn.ret(.{ .k = 47 }),
Insn.jmp(.jset, .x, 1, 0),
Insn.ret(.{ .k = 48 }),
// ldx #0
// fail if a & 0 > 0
// fail if a & x > 0
Insn.ldx_imm(0),
Insn.jmp(.jset, .{ .k = 0 }, 0, 1),
Insn.ret(.{ .k = 49 }),
Insn.jmp(.jset, .x, 0, 1),
Insn.ret(.{ .k = 50 }),
Insn.ret(.{ .k = 0 }),
});
try expectPass(&some_data, &.{
Insn.ld_imm(35),
Insn.ld_imm(0),
Insn.ret(.a),
});
// Errors
try expectFail(error.NoReturn, &some_data, &.{
Insn.ld_imm(10),
});
try expectFail(error.InvalidOpcode, &some_data, &.{
Insn.stmt(0x7f, 0xdeadbeef),
});
try expectFail(error.InvalidOffset, &some_data, &.{
Insn.stmt(LD | ABS | W, 10),
});
try expectFail(error.InvalidLocation, &some_data, &.{
Insn.jmp(.jeq, .{ .k = 0 }, 10, 0),
});
try expectFail(error.InvalidLocation, &some_data, &.{
Insn.jmp(.jeq, .{ .k = 0 }, 0, 10),
});
} | lib/std/x/net/bpf.zig |
const std = @import("std");
const unicode = std.unicode;
const mem = std.mem;
const warn = std.debug.warn;
const builtin = @import("builtin");
const path = std.fs.path;
const is_windows = builtin.os == .windows;
pub const MatchError = error{BadPattern};
/// reports whether name matches the shell file name pattern.
/// The pattern syntax is:
///
/// pattern:
/// { term }
/// term:
/// '*' matches any sequence of non-Separator characters
/// '?' matches any single non-Separator character
/// '[' [ '^' ] { character-range } ']'
/// character class (must be non-empty)
/// c matches character c (c != '*', '?', '\\', '[')
/// '\\' c matches character c
///
/// character-range:
/// c matches character c (c != '\\', '-', ']')
/// '\\' c matches character c
/// lo '-' hi matches character c for lo <= c <= hi
///
/// match requires pattern to match all of name, not just a substring.
/// The only possible returned error is ErrBadPattern, when pattern
/// is malformed.
///
/// On Windows, escaping is disabled. Instead, '\\' is treated as
/// path separator.
///
pub fn match(pattern_string: []const u8, name_string: []const u8) MatchError!bool {
var pattern = pattern_string;
var name = name_string;
PATTERN: while (pattern.len > 0) {
const s = scanChunk(pattern);
var star = s.star;
var chunk = s.chunk;
pattern = s.rest;
if (star and chunk.len == 0) {
return !contains(name, path.sep_str[0..]);
}
const c = try matchChunk(chunk, name);
if (c.ok and (c.rest.len == 0 or pattern.len > 0)) {
name = c.rest;
continue;
}
if (star) {
var i: usize = 0;
while (i < name.len and name[i] != path.sep) : (i += 1) {
const cc = try matchChunk(chunk, name[i + 1 ..]);
if (cc.ok) {
if (pattern.len == 0 and cc.rest.len > 0) {
continue;
}
name = cc.rest;
continue :PATTERN;
}
}
}
return false;
}
return name.len == 0;
}
const ScanChunkResult = struct {
star: bool,
chunk: []const u8,
rest: []const u8,
};
fn scanChunk(pattern_string: []const u8) ScanChunkResult {
var pattern = pattern_string;
var star = false;
while (pattern.len > 0 and pattern[0] == '*') {
pattern = pattern[1..];
star = true;
}
var in_range = false;
var i: usize = 0;
scan: while (i < pattern.len) : (i += 1) {
switch (pattern[i]) {
'\\' => {
if (!is_windows) {
if (i + 1 < pattern.len) {
i += 1;
}
}
},
'[' => {
in_range = true;
},
']' => {
in_range = false;
},
'*' => {
if (!in_range) {
break :scan;
}
},
else => {},
}
}
return ScanChunkResult{
.star = star,
.chunk = pattern[0..i],
.rest = pattern[i..],
};
}
const MatchChunkResult = struct {
rest: []const u8,
ok: bool,
};
fn matchChunk(chunks: []const u8, src: []const u8) MatchError!MatchChunkResult {
var chunk = chunks;
var s = src;
while (chunk.len > 0) {
if (s.len == 0) {
return MatchChunkResult{ .rest = "", .ok = false };
}
switch (chunk[0]) {
'[' => {
const r = decodeRune(s) catch |err| {
return error.BadPattern;
};
const n = runeLength(r) catch |e| {
return error.BadPattern;
};
s = s[n..];
chunk = chunk[1..];
if (chunk.len == 0) {
return error.BadPattern;
}
var negated = chunk[0] == '^';
if (negated) {
chunk = chunk[1..];
}
var matched = false;
var mrange: usize = 0;
while (true) {
if (chunk.len > 0 and chunk[0] == ']' and mrange > 0) {
chunk = chunk[1..];
break;
}
const e = try getEsc(chunk);
var lo = e.rune;
chunk = e.chunk;
var hi = lo;
if (chunk[0] == '-') {
const ee = try getEsc(chunk[1..]);
hi = ee.rune;
chunk = ee.chunk;
}
if (lo <= r and r <= hi) {
matched = true;
}
mrange += 1;
}
if (matched == negated) {
return MatchChunkResult{ .rest = "", .ok = false };
}
},
'?' => {
if (s[0] == path.sep) {
return MatchChunkResult{ .rest = "", .ok = false };
}
const r = decodeRune(s) catch |err| {
return error.BadPattern;
};
const n = runeLength(r) catch |e| {
return error.BadPattern;
};
s = s[n..];
chunk = chunk[1..];
},
'\\' => {
if (!is_windows) {
chunk = chunk[1..];
if (chunk.len == 0) {
return error.BadPattern;
}
}
if (chunk[0] != s[0]) {
return MatchChunkResult{ .rest = "", .ok = false };
}
s = s[1..];
chunk = chunk[1..];
},
else => {
if (chunk[0] != s[0]) {
return MatchChunkResult{ .rest = "", .ok = false };
}
s = s[1..];
chunk = chunk[1..];
},
}
}
return MatchChunkResult{ .rest = s, .ok = true };
}
const EscapeResult = struct {
rune: u32,
chunk: []const u8,
};
fn getEsc(chunk: []const u8) !EscapeResult {
if (chunk.len == 0 or chunk[0] == '-' or chunk[0] == ']') {
return error.BadPattern;
}
var e = EscapeResult{ .rune = 0, .chunk = chunk };
if (chunk[0] == '\\' and !is_windows) {
e.chunk = chunk[1..];
if (e.chunk.len == 0) {
return error.BadPattern;
}
}
const r = decodeRune(e.chunk) catch |err| {
return error.BadPattern;
};
const n = runeLength(r) catch |err| {
return error.BadPattern;
};
e.chunk = e.chunk[n..];
if (e.chunk.len == 0) {
return error.BadPattern;
}
e.rune = r;
return e;
}
fn runeLength(rune: u32) !usize {
return @intCast(usize, try unicode.utf8CodepointSequenceLength(rune));
}
fn contains(s: []const u8, needle: []const u8) bool {
return mem.indexOf(u8, s, needle) != null;
}
fn decodeRune(s: []const u8) !u32 {
const n = try unicode.utf8ByteSequenceLength(s[0]);
return unicode.utf8Decode(s[0..n]);
} | src/path/filepath/match.zig |
const std = @import("std");
const json = @import("../json.zig");
const common = @import("common.zig");
const general = @import("general.zig");
const language_features = @import("language_features.zig");
/// A request message to describe a request between the client and the server.
/// Every processed request must send a response back to the sender of the request.
///
/// [Docs](https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#requestMessage)
pub const RequestMessage = struct {
jsonrpc: []const u8 = "2.0",
/// The request id.
id: common.RequestId,
/// The method to be invoked.
method: []const u8,
/// The method's params.
params: RequestParams,
};
pub const RequestParams = union(enum) {
// General
initialize: general.InitializeParams,
// Window
// show_message_request
// show_document
// Language Features
completion: language_features.CompletionParams,
};
/// Params of a request (params)
pub const RequestParseTarget = union(enum) {
// General
initialize: common.Paramsify(general.InitializeParams),
// Language Features
completion: common.Paramsify(language_features.CompletionParams),
pub fn toMessage(self: RequestParseTarget) RequestMessage {
inline for (std.meta.fields(RequestParseTarget)) |field, i| {
if (@enumToInt(self) == i) {
return .{
.id = @field(self, field.name).id,
.method = @field(self, field.name).method,
.params = @unionInit(RequestParams, field.name, @field(self, field.name).params),
};
}
}
unreachable;
}
};
/// The base protocol offers support for request cancellation.
/// To cancel a request, a notification message with the following properties is sent.
///
/// [Docs](https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#cancelRequest)
pub const CancelParams = struct {
pub const method = "$/cancelRequest";
pub const kind = common.PacketKind.notification;
/// The request id to cancel.
id: common.RequestId,
};
pub const DidChangeWorkspaceFoldersParams = struct {
pub const method = "workspace/didChangeWorkspaceFolders";
pub const kind = common.PacketKind.notification;
event: struct {
added: []const common.WorkspaceFolder,
removed: []const common.WorkspaceFolder,
},
};
const TextDocumentIdentifierRequestParams = struct {
textDocument: common.TextDocumentIdentifier,
};
pub const TextDocumentSaveReason = enum(i64) {
/// Manually triggered, e.g. by the user pressing save, by starting
/// debugging, or by an API call.
manual = 1,
/// Automatic after a delay.
after_delay = 2,
/// When the editor lost focus.
focus_out = 3,
usingnamespace common.EnumStringify(@This());
};
pub const SaveDocument = struct {
comptime method: []const u8 = "textDocument/willSave",
params: struct {
textDocument: common.TextDocumentIdentifier,
reason: TextDocumentSaveReason,
},
};
pub const CloseDocument = struct {
comptime method: []const u8 = "textDocument/didClose",
params: TextDocumentIdentifierRequestParams,
};
pub const SemanticTokensFull = struct {
params: TextDocumentIdentifierRequestParams,
};
const TextDocumentIdentifierPositionRequest = struct {
textDocument: common.TextDocumentIdentifier,
position: common.Position,
};
pub const SignatureHelp = struct {
comptime method: []const u8 = "textDocument/signatureHelp",
params: struct {
textDocument: common.TextDocumentIdentifier,
position: common.Position,
context: ?struct {
triggerKind: enum(u32) {
invoked = 1,
trigger_character = 2,
content_change = 3,
},
triggerCharacter: ?[]const u8,
isRetrigger: bool,
activeSignatureHelp: ?common.SignatureHelp,
},
},
};
pub const GotoDefinition = TextDocumentIdentifierPositionRequest;
pub const GotoDeclaration = TextDocumentIdentifierPositionRequest;
pub const Hover = TextDocumentIdentifierPositionRequest;
pub const DocumentSymbols = struct {
params: TextDocumentIdentifierRequestParams,
};
pub const Formatting = struct {
params: TextDocumentIdentifierRequestParams,
};
pub const Rename = struct {
params: struct {
textDocument: common.TextDocumentIdentifier,
position: common.Position,
newName: []const u8,
},
};
pub const References = struct {
params: struct {
textDocument: common.TextDocumentIdentifier,
position: common.Position,
context: struct {
includeDeclaration: bool,
},
},
}; | src/types/requests.zig |
const std = @import("std");
const pkmn = @import("pkmn");
const protocol = pkmn.protocol;
const Tool = enum {
markdown,
protocol,
layout,
};
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
const args = try std.process.argsAlloc(allocator);
defer std.process.argsFree(allocator, args);
if (args.len != 2) usageAndExit(args[0]);
var tool: Tool = undefined;
if (std.mem.eql(u8, args[1], "markdown")) {
tool = .markdown;
} else if (std.mem.eql(u8, args[1], "protocol")) {
tool = .protocol;
} else if (std.mem.eql(u8, args[1], "layout")) {
tool = .layout;
} else {
usageAndExit(args[0]);
}
const out = std.io.getStdOut();
var buf = std.io.bufferedWriter(out.writer());
var w = buf.writer();
switch (tool) {
.markdown => {
inline for (@typeInfo(protocol).Struct.decls) |decl| {
if (@TypeOf(@field(protocol, decl.name)) == type) {
switch (@typeInfo(@field(protocol, decl.name))) {
.Enum => |e| {
try w.print(
"## {s}\n\n<details><summary>Reason</summary>\n",
.{decl.name},
);
try w.writeAll("\n|Raw|Description|\n|--|--|\n");
inline for (e.fields) |field| {
try w.print("|`0x{X:0>2}`|`{s}`|\n", .{ field.value, field.name });
}
try w.writeAll("</details>\n\n");
},
else => {},
}
}
}
},
.protocol => {
var outer = false;
try w.writeAll("{\n");
inline for (@typeInfo(protocol).Struct.decls) |decl| {
if (@TypeOf(@field(protocol, decl.name)) == type) {
switch (@typeInfo(@field(protocol, decl.name))) {
.Enum => |e| {
if (outer) try w.writeAll(",\n");
try w.print(" \"{s}\": [\n", .{decl.name});
var inner = false;
inline for (e.fields) |field| {
if (inner) try w.writeAll(",\n");
try w.print(" \"{s}\"", .{field.name});
inner = true;
}
try w.writeAll("\n ]");
outer = true;
},
else => {},
}
}
}
try w.writeAll("\n}\n");
},
.layout => {
try w.writeAll("[\n");
{
try w.writeAll(" {\n \"sizes\": {\n");
{
try w.print(
" \"{s}\": {d},\n",
.{ "Battle", @sizeOf(pkmn.gen1.Battle(pkmn.gen1.PRNG)) },
);
try w.print(
" \"{s}\": {d},\n",
.{ "Side", @sizeOf(pkmn.gen1.Side) },
);
try w.print(
" \"{s}\": {d},\n",
.{ "Pokemon", @sizeOf(pkmn.gen1.Pokemon) },
);
try w.print(
" \"{s}\": {d}\n",
.{ "ActivePokemon", @sizeOf(pkmn.gen1.ActivePokemon) },
);
}
try w.writeAll(" },\n");
try w.writeAll(" \"offsets\": {\n");
{
try print(w, "Battle", pkmn.gen1.Battle(pkmn.gen1.PRNG), false);
try w.writeAll(",\n");
try print(w, "Side", pkmn.gen1.Side, false);
try w.writeAll(",\n");
try print(w, "Pokemon", pkmn.gen1.Pokemon, false);
try w.writeAll(",\n");
try print(w, "ActivePokemon", pkmn.gen1.ActivePokemon, false);
try w.writeAll(",\n");
try print(w, "Stats", pkmn.gen1.Stats(u16), false);
try w.writeAll(",\n");
try print(w, "Boosts", pkmn.gen1.Boosts, true);
try w.writeAll(",\n");
try print(w, "Volatiles", pkmn.gen1.Volatiles, true);
try w.writeAll("\n }\n");
}
try w.writeAll(" }\n");
}
try w.writeAll("]\n");
},
}
try buf.flush();
}
fn print(w: anytype, name: []const u8, comptime T: type, comptime bits: bool) !void {
try w.print(" \"{s}\": {{\n", .{name});
var inner = false;
inline for (std.meta.fields(T)) |field| {
if (field.name[0] != '_') {
if (inner) try w.writeAll(",\n");
const offset = @bitOffsetOf(T, field.name);
try w.print(" \"{s}\": {d}", .{ field.name, if (bits) offset else offset / 8 });
inner = true;
}
}
try w.writeAll("\n }");
}
fn usageAndExit(cmd: []const u8) noreturn {
const err = std.io.getStdErr().writer();
err.print("Usage: {s} <markdown|protocol|layout>\n", .{cmd}) catch {};
std.process.exit(1);
} | src/tools/protocol.zig |
pub const CompositorOutput = backends.BackendOutput(Output);
pub var OUTPUTS: Stalloc(void, CompositorOutput, 16) = undefined;
pub const OUTPUT_BASE: usize = 1000;
pub const Output = struct {
views: [4]View,
const Self = @This();
pub fn deinit(self: *Self) !void {
var parent = @fieldParentPtr(CompositorOutput, "data", self);
var freed_index = OUTPUTS.deinit(parent);
// Inform all clients that have bound this output
// that it is going away
var client_it = clients.CLIENTS.iterator();
while (client_it.next()) |client| {
var obj_it = client.context.objects.iterator();
while (obj_it.next()) |wl_object_entry| {
var wl_object = wl_object_entry.value_ptr;
if (@ptrToInt(self) == wl_object.container) {
// TODO: in release mode do not error
const wl_registry_id = client.wl_registry_id orelse return error.ClientHasNoRegistry;
const wl_registry = client.context.get(wl_registry_id) orelse return error.ContextHasNoRegistry;
try prot.wl_registry_send_global_remove(wl_registry, @intCast(u32, OUTPUT_BASE + freed_index));
std.debug.warn("OUTPUTS[{}] removed from CLIENTS[{}] (wl_output@{})\n", .{ freed_index, client.getIndexOf(), wl_object.id });
}
}
}
}
pub fn getIndexOf(self: *Self) usize {
return OUTPUTS.getIndexOf(self);
}
};
pub fn newOutput(backend: *CompositorBackend, width: i32, height: i32) !*CompositorOutput {
var output: *CompositorOutput = try OUTPUTS.new(undefined);
output.* = try backend.newOutput(width, height);
for (output.data.views) |*view| {
view.* = views.makeView(output);
}
var it = clients.CLIENTS.iterator();
while (it.next()) |client| {
// TODO: in release mode do not error
const wl_registry_id = client.wl_registry_id orelse return error.ClientHasNoRegistry;
const wl_registry = client.context.get(wl_registry_id) orelse return error.ContextHasNoRegistry;
const global_id = @intCast(u32, OUTPUTS.getIndexOf(output) + OUTPUT_BASE);
try prot.wl_registry_send_global(wl_registry, global_id, "wl_output\x00", 2);
}
return output;
}
const std = @import("std");
const clients = @import("client.zig");
const prot = @import("protocols.zig");
const views = @import("view.zig");
const backends = @import("backend/backend.zig");
const Stalloc = @import("stalloc.zig").Stalloc;
const View = @import("view.zig").View;
const CompositorBackend = @import("backend/backend.zig").Backend(Output); | src/output.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/day10.txt");
const example_data =
\\[({(<(())[]>[[{[]{<()<>>
\\[(()[<>])]({[<{<<[]>>(
\\{([(<{}[<>[]}>{[]{[(<()>
\\(((({<>}<{<{<>}{[]{[]{}
\\[[<[([]))<([[{}[[()]]]
\\[{[{({}]{}}([{[{{{}}([]
\\{<[[]]>}<{[{[{[]{()[[[]
\\[<(<(<(<{}))><([]([]()
\\<{([([[(<>()){}]>(<<{{
\\<{([{{}}[<[[[<>{}]]]>[]]
;
//const data = example_data;
pub fn main() !void {
const input: [][]u8 = blk: {
var list = std.ArrayList([]u8).init(gpa);
var iter = tokenize(u8, data, "\r\n");
while (iter.next()) |line| {
var list2 = std.ArrayList(u8).init(gpa);
for (line) |c| {
try list2.append(c);
}
try list.append(list2.toOwnedSlice());
}
break :blk list.toOwnedSlice();
};
{
var part1: u64 = 0;
var part2 = std.ArrayList(u64).init(gpa);
for (input) |line, line_index| {
var stack = std.ArrayList(u8).init(gpa);
const result: Result = for (line) |c, col_index| {
switch(c) {
'(', '[', '{', '<' => try stack.append(c),
')', ']', '}', '>' => {
const last_or_null = stack.popOrNull();
if (last_or_null) |last| {
if (isMatch(last, c)) {
continue;
} else {
break Result{.corrupted = c};
}
} else {
print("{d}:{s} :: {d}:{c}\n", .{line_index, line, col_index, c});
unreachable; // not sure how to articulate this property of our puzzle input
}
},
else => {
print("{d}:{s} :: {d}:{c}\n", .{line_index, line, col_index, c});
unreachable;
},
}
} else blk: {
if (stack.items.len == 0) {
break :blk .complete;
} else {
break :blk Result{.incomplete = stack.toOwnedSlice()};
}
};
switch (result) {
Result.complete => {},
Result.incomplete => |s| {
var score: u64 = 0;
std.mem.reverse(u8, s);
for (s) |c| {
score *= 5;
switch (c) {
'(' => score += 1,
'[' => score += 2,
'{' => score += 3,
'<' => score += 4,
else => unreachable,
}
}
try part2.append(score);
//print("{d}: {s}\n", .{score, s});
},
Result.corrupted => |c| switch (c) {
')' => part1 += 3,
']' => part1 += 57,
'}' => part1 += 1197,
'>' => part1 += 25137,
else => unreachable,
}
}
}
print("{d}\n", .{part1});
sort(u64, part2.items, {}, comptime asc(u64));
const middle_index = part2.items.len / 2;
print("{d}\n", .{part2.items[middle_index]});
}
}
const Result = union(enum) {
complete: void,
incomplete: []u8,
corrupted: u8,
};
fn isMatch(fst: u8, snd: u8) bool {
const expected_snd: u8 = switch(fst) {
'(' => ')',
'[' => ']',
'{' => '}',
'<' => '>',
else => unreachable,
};
return if (snd == expected_snd) true else false;
}
// 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/day10.zig |
//***************************************************************
// library imports
//***************************************************************
const std = @import("std");
const stdin = std.io.getStdIn();
const warn = std.debug.warn;
const fmt = std.fmt;
//***************************************************************
//***************************************************************
// global variables
//***************************************************************
var n: u16 = 0;
var x: f32 = 0.0;
var y: f32 = 0.0;
var sum_x: f32 = 0.0;
var sum_xx: f32 = 0.0;
var sum_y: f32 = 0.0;
var sum_yy: f32 = 0;
var sum_xy: f32 = 0.0;
//***************************************************************
pub fn main() !void {
warn("\nLR - perform linear regeression", .{});
warn("\nHow many (x, y) pairs? ", .{});
var num_buf: [20]u8 = undefined;
const amt = try stdin.read(&num_buf);
const line = std.mem.trimRight(u8, num_buf[0..amt], " \r\n\t");
while (true) {
const num = std.fmt.parseUnsigned(u16, line, 10) catch {
continue;
};
if (n == num) {
break;
}
n += 1; // loop counter
warn("\nPair: {}", .{n});
warn("\nEnter x: ", .{});
var x_buf: [20]u8 = undefined;
const x_len = try stdin.read(&x_buf);
const x_line = std.mem.trimRight(u8, x_buf[0..x_len], " \r\n\t");
x = std.fmt.parseFloat(f32, x_line) catch {
continue;
};
warn("Enter y: ", .{});
var y_buf: [20]u8 = undefined;
const y_len = try stdin.read(&y_buf);
const y_line = std.mem.trimRight(u8, y_buf[0..y_len], " \r\n\t");
y = std.fmt.parseFloat(f32, y_line) catch {
continue;
};
sum_x += x;
sum_xx += x * x;
sum_y += y;
sum_yy += y * y;
sum_xy += x * y;
}
warn("\n]- total N = {}", .{n});
const N = @intToFloat(f32, n);
const m = (N * sum_xy - sum_x * sum_y) / (N * sum_xx - @exp2(sum_x));
const b = (sum_y * sum_xx - sum_x * sum_xy) / (N * sum_xx - @exp2(sum_x));
const r = (sum_xy - sum_x * sum_y / N) / @sqrt((sum_xx - @exp2(sum_x) / N) * (@exp2(sum_y) / 2));
//**************************************************************
// print results
//**************************************************************
warn("\n]- slope m = {}", .{m});
warn("\n]- y-intercept b = {}", .{b});
warn("\n]- correlation r = {}\n", .{r});
} | zig/lr.zig |
const std = @import("std");
const assert = std.debug.assert;
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var input_file = try std.fs.cwd().openFile("input/09.txt", .{});
defer input_file.close();
var buffered_reader = std.io.bufferedReader(input_file.reader());
const risk_level = try calculateRiskLevel(allocator, buffered_reader.reader());
std.debug.print("sum of risk levels: {}\n", .{risk_level});
}
fn calculateRiskLevel(gpa: std.mem.Allocator, reader: anytype) !u64 {
var arena = std.heap.ArenaAllocator.init(gpa);
defer arena.deinit();
const allocator = arena.allocator();
var buf: [4096]u8 = undefined;
var height_map_array_list = std.ArrayList(u8).init(allocator);
var width: u64 = 0;
while (try reader.readUntilDelimiterOrEof(&buf, '\n')) |line| {
assert(line.len > 0); // empty line
if (width > 0) assert(width == line.len); // different line lengths
width = line.len;
try height_map_array_list.appendSlice(line);
}
const height_map = height_map_array_list.items;
var sum: u64 = 0;
for (height_map) |x, i| {
const lower_than_north = i < width or x < height_map[i - width];
const lower_than_south = i >= height_map.len - width or x < height_map[i + width];
const lower_than_west = i % width < 1 or x < height_map[i - 1];
const lower_than_east = i % width >= width - 1 or x < height_map[i + 1];
if (lower_than_north and lower_than_south and lower_than_west and lower_than_east) {
sum += x - '0' + 1;
}
}
return sum;
}
test "example 1" {
const text =
\\2199943210
\\3987894921
\\9856789892
\\8767896789
\\9899965678
;
var fbs = std.io.fixedBufferStream(text);
const risk_level = try calculateRiskLevel(std.testing.allocator, fbs.reader());
try std.testing.expectEqual(@as(u64, 15), risk_level);
} | src/09.zig |
const std = @import("std");
const builtin = @import("builtin");
const os = @import("../os.zig");
const system = os.system;
const errno = system.getErrno;
const fd_t = system.fd_t;
const mode_t = system.mode_t;
const pid_t = system.pid_t;
const unexpectedErrno = os.unexpectedErrno;
const UnexpectedError = os.UnexpectedError;
const toPosixPath = os.toPosixPath;
const WaitPidResult = os.WaitPidResult;
pub usingnamespace posix_spawn;
pub const Error = error{
SystemResources,
InvalidFileDescriptor,
NameTooLong,
TooBig,
PermissionDenied,
InputOutput,
FileSystem,
FileNotFound,
InvalidExe,
NotDir,
FileBusy,
/// Returned when the child fails to execute either in the pre-exec() initialization step, or
/// when exec(3) is invoked.
ChildExecFailed,
} || UnexpectedError;
const posix_spawn = if (builtin.target.isDarwin()) struct {
pub const Attr = struct {
attr: system.posix_spawnattr_t,
pub fn init() Error!Attr {
var attr: system.posix_spawnattr_t = undefined;
switch (errno(system.posix_spawnattr_init(&attr))) {
.SUCCESS => return Attr{ .attr = attr },
.NOMEM => return error.SystemResources,
.INVAL => unreachable,
else => |err| return unexpectedErrno(err),
}
}
pub fn deinit(self: *Attr) void {
system.posix_spawnattr_destroy(&self.attr);
self.* = undefined;
}
pub fn get(self: Attr) Error!u16 {
var flags: c_short = undefined;
switch (errno(system.posix_spawnattr_getflags(&self.attr, &flags))) {
.SUCCESS => return @bitCast(u16, flags),
.INVAL => unreachable,
else => |err| return unexpectedErrno(err),
}
}
pub fn set(self: *Attr, flags: u16) Error!void {
switch (errno(system.posix_spawnattr_setflags(&self.attr, @bitCast(c_short, flags)))) {
.SUCCESS => return,
.INVAL => unreachable,
else => |err| return unexpectedErrno(err),
}
}
};
pub const Actions = struct {
actions: system.posix_spawn_file_actions_t,
pub fn init() Error!Actions {
var actions: system.posix_spawn_file_actions_t = undefined;
switch (errno(system.posix_spawn_file_actions_init(&actions))) {
.SUCCESS => return Actions{ .actions = actions },
.NOMEM => return error.SystemResources,
.INVAL => unreachable,
else => |err| return unexpectedErrno(err),
}
}
pub fn deinit(self: *Actions) void {
system.posix_spawn_file_actions_destroy(&self.actions);
self.* = undefined;
}
pub fn open(self: *Actions, fd: fd_t, path: []const u8, flags: u32, mode: mode_t) Error!void {
const posix_path = try toPosixPath(path);
return self.openZ(fd, &posix_path, flags, mode);
}
pub fn openZ(self: *Actions, fd: fd_t, path: [*:0]const u8, flags: u32, mode: mode_t) Error!void {
switch (errno(system.posix_spawn_file_actions_addopen(&self.actions, fd, path, @bitCast(c_int, flags), mode))) {
.SUCCESS => return,
.BADF => return error.InvalidFileDescriptor,
.NOMEM => return error.SystemResources,
.NAMETOOLONG => return error.NameTooLong,
.INVAL => unreachable, // the value of file actions is invalid
else => |err| return unexpectedErrno(err),
}
}
pub fn close(self: *Actions, fd: fd_t) Error!void {
switch (errno(system.posix_spawn_file_actions_addclose(&self.actions, fd))) {
.SUCCESS => return,
.BADF => return error.InvalidFileDescriptor,
.NOMEM => return error.SystemResources,
.INVAL => unreachable, // the value of file actions is invalid
.NAMETOOLONG => unreachable,
else => |err| return unexpectedErrno(err),
}
}
pub fn dup2(self: *Actions, fd: fd_t, newfd: fd_t) Error!void {
switch (errno(system.posix_spawn_file_actions_adddup2(&self.actions, fd, newfd))) {
.SUCCESS => return,
.BADF => return error.InvalidFileDescriptor,
.NOMEM => return error.SystemResources,
.INVAL => unreachable, // the value of file actions is invalid
.NAMETOOLONG => unreachable,
else => |err| return unexpectedErrno(err),
}
}
pub fn inherit(self: *Actions, fd: fd_t) Error!void {
switch (errno(system.posix_spawn_file_actions_addinherit_np(&self.actions, fd))) {
.SUCCESS => return,
.BADF => return error.InvalidFileDescriptor,
.NOMEM => return error.SystemResources,
.INVAL => unreachable, // the value of file actions is invalid
.NAMETOOLONG => unreachable,
else => |err| return unexpectedErrno(err),
}
}
pub fn chdir(self: *Actions, path: []const u8) Error!void {
const posix_path = try toPosixPath(path);
return self.chdirZ(&posix_path);
}
pub fn chdirZ(self: *Actions, path: [*:0]const u8) Error!void {
switch (errno(system.posix_spawn_file_actions_addchdir_np(&self.actions, path))) {
.SUCCESS => return,
.NOMEM => return error.SystemResources,
.NAMETOOLONG => return error.NameTooLong,
.BADF => unreachable,
.INVAL => unreachable, // the value of file actions is invalid
else => |err| return unexpectedErrno(err),
}
}
pub fn fchdir(self: *Actions, fd: fd_t) Error!void {
switch (errno(system.posix_spawn_file_actions_addfchdir_np(&self.actions, fd))) {
.SUCCESS => return,
.BADF => return error.InvalidFileDescriptor,
.NOMEM => return error.SystemResources,
.INVAL => unreachable, // the value of file actions is invalid
.NAMETOOLONG => unreachable,
else => |err| return unexpectedErrno(err),
}
}
};
pub fn spawn(
path: []const u8,
actions: ?Actions,
attr: ?Attr,
argv: [*:null]?[*:0]const u8,
envp: [*:null]?[*:0]const u8,
) Error!pid_t {
const posix_path = try toPosixPath(path);
return spawnZ(&posix_path, actions, attr, argv, envp);
}
pub fn spawnZ(
path: [*:0]const u8,
actions: ?Actions,
attr: ?Attr,
argv: [*:null]?[*:0]const u8,
envp: [*:null]?[*:0]const u8,
) Error!pid_t {
var pid: pid_t = undefined;
switch (errno(system.posix_spawn(
&pid,
path,
if (actions) |a| &a.actions else null,
if (attr) |a| &a.attr else null,
argv,
envp,
))) {
.SUCCESS => return pid,
.@"2BIG" => return error.TooBig,
.NOMEM => return error.SystemResources,
.BADF => return error.InvalidFileDescriptor,
.ACCES => return error.PermissionDenied,
.IO => return error.InputOutput,
.LOOP => return error.FileSystem,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOEXEC => return error.InvalidExe,
.NOTDIR => return error.NotDir,
.TXTBSY => return error.FileBusy,
.BADARCH => return error.InvalidExe,
.BADEXEC => return error.InvalidExe,
.FAULT => unreachable,
.INVAL => unreachable,
else => |err| return unexpectedErrno(err),
}
}
pub fn spawnp(
file: []const u8,
actions: ?Actions,
attr: ?Attr,
argv: [*:null]?[*:0]const u8,
envp: [*:null]?[*:0]const u8,
) Error!pid_t {
const posix_file = try toPosixPath(file);
return spawnpZ(&posix_file, actions, attr, argv, envp);
}
pub fn spawnpZ(
file: [*:0]const u8,
actions: ?Actions,
attr: ?Attr,
argv: [*:null]?[*:0]const u8,
envp: [*:null]?[*:0]const u8,
) Error!pid_t {
var pid: pid_t = undefined;
switch (errno(system.posix_spawnp(
&pid,
file,
if (actions) |a| &a.actions else null,
if (attr) |a| &a.attr else null,
argv,
envp,
))) {
.SUCCESS => return pid,
.@"2BIG" => return error.TooBig,
.NOMEM => return error.SystemResources,
.BADF => return error.InvalidFileDescriptor,
.ACCES => return error.PermissionDenied,
.IO => return error.InputOutput,
.LOOP => return error.FileSystem,
.NAMETOOLONG => return error.NameTooLong,
.NOENT => return error.FileNotFound,
.NOEXEC => return error.InvalidExe,
.NOTDIR => return error.NotDir,
.TXTBSY => return error.FileBusy,
.BADARCH => return error.InvalidExe,
.BADEXEC => return error.InvalidExe,
.FAULT => unreachable,
.INVAL => unreachable,
else => |err| return unexpectedErrno(err),
}
}
/// Use this version of the `waitpid` wrapper if you spawned your child process using `posix_spawn`
/// or `posix_spawnp` syscalls.
/// See also `std.os.waitpid` for an alternative if your child process was spawned via `fork` and
/// `execve` method.
pub fn waitpid(pid: pid_t, flags: u32) Error!WaitPidResult {
const Status = if (builtin.link_libc) c_int else u32;
var status: Status = undefined;
while (true) {
const rc = system.waitpid(pid, &status, if (builtin.link_libc) @intCast(c_int, flags) else flags);
switch (errno(rc)) {
.SUCCESS => return WaitPidResult{
.pid = @intCast(pid_t, rc),
.status = @bitCast(u32, status),
},
.INTR => continue,
.CHILD => return error.ChildExecFailed,
.INVAL => unreachable, // Invalid flags.
else => unreachable,
}
}
}
} else struct {}; | lib/std/os/posix_spawn.zig |
const std = @import("std");
const print = std.debug.print;
const data = @embedFile("../inputs/day11.txt");
pub fn main() anyerror!void {
const grid = parse(data[0..]).?;
print("Part 1: {d}\n", .{part1(grid)});
print("Part 2: {d}\n", .{part2(grid)});
}
const Size = 10;
const Octopus = struct {
energy: u4,
flash: bool,
};
const Grid = [Size][Size]Octopus;
fn parse(input: []const u8) ?Grid {
var lines = std.mem.tokenize(u8, input, "\n");
var out: Grid = undefined;
var row: usize = 0;
while (lines.next()) |line| {
if (line.len != Size) return null;
for (line) |c, col| {
out[row][col].energy = @intCast(u4, c - '0');
out[row][col].flash = false;
}
row += 1;
}
if (row != Size) return null;
return out;
}
fn propagate(x: usize, y: usize, grid: *Grid) void {
const from_y: usize = if (y == 0) y else y - 1;
const to_y: usize = if (y == grid.len - 1) y else y + 1;
const from_x: usize = if (x == 0) x else x - 1;
const to_x: usize = if (x == grid[0].len - 1) x else x + 1;
var i = from_y;
while (i <= to_y) : (i += 1) {
var j = from_x;
while (j <= to_x) : (j += 1) {
if (grid[i][j].energy <= 9) {
grid[i][j].energy += 1;
if (grid[i][j].energy > 9) {
grid[i][j].flash = true;
propagate(j, i, grid);
}
}
}
}
}
fn run_step(grid: *Grid) usize {
for (grid) |*row| {
for (row.*) |*c| {
c.energy += 1;
}
}
for (grid) |row, y| {
for (row) |c, x| {
if (c.energy > 9 and c.flash == false) propagate(x, y, grid);
}
}
var flashes: usize = 0;
for (grid) |*row| {
for (row.*) |*c| {
if (c.energy > 9) {
flashes += 1;
c.energy = 0;
c.flash = false;
}
}
}
return flashes;
}
fn dump(grid: Grid) void {
for (grid) |row| {
for (row) |c| {
if (c.energy == 0) {
print("\x1B[31m0\x1B[0m", .{});
} else {
print("{d}", .{c.energy});
}
}
print("\n", .{});
}
}
fn part1(const_grid: Grid) usize {
var grid = const_grid;
var flashes: usize = 0;
var step: usize = 0;
while (step < 100) : (step += 1) {
flashes += run_step(&grid);
}
return flashes;
}
fn all_in_sync(grid: Grid) bool {
for (grid) |row| {
for (row) |c| {
if (c.energy != 0) return false;
}
}
return true;
}
fn part2(const_grid: Grid) usize {
var grid = const_grid;
var step: usize = 0;
while (!all_in_sync(grid)) : (step += 1) {
_ = run_step(&grid);
}
return step;
}
test "dumbo octopuses" {
const input =
\\5483143223
\\2745854711
\\5264556173
\\6141336146
\\6357385478
\\4167524645
\\2176841721
\\6882881134
\\4846848554
\\5283751526
;
const grid = parse(input[0..]).?;
try std.testing.expectEqual(@as(usize, 1656), part1(grid));
try std.testing.expectEqual(@as(usize, 195), part2(grid));
} | src/day11.zig |
const x86_64 = @import("../../../index.zig");
const bitjuggle = @import("bitjuggle");
const std = @import("std");
pub const OffsetPageTable = @import("mapped_page_table.zig").OffsetPageTable;
pub const MappedPageTable = @import("mapped_page_table.zig").MappedPageTable;
pub const RecursivePageTable = @import("recursive_page_table.zig").RecursivePageTable;
const paging = x86_64.structures.paging;
pub const Mapper = struct {
// This is the most annoying code ive ever written...
// All just to have something that is trivial in most languages; an interface
z_impl_mapToWithTableFlags1GiB: fn (
mapper: *Mapper,
page: paging.Page1GiB,
frame: paging.PhysFrame1GiB,
flags: paging.PageTableFlags,
parent_table_flags: paging.PageTableFlags,
frame_allocator: *paging.FrameAllocator,
) MapToError!MapperFlush1GiB,
z_impl_unmap1GiB: fn (
mapper: *Mapper,
page: paging.Page1GiB,
) UnmapError!UnmapResult1GiB,
z_impl_updateFlags1GiB: fn (
mapper: *Mapper,
page: paging.Page1GiB,
flags: paging.PageTableFlags,
) FlagUpdateError!MapperFlush1GiB,
z_impl_setFlagsP4Entry1GiB: fn (
mapper: *Mapper,
page: paging.Page1GiB,
flags: paging.PageTableFlags,
) FlagUpdateError!MapperFlushAll,
z_impl_translatePage1GiB: fn (
mapper: *Mapper,
page: paging.Page1GiB,
) TranslateError!paging.PhysFrame1GiB,
z_impl_mapToWithTableFlags2MiB: fn (
mapper: *Mapper,
page: paging.Page2MiB,
frame: paging.PhysFrame2MiB,
flags: paging.PageTableFlags,
parent_table_flags: paging.PageTableFlags,
frame_allocator: *paging.FrameAllocator,
) MapToError!MapperFlush2MiB,
z_impl_unmap2MiB: fn (
mapper: *Mapper,
page: paging.Page2MiB,
) UnmapError!UnmapResult2MiB,
z_impl_updateFlags2MiB: fn (
mapper: *Mapper,
page: paging.Page2MiB,
flags: paging.PageTableFlags,
) FlagUpdateError!MapperFlush2MiB,
z_impl_setFlagsP4Entry2MiB: fn (
mapper: *Mapper,
page: paging.Page2MiB,
flags: paging.PageTableFlags,
) FlagUpdateError!MapperFlushAll,
z_impl_setFlagsP3Entry2MiB: fn (
mapper: *Mapper,
page: paging.Page2MiB,
flags: paging.PageTableFlags,
) FlagUpdateError!MapperFlushAll,
z_impl_translatePage2MiB: fn (
mapper: *Mapper,
page: paging.Page2MiB,
) TranslateError!paging.PhysFrame2MiB,
z_impl_mapToWithTableFlags: fn (
mapper: *Mapper,
page: paging.Page,
frame: paging.PhysFrame,
flags: paging.PageTableFlags,
parent_table_flags: paging.PageTableFlags,
frame_allocator: *paging.FrameAllocator,
) MapToError!MapperFlush,
z_impl_unmap: fn (
mapper: *Mapper,
page: paging.Page,
) UnmapError!UnmapResult,
z_impl_updateFlags: fn (
mapper: *Mapper,
page: paging.Page,
flags: paging.PageTableFlags,
) FlagUpdateError!MapperFlush,
z_impl_setFlagsP4Entry: fn (
mapper: *Mapper,
page: paging.Page,
flags: paging.PageTableFlags,
) FlagUpdateError!MapperFlushAll,
z_impl_setFlagsP3Entry: fn (
mapper: *Mapper,
page: paging.Page,
flags: paging.PageTableFlags,
) FlagUpdateError!MapperFlushAll,
z_impl_setFlagsP2Entry: fn (
mapper: *Mapper,
page: paging.Page,
flags: paging.PageTableFlags,
) FlagUpdateError!MapperFlushAll,
z_impl_translatePage: fn (
mapper: *Mapper,
page: paging.Page,
) TranslateError!paging.PhysFrame,
z_impl_translate: fn (
mapper: *Mapper,
addr: x86_64.VirtAddr,
) TranslateError!TranslateResult,
/// Creates a new mapping in the page table.
///
/// This function might need additional physical frames to create new page tables. These
/// frames are allocated from the `allocator` argument. At most three frames are required.
///
/// Parent page table entries are automatically updated with `PRESENT | WRITABLE | USER_ACCESSIBLE`
/// if present in the `PageTableFlags`. Depending on the used mapper implementation
/// the `PRESENT` and `WRITABLE` flags might be set for parent tables,
/// even if they are not set in `PageTableFlags`.
///
/// The `mapToWithTableFlags` method gives explicit control over the parent page table flags.
pub inline fn mapTo(
mapper: *Mapper,
page: paging.Page,
frame: paging.PhysFrame,
flags: paging.PageTableFlags,
frame_allocator: *paging.FrameAllocator,
) MapToError!MapperFlush {
return mapper.z_impl_mapToWithTableFlags(mapper, page, frame, flags, flags, frame_allocator);
}
/// Creates a new mapping in the page table.
///
/// This function might need additional physical frames to create new page tables. These
/// frames are allocated from the `allocator` argument. At most three frames are required.
///
/// Parent page table entries are automatically updated with `PRESENT | WRITABLE | USER_ACCESSIBLE`
/// if present in the `PageTableFlags`. Depending on the used mapper implementation
/// the `PRESENT` and `WRITABLE` flags might be set for parent tables,
/// even if they are not set in `PageTableFlags`.
///
/// The `mapToWithTableFlags` method gives explicit control over the parent page table flags.
pub inline fn mapTo2MiB(
mapper: *Mapper,
page: paging.Page2MiB,
frame: paging.PhysFrame2MiB,
flags: paging.PageTableFlags,
frame_allocator: *paging.FrameAllocator,
) MapToError!MapperFlush2MiB {
return mapper.z_impl_mapToWithTableFlags2MiB(mapper, page, frame, flags, flags, frame_allocator);
}
/// Creates a new mapping in the page table.
///
/// This function might need additional physical frames to create new page tables. These
/// frames are allocated from the `allocator` argument. At most three frames are required.
///
/// Parent page table entries are automatically updated with `PRESENT | WRITABLE | USER_ACCESSIBLE`
/// if present in the `PageTableFlags`. Depending on the used mapper implementation
/// the `PRESENT` and `WRITABLE` flags might be set for parent tables,
/// even if they are not set in `PageTableFlags`.
///
/// The `mapToWithTableFlags` method gives explicit control over the parent page table flags.
pub inline fn mapTo1GiB(
mapper: *Mapper,
page: paging.Page1GiB,
frame: paging.PhysFrame1GiB,
flags: paging.PageTableFlags,
frame_allocator: *paging.FrameAllocator,
) MapToError!MapperFlush1GiB {
return mapper.z_impl_mapToWithTableFlags1GiB(mapper, page, frame, flags, flags, frame_allocator);
}
/// Maps the given frame to the virtual page with the same address.
pub fn identityMap(
mapper: *Mapper,
frame: paging.PhysFrame,
flags: paging.PageTableFlags,
frame_allocator: *paging.FrameAllocator,
) MapToError!MapperFlush {
return mapper.mapTo(
paging.Page.containingAddress(x86_64.VirtAddr.initPanic(frame.start_address.value)),
frame,
flags,
frame_allocator,
);
}
/// Maps the given frame to the virtual page with the same address.
pub fn identityMap2MiB(
mapper: *Mapper,
frame: paging.PhysFrame2MiB,
flags: paging.PageTableFlags,
frame_allocator: *paging.FrameAllocator,
) MapToError!MapperFlush2MiB {
return mapper.mapTo2MiB(
paging.Page2MiB.containingAddress(x86_64.VirtAddr.initPanic(frame.start_address.value)),
frame,
flags,
frame_allocator,
);
}
/// Maps the given frame to the virtual page with the same address.
pub fn identityMap1GiB(
mapper: *Mapper,
frame: paging.PhysFrame1GiB,
flags: paging.PageTableFlags,
frame_allocator: *paging.FrameAllocator,
) MapToError!MapperFlush1GiB {
return mapper.mapTo1GiB(
paging.Page1GiB.containingAddress(x86_64.VirtAddr.initPanic(frame.start_address.value)),
frame,
flags,
frame_allocator,
);
}
/// Translates the given virtual address to the physical address that it maps to.
///
/// Returns `None` if there is no valid mapping for the given address.
///
/// This is a convenience method. For more information about a mapping see the
/// `translate` function.
pub fn translateAddr(mapper: *Mapper, addr: x86_64.VirtAddr) ?x86_64.PhysAddr {
return switch (mapper.translate(addr) catch return null) {
.Frame4KiB => |res| x86_64.PhysAddr.initPanic(res.frame.start_address.value + res.offset),
.Frame2MiB => |res| x86_64.PhysAddr.initPanic(res.frame.start_address.value + res.offset),
.Frame1GiB => |res| x86_64.PhysAddr.initPanic(res.frame.start_address.value + res.offset),
};
}
/// Return the frame that the given virtual address is mapped to and the offset within that
/// frame.
///
/// If the given address has a valid mapping, the mapped frame and the offset within that
/// frame is returned. Otherwise an error value is returned.
pub inline fn translate(
mapper: *Mapper,
addr: x86_64.VirtAddr,
) TranslateError!TranslateResult {
return mapper.z_impl_translate(mapper, addr);
}
/// Return the frame that the specified page is mapped to.
pub inline fn translatePage(
mapper: *Mapper,
page: paging.Page,
) TranslateError!paging.PhysFrame {
return mapper.z_impl_translatePage(mapper, page);
}
/// Return the frame that the specified page is mapped to.
pub inline fn translatePage2MiB(
mapper: *Mapper,
page: paging.Page2MiB,
) TranslateError!paging.PhysFrame2MiB {
return mapper.z_impl_translatePage2MiB(mapper, page);
}
/// Return the frame that the specified page is mapped to.
pub inline fn translatePage1GiB(
mapper: *Mapper,
page: paging.Page1GiB,
) TranslateError!paging.PhysFrame1GiB {
return mapper.z_impl_translatePage1GiB(mapper, page);
}
/// Set the flags of an existing page table level 2 entry
pub inline fn setFlagsP2Entry(
mapper: *Mapper,
page: paging.Page,
flags: paging.PageTableFlags,
) FlagUpdateError!MapperFlushAll {
return mapper.z_impl_setFlagsP2Entry(mapper, page, flags);
}
/// Set the flags of an existing page table level 3 entry
pub inline fn setFlagsP3Entry(
mapper: *Mapper,
page: paging.Page,
flags: paging.PageTableFlags,
) FlagUpdateError!MapperFlushAll {
return mapper.z_impl_setFlagsP3Entry(mapper, page, flags);
}
/// Set the flags of an existing page table level 3 entry
pub inline fn setFlagsP3Entry2MiB(
mapper: *Mapper,
page: paging.Page2MiB,
flags: paging.PageTableFlags,
) FlagUpdateError!MapperFlushAll {
return mapper.z_impl_setFlagsP3Entry2MiB(mapper, page, flags);
}
/// Set the flags of an existing page table level 4 entry
pub inline fn setFlagsP4Entry(
mapper: *Mapper,
page: paging.Page,
flags: paging.PageTableFlags,
) FlagUpdateError!MapperFlushAll {
return mapper.z_impl_setFlagsP4Entry(mapper, page, flags);
}
/// Set the flags of an existing page table level 4 entry
pub inline fn setFlagsP4Entry2MiB(
mapper: *Mapper,
page: paging.Page2MiB,
flags: paging.PageTableFlags,
) FlagUpdateError!MapperFlushAll {
return mapper.z_impl_setFlagsP4Entry2MiB(mapper, page, flags);
}
/// Set the flags of an existing page table level 4 entry
pub inline fn setFlagsP4Entry1GiB(
mapper: *Mapper,
page: paging.Page1GiB,
flags: paging.PageTableFlags,
) FlagUpdateError!MapperFlushAll {
return mapper.z_impl_setFlagsP4Entry1GiB(mapper, page, flags);
}
/// Updates the flags of an existing mapping.
pub inline fn updateFlags(
mapper: *Mapper,
page: paging.Page,
flags: paging.PageTableFlags,
) FlagUpdateError!MapperFlush {
return mapper.z_impl_updateFlags(mapper, page, flags);
}
/// Updates the flags of an existing mapping.
pub inline fn updateFlags2MiB(
mapper: *Mapper,
page: paging.Page2MiB,
flags: paging.PageTableFlags,
) FlagUpdateError!MapperFlush2MiB {
return mapper.z_impl_updateFlags2MiB(mapper, page, flags);
}
/// Updates the flags of an existing mapping.
pub inline fn updateFlags1GiB(
mapper: *Mapper,
page: paging.Page1GiB,
flags: paging.PageTableFlags,
) FlagUpdateError!MapperFlush1GiB {
return mapper.z_impl_updateFlags1GiB(mapper, page, flags);
}
/// Removes a mapping from the page table and returns the frame that used to be mapped.
///
/// Note that no page tables or pages are deallocated.
pub inline fn unmap(
mapper: *Mapper,
page: paging.Page,
) UnmapError!UnmapResult {
return mapper.z_impl_unmap(mapper, page);
}
/// Removes a mapping from the page table and returns the frame that used to be mapped.
///
/// Note that no page tables or pages are deallocated.
pub inline fn unmap2MiB(
mapper: *Mapper,
page: paging.Page2MiB,
) UnmapError!UnmapResult2MiB {
return mapper.z_impl_unmap2MiB(mapper, page);
}
/// Removes a mapping from the page table and returns the frame that used to be mapped.
///
/// Note that no page tables or pages are deallocated.
pub inline fn unmap1GiB(
mapper: *Mapper,
page: paging.Page1GiB,
) UnmapError!UnmapResult1GiB {
return mapper.z_impl_unmap1GiB(mapper, page);
}
/// Creates a new mapping in the page table.
///
/// This function might need additional physical frames to create new page tables. These
/// frames are allocated from the `allocator` argument. At most three frames are required.
///
/// The flags of the parent table(s) can be explicitly specified. Those flags are used for
/// newly created table entries, and for existing entries the flags are added.
///
/// Depending on the used mapper implementation, the `PRESENT` and `WRITABLE` flags might
/// be set for parent tables, even if they are not specified in `parent_table_flags`.
pub inline fn mapToWithTableFlags(
mapper: *Mapper,
page: paging.Page,
frame: paging.PhysFrame,
flags: paging.PageTableFlags,
parent_table_flags: paging.PageTableFlags,
frame_allocator: *paging.FrameAllocator,
) MapToError!MapperFlush {
return mapper.z_impl_mapToWithTableFlags(mapper, page, frame, flags, parent_table_flags, frame_allocator);
}
/// Creates a new mapping in the page table.
///
/// This function might need additional physical frames to create new page tables. These
/// frames are allocated from the `allocator` argument. At most three frames are required.
///
/// The flags of the parent table(s) can be explicitly specified. Those flags are used for
/// newly created table entries, and for existing entries the flags are added.
///
/// Depending on the used mapper implementation, the `PRESENT` and `WRITABLE` flags might
/// be set for parent tables, even if they are not specified in `parent_table_flags`.
pub inline fn mapToWithTableFlags2MiB(
mapper: *Mapper,
page: paging.Page2MiB,
frame: paging.PhysFrame2MiB,
flags: paging.PageTableFlags,
parent_table_flags: paging.PageTableFlags,
frame_allocator: *paging.FrameAllocator,
) MapToError!MapperFlush2MiB {
return mapper.z_impl_mapToWithTableFlags2MiB(mapper, page, frame, flags, parent_table_flags, frame_allocator);
}
/// Creates a new mapping in the page table.
///
/// This function might need additional physical frames to create new page tables. These
/// frames are allocated from the `allocator` argument. At most three frames are required.
///
/// The flags of the parent table(s) can be explicitly specified. Those flags are used for
/// newly created table entries, and for existing entries the flags are added.
///
/// Depending on the used mapper implementation, the `PRESENT` and `WRITABLE` flags might
/// be set for parent tables, even if they are not specified in `parent_table_flags`.
pub inline fn mapToWithTableFlags1GiB(
mapper: *Mapper,
page: paging.Page1GiB,
frame: paging.PhysFrame1GiB,
flags: paging.PageTableFlags,
parent_table_flags: paging.PageTableFlags,
frame_allocator: *paging.FrameAllocator,
) MapToError!MapperFlush1GiB {
return mapper.z_impl_mapToWithTableFlags1GiB(mapper, page, frame, flags, parent_table_flags, frame_allocator);
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// Unmap result. Page size 4 KiB
pub const UnmapResult = struct {
frame: paging.PhysFrame,
flush: MapperFlush,
comptime {
std.testing.refAllDecls(@This());
}
};
/// Unmap result. Page size 2 MiB
pub const UnmapResult2MiB = struct {
frame: paging.PhysFrame2MiB,
flush: MapperFlush2MiB,
comptime {
std.testing.refAllDecls(@This());
}
};
/// Unmap result. Page size 1 GiB
pub const UnmapResult1GiB = struct {
frame: paging.PhysFrame1GiB,
flush: MapperFlush1GiB,
comptime {
std.testing.refAllDecls(@This());
}
};
pub const TranslateResultType = enum {
Frame4KiB,
Frame2MiB,
Frame1GiB,
};
pub const TranslateResult = union(TranslateResultType) {
Frame4KiB: TranslateResultContents,
Frame2MiB: TranslateResult2MiBContents,
Frame1GiB: TranslateResult1GiBContents,
};
pub const TranslateResultContents = struct {
/// The mapped frame.
frame: paging.PhysFrame,
/// The offset within the mapped frame.
offset: u64,
/// The flags for the frame.
flags: paging.PageTableFlags,
comptime {
std.testing.refAllDecls(@This());
}
};
pub const TranslateResult2MiBContents = struct {
/// The mapped frame.
frame: paging.PhysFrame2MiB,
/// The offset within the mapped frame.
offset: u64,
/// The flags for the frame.
flags: paging.PageTableFlags,
comptime {
std.testing.refAllDecls(@This());
}
};
pub const TranslateResult1GiBContents = struct {
/// The mapped frame.
frame: paging.PhysFrame1GiB,
/// The offset within the mapped frame.
offset: u64,
/// The flags for the frame.
flags: paging.PageTableFlags,
comptime {
std.testing.refAllDecls(@This());
}
};
/// An error indicating that a `translate` call failed.
pub const TranslateError = error{
/// The given page is not mapped to a physical frame.
NotMapped,
/// The page table entry for the given page points to an invalid physical address.
InvalidFrameAddress,
};
/// This type represents a change of a page table requiring a complete TLB flush
///
/// The old mapping might be still cached in the translation lookaside buffer (TLB), so it needs
/// to be flushed from the TLB before it's accessed. This type is returned from a function that
/// made the change to ensure that the TLB flush is not forgotten.
pub const MapperFlushAll = struct {
/// Flush all pages from the TLB to ensure that the newest mapping is used.
pub fn flushAll(self: MapperFlushAll) void {
_ = self;
x86_64.instructions.tlb.flushAll();
}
};
/// This type represents a page whose mapping has changed in the page table. Page size 4 KiB
///
/// The old mapping might be still cached in the translation lookaside buffer (TLB), so it needs
/// to be flushed from the TLB before it's accessed. This type is returned from function that
/// change the mapping of a page to ensure that the TLB flush is not forgotten.
pub const MapperFlush = struct {
page: paging.Page,
/// Create a new flush promise
pub fn init(page: paging.Page) MapperFlush {
return .{ .page = page };
}
/// Flush the page from the TLB to ensure that the newest mapping is used.
pub fn flush(self: MapperFlush) void {
x86_64.instructions.tlb.flush(self.page.start_address);
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// This type represents a page whose mapping has changed in the page table. Page size 2 MiB
///
/// The old mapping might be still cached in the translation lookaside buffer (TLB), so it needs
/// to be flushed from the TLB before it's accessed. This type is returned from function that
/// change the mapping of a page to ensure that the TLB flush is not forgotten.
pub const MapperFlush2MiB = struct {
page: paging.Page2MiB,
/// Create a new flush promise
pub fn init(page: paging.Page2MiB) MapperFlush2MiB {
return .{ .page = page };
}
/// Flush the page from the TLB to ensure that the newest mapping is used.
pub fn flush(self: MapperFlush2MiB) void {
x86_64.instructions.tlb.flush(self.page.start_address);
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// This type represents a page whose mapping has changed in the page table. Page size 1 GiB
///
/// The old mapping might be still cached in the translation lookaside buffer (TLB), so it needs
/// to be flushed from the TLB before it's accessed. This type is returned from function that
/// change the mapping of a page to ensure that the TLB flush is not forgotten.
pub const MapperFlush1GiB = struct {
page: paging.Page1GiB,
/// Create a new flush promise
pub fn init(page: paging.Page1GiB) MapperFlush1GiB {
return .{ .page = page };
}
/// Flush the page from the TLB to ensure that the newest mapping is used.
pub fn flush(self: MapperFlush1GiB) void {
x86_64.instructions.tlb.flush(self.page.start_address);
}
comptime {
std.testing.refAllDecls(@This());
}
};
pub const MapToError = error{
/// An additional frame was needed for the mapping process, but the frame allocator
/// returned `None`.
FrameAllocationFailed,
/// An upper level page table entry has the `huge_page` flag set, which means that the
/// given page is part of an already mapped huge page.
ParentEntryHugePage,
/// The given page is already mapped to a physical frame.
PageAlreadyMapped,
};
/// An error indicating that an `unmap` call failed.
pub const UnmapError = error{
/// An upper level page table entry has the `huge_page` flag set, which means that the
/// given page is part of a huge page and can't be freed individually.
ParentEntryHugePage,
/// The given page is not mapped to a physical frame.
PageNotMapped,
/// The page table entry for the given page points to an invalid physical address.
InvalidFrameAddress,
};
/// An error indicating that an `update_flags` call failed.
pub const FlagUpdateError = error{
/// The given page is not mapped to a physical frame.
PageNotMapped,
/// An upper level page table entry has the `huge_page` flag set, which means that the
/// given page is part of a huge page and can't be freed individually.
ParentEntryHugePage,
};
/// An error indicating that an `translate` call failed.
pub const TranslatePageError = error{
/// The given page is not mapped to a physical frame.
PageNotMapped,
/// An upper level page table entry has the `huge_page` flag set, which means that the
/// given page is part of a huge page and can't be freed individually.
ParentEntryHugePage,
/// The page table entry for the given page points to an invalid physical address.
InvalidFrameAddress,
};
comptime {
std.testing.refAllDecls(@This());
} | src/structures/paging/mapping/mapping.zig |
const std = @import("std");
const math = std.math;
const assert = std.debug.assert;
const warn = std.debug.warn;
const ae = @import("../modules/zig-approxeql/approxeql.zig");
const DBG = false;
pub const Mat4x4 = struct {
const Self = @This();
data: [4][4]f32,
/// matrix multiplication
pub fn mult(m: *const Mat4x4, other: *const Mat4x4) Mat4x4 {
return Mat4x4{ .data = [][4]f32{
[]f32{
m.data[0][0] * other.data[0][0] + m.data[0][1] * other.data[1][0] + m.data[0][2] * other.data[2][0] + m.data[0][3] * other.data[3][0],
m.data[0][0] * other.data[0][1] + m.data[0][1] * other.data[1][1] + m.data[0][2] * other.data[2][1] + m.data[0][3] * other.data[3][1],
m.data[0][0] * other.data[0][2] + m.data[0][1] * other.data[1][2] + m.data[0][2] * other.data[2][2] + m.data[0][3] * other.data[3][2],
m.data[0][0] * other.data[0][3] + m.data[0][1] * other.data[1][3] + m.data[0][2] * other.data[2][3] + m.data[0][3] * other.data[3][3],
},
[]f32{
m.data[1][0] * other.data[0][0] + m.data[1][1] * other.data[1][0] + m.data[1][2] * other.data[2][0] + m.data[1][3] * other.data[3][0],
m.data[1][0] * other.data[0][1] + m.data[1][1] * other.data[1][1] + m.data[1][2] * other.data[2][1] + m.data[1][3] * other.data[3][1],
m.data[1][0] * other.data[0][2] + m.data[1][1] * other.data[1][2] + m.data[1][2] * other.data[2][2] + m.data[1][3] * other.data[3][2],
m.data[1][0] * other.data[0][3] + m.data[1][1] * other.data[1][3] + m.data[1][2] * other.data[2][3] + m.data[1][3] * other.data[3][3],
},
[]f32{
m.data[2][0] * other.data[0][0] + m.data[2][1] * other.data[1][0] + m.data[2][2] * other.data[2][0] + m.data[2][3] * other.data[3][0],
m.data[2][0] * other.data[0][1] + m.data[2][1] * other.data[1][1] + m.data[2][2] * other.data[2][1] + m.data[2][3] * other.data[3][1],
m.data[2][0] * other.data[0][2] + m.data[2][1] * other.data[1][2] + m.data[2][2] * other.data[2][2] + m.data[2][3] * other.data[3][2],
m.data[2][0] * other.data[0][3] + m.data[2][1] * other.data[1][3] + m.data[2][2] * other.data[2][3] + m.data[2][3] * other.data[3][3],
},
[]f32{
m.data[3][0] * other.data[0][0] + m.data[3][1] * other.data[1][0] + m.data[3][2] * other.data[2][0] + m.data[3][3] * other.data[3][0],
m.data[3][0] * other.data[0][1] + m.data[3][1] * other.data[1][1] + m.data[3][2] * other.data[2][1] + m.data[3][3] * other.data[3][1],
m.data[3][0] * other.data[0][2] + m.data[3][1] * other.data[1][2] + m.data[3][2] * other.data[2][2] + m.data[3][3] * other.data[3][2],
m.data[3][0] * other.data[0][3] + m.data[3][1] * other.data[1][3] + m.data[3][2] * other.data[2][3] + m.data[3][3] * other.data[3][3],
},
} };
}
pub fn assert_matrix_eq(pSelf: *const Mat4x4, pOther: *const Mat4x4) void {
const digits = 7;
assert(ae.approxEql(pSelf.data[0][0], pOther.data[0][0], digits));
assert(ae.approxEql(pSelf.data[0][1], pOther.data[0][1], digits));
assert(ae.approxEql(pSelf.data[0][2], pOther.data[0][2], digits));
assert(ae.approxEql(pSelf.data[0][3], pOther.data[0][3], digits));
assert(ae.approxEql(pSelf.data[1][0], pOther.data[1][0], digits));
assert(ae.approxEql(pSelf.data[1][1], pOther.data[1][1], digits));
assert(ae.approxEql(pSelf.data[1][2], pOther.data[1][2], digits));
assert(ae.approxEql(pSelf.data[1][3], pOther.data[1][3], digits));
assert(ae.approxEql(pSelf.data[2][0], pOther.data[2][0], digits));
assert(ae.approxEql(pSelf.data[2][1], pOther.data[2][1], digits));
assert(ae.approxEql(pSelf.data[2][2], pOther.data[2][2], digits));
assert(ae.approxEql(pSelf.data[2][3], pOther.data[2][3], digits));
assert(ae.approxEql(pSelf.data[3][0], pOther.data[3][0], digits));
assert(ae.approxEql(pSelf.data[3][1], pOther.data[3][1], digits));
assert(ae.approxEql(pSelf.data[3][2], pOther.data[3][2], digits));
assert(ae.approxEql(pSelf.data[3][3], pOther.data[3][3], digits));
}
/// Custom format routine for Mat4x4
pub fn format(
self: *const Self,
comptime fmt: []const u8,
context: var,
comptime FmtError: type,
output: fn (@typeOf(context), []const u8) FmtError!void,
) FmtError!void {
for (self.data) |row, i| {
try std.fmt.format(context, FmtError, output, " []f32.{{ ");
for (row) |col, j| {
try std.fmt.format(context, FmtError, output, "{.7}{} ", col, if (j < (row.len - 1)) "," else "");
}
try std.fmt.format(context, FmtError, output, "}},\n");
}
}
};
pub const mat4x4_identity = Mat4x4{ .data = [][4]f32{
[]f32{ 1.0, 0.0, 0.0, 0.0 },
[]f32{ 0.0, 1.0, 0.0, 0.0 },
[]f32{ 0.0, 0.0, 1.0, 0.0 },
[]f32{ 0.0, 0.0, 0.0, 1.0 },
} };
pub const Vec2 = struct {
const Self = @This();
data: [2]f32,
pub fn init(xp: f32, yp: f32) Vec2 {
return vec2(xp, yp);
}
pub fn x(v: *const Vec2) f32 {
return v.data[0];
}
pub fn y(v: *const Vec2) f32 {
return v.data[1];
}
pub fn setX(v: *Vec2, xp: f32) void {
v.data[0] = xp;
}
pub fn setY(v: *Vec2, yp: f32) void {
v.data[1] = yp;
}
pub fn normalize(v: *const Vec2) Vec2 {
return v.scale(1.0 / math.sqrt(v.dot(v)));
}
pub fn scale(v: *const Vec2, scalar: f32) Vec2 {
return Vec2{ .data = []f32{
v.data[0] * scalar,
v.data[1] * scalar,
} };
}
pub fn dot(v: *const Vec2, other: *const Vec2) f32 {
return v.data[0] * other.data[0] + v.data[1] * other.data[1];
}
pub fn length(v: *const Vec2) f32 {
return math.sqrt(v.dot(v));
}
pub fn add(v: *const Vec2, other: *const Vec2) Vec2 {
return Vec2.init(v.x() + other.x(), v.y() + other.y());
}
/// Custom format routine for Vec2
pub fn format(
self: *const Self,
comptime fmt: []const u8,
context: var,
comptime FmtError: type,
output: fn (@typeOf(context), []const u8) FmtError!void,
) FmtError!void {
try std.fmt.format(context, FmtError, output, "x={.3} y={.3}", self.x(), self.y());
}
};
pub fn vec2(x: f32, y: f32) Vec2 {
return Vec2{ .data = []f32{
x,
y,
} };
}
test "math3d.vec2" {
var v1 = vec2(1, 2);
var v2 = Vec2.init(0.1, 0.2);
assert(v1.x() == 1.0);
assert(v1.y() == 2.0);
assert(v2.x() == 0.1);
assert(v2.y() == 0.2);
v1.setX(v2.x());
v1.setY(v2.y());
assert(v1.x() == v2.x());
assert(v1.y() == v2.y());
// TODO: More tests
}
pub const Vec3 = struct {
const Self = @This();
data: [3]f32,
pub fn init(xp: f32, yp: f32, zp: f32) Vec3 {
return vec3(xp, yp, zp);
}
pub fn x(v: *const Vec3) f32 {
return v.data[0];
}
pub fn y(v: *const Vec3) f32 {
return v.data[1];
}
pub fn z(v: *const Vec3) f32 {
return v.data[2];
}
pub fn setX(v: *Vec3, xp: f32) void {
v.data[0] = xp;
}
pub fn setY(v: *Vec3, yp: f32) void {
v.data[1] = yp;
}
pub fn setZ(v: *Vec3, zp: f32) void {
v.data[2] = zp;
}
pub fn unitX() Vec3 {
return Vec3.init(1, 0, 0);
}
pub fn unitY() Vec3 {
return Vec3.init(0, 1, 0);
}
pub fn unitZ() Vec3 {
return Vec3.init(0, 0, 1);
}
pub fn zero() Vec3 {
return Vec3.init(0, 0, 0);
}
pub fn normalize(v: *const Vec3) Vec3 {
return v.scale(1.0 / math.sqrt(v.dot(v)));
}
pub fn scale(v: *const Vec3, scalar: f32) Vec3 {
return Vec3.init(v.x() * scalar, v.y() * scalar, v.z() * scalar);
}
pub fn dot(v: *const Vec3, other: *const Vec3) f32 {
return (v.x() * other.x()) + (v.y() * other.y()) + (v.z() * other.z());
}
pub fn length(v: *const Vec3) f32 {
return math.sqrt(v.dot(v));
}
/// returns the cross product
pub fn cross(v: *const Vec3, other: *const Vec3) Vec3 {
var rx = (v.y() * other.z()) - (other.y() * v.z());
var ry = (v.z() * other.x()) - (other.z() * v.z());
var rz = (v.x() * other.y()) - (other.x() * v.y());
return Vec3.init(rx, ry, rz);
}
pub fn eql(v: *const Vec3, other: *const Vec3) bool {
return v.x() == other.x() and v.y() == other.y() and v.z() == other.z();
}
pub fn approxEql(v: *const Vec3, other: *const Vec3, digits: usize) bool {
return ae.approxEql(v.x(), other.x(), digits) and ae.approxEql(v.y(), other.y(), digits) and ae.approxEql(v.z(), other.z(), digits);
}
pub fn add(v: *const Vec3, other: *const Vec3) Vec3 {
return Vec3.init(v.x() + other.x(), v.y() + other.y(), v.z() + other.z());
}
pub fn subtract(v: *const Vec3, other: *const Vec3) Vec3 {
return Vec3.init(v.x() - other.x(), v.y() - other.y(), v.z() - other.z());
}
/// Transform the v using m returning a new Vec3.
/// BasedOn: https://www.scratchapixel.com/code.php?id=4&origin=/lessons/3d-basic-rendering/perspective-and-orthographic-projection-matrix
pub fn transform(v: *const Vec3, m: *const Mat4x4) Vec3 {
const rx = (v.x() * m.data[0][0]) + (v.y() * m.data[1][0]) + (v.z() * m.data[2][0]) + m.data[3][0];
const ry = (v.x() * m.data[0][1]) + (v.y() * m.data[1][1]) + (v.z() * m.data[2][1]) + m.data[3][1];
const rz = (v.x() * m.data[0][2]) + (v.y() * m.data[1][2]) + (v.z() * m.data[2][2]) + m.data[3][2];
var rw = (v.x() * m.data[0][3]) + (v.y() * m.data[1][3]) + (v.z() * m.data[2][3]) + m.data[3][3];
if (rw != 1) {
rw = 1.0 / rw;
if (DBG) warn("transform: rw != 1 v={} m:\n{}\n", v, m);
}
return Vec3.init(rx * rw, ry * rw, rz * rw);
}
/// Custom format routine for Vec3
pub fn format(
self: *const Self,
comptime fmt: []const u8,
context: var,
comptime FmtError: type,
output: fn (@typeOf(context), []const u8) FmtError!void,
) FmtError!void {
try std.fmt.format(context, FmtError, output, "{{.x={.3} .y={.3} .z={.3}}}", self.data[0], self.data[1], self.data[2]);
}
};
pub fn vec3(x: f32, y: f32, z: f32) Vec3 {
return Vec3{ .data = []f32{
x,
y,
z,
} };
}
test "math3d.vec3" {
var v1 = vec3(1, 2, 3);
var v2 = Vec3.init(0.1, 0.2, 0.3);
assert(v1.x() == 1.0);
assert(v1.y() == 2.0);
assert(v1.z() == 3.0);
assert(v2.x() == 0.1);
assert(v2.y() == 0.2);
assert(v2.z() == 0.3);
v1.setX(v2.x());
v1.setY(v2.y());
v1.setZ(v2.z());
assert(v1.x() == v2.x());
assert(v1.y() == v2.y());
assert(v1.z() == v2.z());
v1 = Vec3.unitX();
assert(v1.x() == 1);
assert(v1.y() == 0);
assert(v1.z() == 0);
v1 = Vec3.unitY();
assert(v1.x() == 0);
assert(v1.y() == 1);
assert(v1.z() == 0);
v1 = Vec3.unitZ();
assert(v1.x() == 0);
assert(v1.y() == 0);
assert(v1.z() == 1);
// TODO: More tests
}
test "math3d.vec3.add" {
var v1 = vec3(0, 0, 0);
var v2 = vec3(0, 0, 0);
var r = v1.add(&v2);
assert(r.x() == 0);
assert(r.y() == 0);
assert(r.z() == 0);
v1 = vec3(1, 2, 3);
v2 = vec3(0.1, 0.2, 0.3);
r = v1.add(&v2);
assert(r.x() == 1.1);
assert(r.y() == 2.2);
assert(r.z() == 3.3);
}
pub const Vec4 = struct {
const Self = @This();
data: [4]f32,
pub fn init(xp: f32, yp: f32, zp: f32, wp: f32) Vec4 {
return vec4(xp, yp, zp, wp);
}
pub fn x(v: *const Vec4) f32 {
return v.data[0];
}
pub fn y(v: *const Vec4) f32 {
return v.data[1];
}
pub fn z(v: *const Vec4) f32 {
return v.data[2];
}
pub fn w(v: *const Vec4) f32 {
return v.data[3];
}
pub fn setX(v: *Vec4, xp: f32) void {
v.data[0] = xp;
}
pub fn setY(v: *Vec4, yp: f32) void {
v.data[1] = yp;
}
pub fn setZ(v: *Vec4, zp: f32) void {
v.data[2] = zp;
}
pub fn setW(v: *Vec4, wp: f32) void {
v.data[3] = wp;
}
/// Custom format routine for Vec4
pub fn format(
self: *const Self,
comptime fmt: []const u8,
context: var,
comptime FmtError: type,
output: fn (@typeOf(context), []const u8) FmtError!void,
) FmtError!void {
try std.fmt.format(context, FmtError, output, "x={.3} y={.3} z={.3} w={.3}", self.x(), self.y(), self.z(), self.w());
}
};
pub fn vec4(x: f32, y: f32, z: f32, w: f32) Vec4 {
return Vec4{ .data = []f32{
x,
y,
z,
w,
} };
}
test "math3d.vec4" {
var v1 = vec4(1, 2, 3, 0.0);
var v2 = Vec4.init(0.1, 0.2, 0.3, 1.0);
assert(v1.x() == 1.0);
assert(v1.y() == 2.0);
assert(v1.z() == 3.0);
assert(v1.w() == 0.0);
assert(v2.x() == 0.1);
assert(v2.y() == 0.2);
assert(v2.z() == 0.3);
assert(v2.w() == 1.0);
v1.setX(v2.x());
v1.setY(v2.y());
v1.setZ(v2.z());
v1.setW(v2.w());
assert(v1.x() == v2.x());
assert(v1.y() == v2.y());
assert(v1.z() == v2.z());
assert(v1.w() == v2.w());
}
/// Builds a 4x4 translation matrix
pub fn translation(x: f32, y: f32, z: f32) Mat4x4 {
return Mat4x4{ .data = [][4]f32{
[]f32{ 1.0, 0.0, 0.0, x },
[]f32{ 0.0, 1.0, 0.0, y },
[]f32{ 0.0, 0.0, 1.0, z },
[]f32{ 0.0, 0.0, 0.0, 1.0 },
} };
}
pub fn translationVec3(vertex: Vec3) Mat4x4 {
return translation(vertex.x(), vertex.y(), vertex.z());
}
test "math3d.translation" {
if (DBG) warn("\n");
var m = translation(1, 2, 3);
const expected = Mat4x4{ .data = [][4]f32{
[]f32{ 1.0, 0.0, 0.0, 1.0 },
[]f32{ 0.0, 1.0, 0.0, 2.0 },
[]f32{ 0.0, 0.0, 1.0, 3.0 },
[]f32{ 0.0, 0.0, 0.0, 1.0 },
} };
if (DBG) warn("translation: expected\n{}", &expected);
m.assert_matrix_eq(&expected);
}
/// Create look-at matrix
pub fn lookAtLh(eye: *const Vec3, target: *const Vec3, up: *const Vec3) Mat4x4 {
if (DBG) warn("math3d.lookAtLh: eye {} target {}\n", eye, target);
var zaxis = target.subtract(eye).normalize();
var xaxis = up.cross(&zaxis).normalize();
var yaxis = zaxis.cross(&xaxis);
// Column major order?
var cmo = Mat4x4{ .data = [][4]f32{
[]f32{ xaxis.x(), yaxis.x(), zaxis.x(), 0 },
[]f32{ xaxis.y(), yaxis.y(), zaxis.y(), 0 },
[]f32{ xaxis.z(), yaxis.z(), zaxis.z(), 0 },
[]f32{ -xaxis.dot(eye), -yaxis.dot(eye), -zaxis.dot(eye), 1 },
} };
// Row major order?
var rmo = Mat4x4{ .data = [][4]f32{
[]f32{ xaxis.x(), xaxis.y(), xaxis.z(), -xaxis.dot(eye) },
[]f32{ yaxis.x(), yaxis.y(), yaxis.z(), -yaxis.dot(eye) },
[]f32{ zaxis.x(), zaxis.y(), zaxis.z(), -zaxis.dot(eye) },
[]f32{ 0, 0, 0, 1 },
} };
var result = cmo;
if (DBG) warn("math3d.lookAtLh: result\n{}", &result);
return result;
}
test "math3d.lookAtLh" {
var width: f32 = 640;
var height: f32 = 480;
var scn_x: f32 = undefined;
var scn_y: f32 = undefined;
var coord: Vec3 = undefined;
var screen: Vec2 = undefined;
var point: Vec2 = undefined;
var eye = Vec3.init(0, 0, -10);
var target = Vec3.init(0, 0, 0);
var view_matrix = lookAtLh(&eye, &target, &Vec3.unitY());
const expected = Mat4x4{ .data = [][4]f32{
[]f32{ 1.00000, 0.00000, 0.00000, 0.00000 },
[]f32{ 0.00000, 1.00000, 0.00000, 0.00000 },
[]f32{ 0.00000, 0.00000, 1.00000, 0.00000 },
[]f32{ 0.00000, 0.00000, 10.00000, 1.00000 },
} };
view_matrix.assert_matrix_eq(&expected);
coord = Vec3.init(0, 0, 0);
screen = project(width, height, coord, &view_matrix);
if (DBG) warn("math3d.lookAtLh: coord={} screen={}\n", &coord, &screen);
assert(screen.x() == 320);
assert(screen.y() == 240);
coord = Vec3.init(0.1, 0.1, 0);
screen = project(width, height, coord, &view_matrix);
if (DBG) warn("math3d.lookAtLh: coord={} screen={}\n", &coord, &screen);
point = pointToScreen(width, height, 0.1, 0.1);
if (DBG) warn("math3d.lookAtLh: point={}\n", &point);
assert(screen.x() == point.x());
assert(screen.y() == point.y());
coord = Vec3.init(-0.1, -0.1, 0);
screen = project(width, height, coord, &view_matrix);
if (DBG) warn("math3d.lookAtLh: coord={} screen={}\n", &coord, &screen);
point = pointToScreen(width, height, -0.1, -0.1);
if (DBG) warn("math3d.lookAtLh: point={}\n", &point);
assert(screen.x() == point.x());
assert(screen.y() == point.y());
}
fn pointToScreen(widthf: f32, heightf: f32, pos_x: f32, pos_y: f32) Vec2 {
// The transformed coord is based on a coordinate system
// where the origin is the center of the screen. Convert
// them to coordindates where x:0, y:0 is the upper left.
var x = (pos_x + 1) * 0.5 * widthf;
var y = (1 - ((pos_y + 1) * 0.5)) * heightf;
return Vec2.init(x, y);
}
fn project(widthf: f32, heightf: f32, coord: Vec3, transMat: *const Mat4x4) Vec2 {
if (DBG) warn("project: original coord={} widthf={.3} heightf={.3}\n", &coord, widthf, heightf);
// Transform coord in 3D
var point = coord.transform(transMat);
if (DBG) warn("project: transformed point={}\n", &point);
return pointToScreen(widthf, heightf, point.x(), point.y());
}
/// Creates a right-handed perspective project matrix
/// BasedOn: https://github.com/sharpdx/SharpDX/blob/755cb46d59f4bfb94386ff2df3fceccc511c216b/Source/SharpDX.Mathematics/Matrix.cs#L2328
pub fn perspectiveFovRh(fov: f32, aspect: f32, znear: f32, zfar: f32) Mat4x4 {
var y_scale: f32 = 1.0 / math.tan(fov * 0.5);
var q = zfar / (znear - zfar);
return Mat4x4{ .data = [][4]f32{
[]f32{ y_scale / aspect, 0, 0, 0 },
[]f32{ 0, y_scale, 0, 0 },
[]f32{ 0, 0, q, -1.0 },
[]f32{ 0, 0, q * znear, 0 },
} };
}
test "math3d.perspectiveFovRh" {
var fov: f32 = 0.78;
var widthf: f32 = 640;
var heightf: f32 = 480;
var znear: f32 = 0.01;
var zvar: f32 = 1.0;
var projection_matrix = perspectiveFovRh(fov, widthf / heightf, znear, zvar);
if (DBG) warn("\nprojection_matrix:\n{}", &projection_matrix);
const expected = Mat4x4{ .data = [][4]f32{
[]f32{ 1.8245738, 0.0000000, 0.0000000, 0.0000000 },
[]f32{ 0.0000000, 2.4327650, 0.0000000, 0.0000000 },
[]f32{ 0.0000000, 0.0000000, -1.0101010, -1.0000000 },
[]f32{ 0.0000000, 0.0000000, -0.0101010, 0.0000000 },
} };
projection_matrix.assert_matrix_eq(&expected);
}
/// Builds a Yaw Pitch Roll Rotation matrix from x, y, z angles in radians.
pub fn rotationYawPitchRoll(x: f32, y: f32, z: f32) Mat4x4 {
const rz = Mat4x4{ .data = [][4]f32{
[]f32{ math.cos(z), -math.sin(z), 0.0, 0.0 },
[]f32{ math.sin(z), math.cos(z), 0.0, 0.0 },
[]f32{ 0.0, 0.0, 1.0, 0.0 },
[]f32{ 0.0, 0.0, 0.0, 1.0 },
} };
if (DBG) warn("rotationYawPitchRoll rz:\n{}", &rz);
const rx = Mat4x4{ .data = [][4]f32{
[]f32{ 1.0, 0.0, 0.0, 0.0 },
[]f32{ 0.0, math.cos(x), -math.sin(x), 0.0 },
[]f32{ 0.0, math.sin(x), math.cos(x), 0.0 },
[]f32{ 0.0, 0.0, 0.0, 1.0 },
} };
if (DBG) warn("rotationYawPitchRoll rx:\n{}", &rx);
const ry = Mat4x4{ .data = [][4]f32{
[]f32{ math.cos(y), 0.0, math.sin(y), 0.0 },
[]f32{ 0.0, 1.0, 0.0, 0.0 },
[]f32{ -math.sin(y), 0.0, math.cos(y), 0.0 },
[]f32{ 0.0, 0.0, 0.0, 1.0 },
} };
if (DBG) warn("rotationYawPitchRoll ry:\n{}", &ry);
var m = rz.mult(&ry.mult(&rx));
if (DBG) warn("rotationYawPitchRoll m:\n{}", &m);
return m;
}
pub fn rotationYawPitchRollVec3(point: Vec3) Mat4x4 {
return rotationYawPitchRoll(point.x(), point.y(), point.z());
}
/// Builds a Yaw Pitch Roll Rotation matrix from x, y, z angles in radians.
/// With the x, y, z applied in the opposite order then rotationYawPitchRoll.
pub fn rotationYawPitchRollNeg(x: f32, y: f32, z: f32) Mat4x4 {
const rz = Mat4x4{ .data = [][4]f32{
[]f32{ math.cos(z), -math.sin(z), 0.0, 0.0 },
[]f32{ math.sin(z), math.cos(z), 0.0, 0.0 },
[]f32{ 0.0, 0.0, 1.0, 0.0 },
[]f32{ 0.0, 0.0, 0.0, 1.0 },
} };
if (DBG) warn("rotationYawPitchRollNeg rz:\n{}", &rz);
const rx = Mat4x4{ .data = [][4]f32{
[]f32{ 1.0, 0.0, 0.0, 0.0 },
[]f32{ 0.0, math.cos(x), -math.sin(x), 0.0 },
[]f32{ 0.0, math.sin(x), math.cos(x), 0.0 },
[]f32{ 0.0, 0.0, 0.0, 1.0 },
} };
if (DBG) warn("rotationYawPitchRollNeg rx:\n{}", &rx);
const ry = Mat4x4{ .data = [][4]f32{
[]f32{ math.cos(y), 0.0, math.sin(y), 0.0 },
[]f32{ 0.0, 1.0, 0.0, 0.0 },
[]f32{ -math.sin(y), 0.0, math.cos(y), 0.0 },
[]f32{ 0.0, 0.0, 0.0, 1.0 },
} };
if (DBG) warn("rotationYawPitchRollNeg ry:\n{}", &ry);
var m = rx.mult(&ry.mult(&rz));
if (DBG) warn("rotationYawPitchRollNeg m:\n{}", &m);
return m;
}
test "math3d.rotationYawPitchRoll" {
if (DBG) warn("\n");
const deg10rad: f32 = 0.174522;
var m_zero = rotationYawPitchRoll(0, 0, 0);
if (DBG) warn("m_zero:\n{}", &m_zero);
var m_x_pos_ten_deg = rotationYawPitchRoll(deg10rad, 0, 0);
if (DBG) warn("m_x_pos_ten_deg:\n{}", &m_x_pos_ten_deg);
var m_x_neg_ten_deg = rotationYawPitchRoll(-deg10rad, 0, 0);
if (DBG) warn("m_x_neg_ten_deg:\n{}", &m_x_neg_ten_deg);
var x = m_x_pos_ten_deg.mult(&m_x_neg_ten_deg);
if (DBG) warn("x = pos * neg:\n{}", &x);
m_zero.assert_matrix_eq(&x);
if (DBG) warn("\n");
var m_y_pos_ten_deg = rotationYawPitchRoll(0, deg10rad, 0);
if (DBG) warn("m_y_pos_ten_deg:\n{}", m_y_pos_ten_deg);
var m_y_neg_ten_deg = rotationYawPitchRoll(0, -deg10rad, 0);
if (DBG) warn("m_y_neg_ten_deg:\n{}", m_y_neg_ten_deg);
var y = m_y_pos_ten_deg.mult(&m_y_neg_ten_deg);
if (DBG) warn("y = pos * neg:\n{}", &y);
m_zero.assert_matrix_eq(&y);
if (DBG) warn("\n");
var m_z_pos_ten_deg = rotationYawPitchRoll(0, 0, deg10rad);
if (DBG) warn("m_z_pos_ten_deg:\n{}", m_z_pos_ten_deg);
var m_z_neg_ten_deg = rotationYawPitchRoll(0, 0, -deg10rad);
if (DBG) warn("m_z_neg_ten_deg:\n{}", m_z_neg_ten_deg);
var z = m_z_pos_ten_deg.mult(&m_z_neg_ten_deg);
if (DBG) warn("z = pos * neg:\n{}", &z);
m_zero.assert_matrix_eq(&z);
if (DBG) warn("\n");
var xy_pos = m_x_pos_ten_deg.mult(&m_y_pos_ten_deg);
if (DBG) warn("xy_pos = x_pos_ten * y_pos_ten:\n{}", &xy_pos);
var a = xy_pos.mult(&m_y_neg_ten_deg);
if (DBG) warn("a = xy_pos * y_pos_ten\n{}", &a);
var b = a.mult(&m_x_neg_ten_deg);
if (DBG) warn("b = a * x_pos_ten\n{}", &b);
m_zero.assert_matrix_eq(&b);
// To undo a rotationYayPitchRoll the multiplication in rotationYawPitch
// must be applied reverse order. So rz.mult(&ry.mult(&rx)) which is
// 1) r1 = ry * rx
// 2) r2 = rz * r1
// must be applied:
// 1) r3 = -rz * r2
// 2) r4 = -ry * r3
// 3) r5 = -rx * r4
if (DBG) warn("\n");
var r2 = rotationYawPitchRoll(deg10rad, deg10rad, deg10rad);
if (DBG) warn("r2:\n{}", &r2);
var r3 = m_z_neg_ten_deg.mult(&r2);
var r4 = m_y_neg_ten_deg.mult(&r3);
var r5 = m_x_neg_ten_deg.mult(&r4);
if (DBG) warn("r5:\n{}", &r5);
m_zero.assert_matrix_eq(&r5);
// Here is the above as a single line both are equal to m_zero
r5 = m_x_neg_ten_deg.mult(&m_y_neg_ten_deg.mult(&m_z_neg_ten_deg.mult(&r2)));
if (DBG) warn("r5 one line:\n{}", &r5);
m_zero.assert_matrix_eq(&r5);
// Or you can use rotationYawPitchRollNeg
var rneg = rotationYawPitchRollNeg(-deg10rad, -deg10rad, -deg10rad);
if (DBG) warn("rneg:\n{}", &rneg);
r5 = rneg.mult(&r2);
if (DBG) warn("r5:\n{}", &r5);
m_zero.assert_matrix_eq(&r5);
}
test "math3d.world_to_screen" {
if (DBG) warn("\n");
const T = f32;
const fov: T = 90;
const widthf: T = 512;
const heightf: T = 512;
const width: u32 = @floatToInt(u32, 512);
const height: u32 = @floatToInt(u32, 512);
const aspect: T = widthf / heightf;
const znear: T = 0.01;
const zfar: T = 1.0;
var camera_to_perspective_matrix = perspectiveFovRh(fov * math.pi / 180, aspect, znear, zfar);
var world_to_camera_matrix = mat4x4_identity;
world_to_camera_matrix.data[3][2] = -2;
var world_vertexs = []Vec3{
Vec3.init(0, 1.0, 0),
Vec3.init(0, -1.0, 0),
Vec3.init(0, 1.0, 0.2),
Vec3.init(0, -1.0, -0.2),
};
var expected_camera_vertexs = []Vec3{
Vec3.init(0, 1.0, -2),
Vec3.init(0, -1.0, -2),
Vec3.init(0, 1.0, -1.8),
Vec3.init(0, -1.0, -2.2),
};
var expected_projected_vertexs = []Vec3{
Vec3.init(0, 0.5, 1.0050504),
Vec3.init(0, -0.5, 1.0050504),
Vec3.init(0, 0.5555555, 1.0044893),
Vec3.init(0, -0.4545454, 1.0055095),
};
var expected_screen_vertexs = [][2]u32{
[]u32{ 256, 128 },
[]u32{ 256, 384 },
[]u32{ 256, 113 },
[]u32{ 256, 372 },
};
for (world_vertexs) |world_vert, i| {
if (DBG) warn("world_vert[{}] = {}\n", i, &world_vert);
var camera_vert = world_vert.transform(&world_to_camera_matrix);
if (DBG) warn("camera_vert = {}\n", camera_vert);
assert(camera_vert.approxEql(&expected_camera_vertexs[i], 6));
var projected_vert = camera_vert.transform(&camera_to_perspective_matrix);
if (DBG) warn("projected_vert = {}", projected_vert);
assert(projected_vert.approxEql(&expected_projected_vertexs[i], 6));
var xf = projected_vert.x();
var yf = projected_vert.y();
if (DBG) warn(" {.3}:{.3}", xf, yf);
if ((xf < -1) or (xf > 1) or (yf < -1) or (yf > 1)) {
if (DBG) warn(" clipped\n");
}
var x = @floatToInt(u32, math.min(widthf - 1, (xf + 1) * 0.5 * widthf));
var y = @floatToInt(u32, math.min(heightf - 1, (1 - (yf + 1) * 0.5) * heightf));
if (DBG) warn(" visible {}:{}\n", x, y);
assert(x == expected_screen_vertexs[i][0]);
assert(y == expected_screen_vertexs[i][1]);
}
} | deprecated/math3d.zig |
const std = @import("std");
const util = @import("util.zig");
const data = @embedFile("../data/day04.txt");
const BingoBoard = struct {
mask: u25 = 0,
is_winner: bool = false,
cells: [5][5]u8 = undefined,
};
const BoardLoc = struct {
board: usize,
row: u5,
col: u5,
};
const NumLocsMap = struct {
map: std.AutoHashMap(u8, std.ArrayList(BoardLoc)) = undefined,
pub fn init(allocator: std.mem.Allocator) @This() {
var map = std.AutoHashMap(u8, std.ArrayList(BoardLoc)).init(allocator);
return @This(){
.map = map,
};
}
pub fn deinit(self: *@This()) void {
var itor = self.map.valueIterator();
while (itor.next()) |val| {
val.deinit();
}
self.map.deinit();
self.* = undefined;
}
pub fn add(self: *@This(), num: u8, loc: BoardLoc) void {
if (self.map.getOrPut(num)) |result| {
if (!result.found_existing) {
result.value_ptr.* = std.ArrayList(BoardLoc).init(self.map.allocator);
}
result.value_ptr.append(loc) catch unreachable;
} else |err| {
print("getOrPut error: {}\n", .{err});
}
}
pub fn get(self: @This(), num: u8) ?std.ArrayList(BoardLoc) {
return self.map.get(num);
}
};
test "AutoHashMap" {
var map = NumLocsMap.init(std.testing.allocator);
defer map.deinit();
map.add(17, BoardLoc{ .board = 1, .row = 2, .col = 3 });
map.add(17, BoardLoc{ .board = 4, .row = 5, .col = 6 });
map.add(23, BoardLoc{ .board = 7, .row = 8, .col = 9 });
try expect(map.map.count() == 2);
const locs17 = map.get(17);
try expect(locs17 != null);
try expect(locs17.?.items.len == 2);
try expect(locs17.?.items[1].col == 6);
const locs23 = map.get(23);
try expect(locs23 != null);
try expect(locs23.?.items.len == 1);
try expect(locs23.?.items[0].col == 9);
try expect(map.get(42) == null);
}
const win_masks = [10]u25{
0b00000_00000_00000_00000_11111,
0b00000_00000_00000_11111_00000,
0b00000_00000_11111_00000_00000,
0b00000_11111_00000_00000_00000,
0b11111_00000_00000_00000_00000,
0b00001_00001_00001_00001_00001,
0b00010_00010_00010_00010_00010,
0b00100_00100_00100_00100_00100,
0b01000_01000_01000_01000_01000,
0b10000_10000_10000_10000_10000,
};
const Input = struct {
numbers: []const u8,
boards: std.ArrayList(BingoBoard) = std.ArrayList(BingoBoard).init(std.testing.allocator),
board_locs: NumLocsMap = NumLocsMap.init(std.testing.allocator),
pub fn deinit(self: *@This()) void {
self.boards.deinit();
self.board_locs.deinit();
self.* = undefined;
}
};
fn parseInput(input_text: []const u8) Input {
var lines = std.mem.split(u8, input_text, "\n");
// First line is a list of comma-separated numbers
var input = Input{
.numbers = std.mem.trimRight(u8, lines.next().?, "\r"),
};
// Can't go in .init() because default-initialized values must be compile-time constants & can't allocate.
input.board_locs.map.ensureTotalCapacity(100) catch unreachable;
// Each board is six lines: a blank line, then five rows of five cells each
while (lines.next()) |_| {
var board = BingoBoard{};
var row: u5 = 0;
while (row < 5) : (row += 1) {
var row_cells = std.mem.trimRight(u8, lines.next().?, "\r");
var col: u5 = 0;
while (col < 5) : (col += 1) {
const cell = std.mem.trim(u8, row_cells[3 * col .. 3 * col + 2], " ");
const n = parseInt(u8, cell, 10) catch unreachable;
board.cells[row][col] = n;
input.board_locs.add(n, BoardLoc{ .board = input.boards.items.len, .row = row, .col = col });
}
}
input.boards.append(board) catch unreachable;
}
return input;
}
fn boardValue(board: BingoBoard, num: u8) i64 {
var sum: i64 = 0;
var bit: u5 = 0;
while (bit < 25) : (bit += 1) {
if (board.mask & @as(u25, 1) << bit == 0) {
const row = bit / 5;
const col = bit % 5;
sum += board.cells[row][col];
}
}
return sum * num;
}
fn part1(input: Input) i64 {
var nums = std.mem.tokenize(u8, input.numbers, ",");
while (nums.next()) |token| {
const num = parseInt(u8, token, 10) catch unreachable;
if (input.board_locs.get(num)) |locs| {
for (locs.items) |loc| {
const board = &input.boards.items[loc.board];
assert(board.cells[loc.row][loc.col] == num);
const bit: u5 = @intCast(u5, loc.row) * 5 + @intCast(u5, loc.col);
board.mask |= @as(u25, 1) << bit;
for (win_masks) |win_mask| {
if (board.mask & win_mask == win_mask) {
return boardValue(board.*, num);
}
}
}
}
}
unreachable;
}
fn part2(input: Input) i64 {
var nums = std.mem.tokenize(u8, input.numbers, ",");
var num_boards_left: usize = input.boards.items.len;
while (nums.next()) |token| {
const num = parseInt(u8, token, 10) catch unreachable;
if (input.board_locs.get(num)) |locs| {
for (locs.items) |loc| {
const board = &input.boards.items[loc.board];
assert(board.cells[loc.row][loc.col] == num);
if (board.is_winner) {
continue;
}
const bit: u5 = @intCast(u5, loc.row) * 5 + @intCast(u5, loc.col);
board.mask |= @as(u25, 1) << bit;
for (win_masks) |win_mask| {
if (board.mask & win_mask == win_mask) {
board.is_winner = true;
num_boards_left -= 1;
if (num_boards_left == 0) {
return boardValue(board.*, num);
}
break;
}
}
}
}
}
unreachable;
}
fn testPart1() !void {
var test_input = parseInput(test_data);
defer test_input.deinit();
try std.testing.expectEqual(@as(i64, 4512), part1(test_input));
var input = parseInput(data);
defer input.deinit();
try std.testing.expectEqual(@as(i64, 64084), part1(input));
}
fn testPart2() !void {
var test_input = parseInput(test_data);
defer test_input.deinit();
try std.testing.expectEqual(@as(i64, 1924), part2(test_input));
var input = parseInput(data);
defer input.deinit();
try std.testing.expectEqual(@as(i64, 12833), part2(input));
}
pub fn main() !void {
try testPart1();
try testPart2();
}
const test_data =
\\7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1
\\
\\22 13 17 11 0
\\ 8 2 23 4 24
\\21 9 14 16 7
\\ 6 10 3 18 5
\\ 1 12 20 15 19
\\
\\ 3 15 0 2 22
\\ 9 18 13 17 5
\\19 8 7 25 23
\\20 11 10 24 4
\\14 21 16 12 6
\\
\\14 21 17 24 4
\\10 16 15 9 19
\\18 8 23 26 20
\\22 11 13 6 5
\\ 2 0 12 3 7
;
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/day04.zig |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.