code
stringlengths
38
801k
repo_path
stringlengths
6
263
const std = @import("std"); const os = @import("windows.zig"); const HRESULT = os.HRESULT; pub const Rect = extern struct { X: c_int, Y: c_int, Width: c_int, Height: c_int, }; pub const DecodeOptions = extern enum { MetadataCacheOnDemand = 0, MetadataCacheOnLoad = 0x1, }; pub const BitmapPaletteType = extern enum { Custom = 0, MedianCut = 0x1, FixedBW = 0x2, FixedHalftone8 = 0x3, FixedHalftone27 = 0x4, FixedHalftone64 = 0x5, FixedHalftone125 = 0x6, FixedHalftone216 = 0x7, FixedHalftone252 = 0x8, FixedHalftone256 = 0x9, FixedGray4 = 0xa, FixedGray16 = 0xb, FixedGray256 = 0xc, }; pub const BitmapDitherType = extern enum { None = 0, Solid = 0, Ordered4x4 = 0x1, Ordered8x8 = 0x2, Ordered16x16 = 0x3, Spiral4x4 = 0x4, Spiral8x8 = 0x5, DualSpiral4x4 = 0x6, DualSpiral8x8 = 0x7, ErrorDiffusion = 0x8, }; pub const IBitmapSource = extern struct { const Self = @This(); vtbl: *const extern struct { // IUnknown QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT, AddRef: fn (*Self) callconv(.C) u32, Release: fn (*Self) callconv(.C) u32, // IWICBitmapSource GetSize: fn (*Self, *u32, *u32) callconv(.C) HRESULT, GetPixelFormat: fn (*Self, *os.GUID) callconv(.C) HRESULT, GetResolution: *c_void, CopyPalette: *c_void, CopyPixels: fn (*Self, ?*const Rect, u32, u32, [*]u8) callconv(.C) HRESULT, }, usingnamespace os.IUnknown.Methods(Self); usingnamespace IBitmapSource.Methods(Self); fn Methods(comptime T: type) type { return extern struct { pub inline fn GetSize(self: *T, width: *u32, height: *u32) HRESULT { return self.vtbl.GetSize(self, width, height); } pub inline fn GetPixelFormat(self: *T, pPixelFormat: *os.GUID) HRESULT { return self.vtbl.GetPixelFormat(self, pPixelFormat); } pub inline fn CopyPixels( self: *T, prc: ?*const Rect, cbStride: u32, cbBufferSize: u32, pbBuffer: [*]u8, ) HRESULT { return self.vtbl.CopyPixels(self, prc, cbStride, cbBufferSize, pbBuffer); } }; } }; pub const IBitmapFrameDecode = extern struct { const Self = @This(); vtbl: *const extern struct { // IUnknown QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT, AddRef: fn (*Self) callconv(.C) u32, Release: fn (*Self) callconv(.C) u32, // IWICBitmapSource GetSize: fn (*Self, *u32, *u32) callconv(.C) HRESULT, GetPixelFormat: fn (*Self, *os.GUID) callconv(.C) HRESULT, GetResolution: *c_void, CopyPalette: *c_void, CopyPixels: fn (*Self, ?*const Rect, u32, u32, [*]u8) callconv(.C) HRESULT, // IBitmapFrameDecode GetMetadataQueryReader: *c_void, GetColorContexts: *c_void, GetThumbnail: *c_void, }, usingnamespace os.IUnknown.Methods(Self); usingnamespace IBitmapSource.Methods(Self); }; pub const IBitmap = extern struct { const Self = @This(); vtbl: *const extern struct { // IUnknown QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT, AddRef: fn (*Self) callconv(.C) u32, Release: fn (*Self) callconv(.C) u32, // IWICBitmapSource GetSize: fn (*Self, *u32, *u32) callconv(.C) HRESULT, GetPixelFormat: fn (*Self, *os.GUID) callconv(.C) HRESULT, GetResolution: *c_void, CopyPalette: *c_void, CopyPixels: fn (*Self, ?*const Rect, u32, u32, [*]u8) callconv(.C) HRESULT, // IWICBitmap Lock: *c_void, SetPalette: *c_void, SetResolution: *c_void, }, usingnamespace os.IUnknown.Methods(Self); usingnamespace IBitmapSource.Methods(Self); }; pub const IFormatConverter = extern struct { const Self = @This(); vtbl: *const extern struct { // IUnknown QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT, AddRef: fn (*Self) callconv(.C) u32, Release: fn (*Self) callconv(.C) u32, // IWICBitmapSource GetSize: fn (*Self, *u32, *u32) callconv(.C) HRESULT, GetPixelFormat: fn (*Self, *os.GUID) callconv(.C) HRESULT, GetResolution: *c_void, CopyPalette: *c_void, CopyPixels: fn (*Self, ?*const Rect, u32, u32, [*]u8) callconv(.C) HRESULT, // IWICFormatConverter Initialize: fn ( *Self, ?*IBitmapSource, *const os.GUID, BitmapDitherType, ?*IPalette, f64, BitmapPaletteType, ) callconv(.C) HRESULT, CanConvert: *c_void, }, usingnamespace os.IUnknown.Methods(Self); usingnamespace IBitmapSource.Methods(Self); usingnamespace IFormatConverter.Methods(Self); fn Methods(comptime T: type) type { return extern struct { pub inline fn Initialize( self: *T, pISource: ?*IBitmapSource, dstFormat: *const os.GUID, dither: BitmapDitherType, pIPalette: ?*IPalette, alphaThresholdPercent: f64, paletteTranslate: BitmapPaletteType, ) HRESULT { return self.vtbl.Initialize( self, pISource, dstFormat, dither, pIPalette, alphaThresholdPercent, paletteTranslate, ); } }; } }; pub const IPalette = extern struct { const Self = @This(); vtbl: *const extern struct { // IUnknown QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT, AddRef: fn (*Self) callconv(.C) u32, Release: fn (*Self) callconv(.C) u32, // IWICPalette InitializePredefined: *c_void, InitializeCustom: *c_void, InitializeFromBitmap: *c_void, InitializeFromPalette: *c_void, GetType: *c_void, GetColorCount: *c_void, GetColors: *c_void, IsBlackWhite: *c_void, IsGrayscale: *c_void, HasAlpha: *c_void, }, usingnamespace os.IUnknown.Methods(Self); }; pub const IBitmapDecoder = extern struct { const Self = @This(); vtbl: *const extern struct { // IUnknown QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT, AddRef: fn (*Self) callconv(.C) u32, Release: fn (*Self) callconv(.C) u32, // IWICBitmapDecoder QueryCapability: *c_void, Initialize: *c_void, GetContainerFormat: *c_void, GetDecoderInfo: *c_void, CopyPalette: *c_void, GetMetadataQueryReader: *c_void, GetPreview: *c_void, GetColorContexts: *c_void, GetThumbnail: *c_void, GetFrameCount: *c_void, GetFrame: fn (*Self, u32, **IBitmapFrameDecode) callconv(.C) HRESULT, }, usingnamespace os.IUnknown.Methods(Self); usingnamespace IBitmapDecoder.Methods(Self); fn Methods(comptime T: type) type { return extern struct { pub inline fn GetFrame(self: *T, index: u32, ppIBitmapFrame: **IBitmapFrameDecode) HRESULT { return self.vtbl.GetFrame(self, index, ppIBitmapFrame); } }; } }; pub const IImagingFactory = extern struct { const Self = @This(); vtbl: *const extern struct { // IUnknown QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT, AddRef: fn (*Self) callconv(.C) u32, Release: fn (*Self) callconv(.C) u32, // IWICImagingFactory CreateDecoderFromFilename: fn ( *Self, os.LPCWSTR, ?*const os.GUID, os.DWORD, DecodeOptions, **IBitmapDecoder, ) callconv(.C) HRESULT, CreateDecoderFromStream: *c_void, CreateDecoderFromFileHandle: *c_void, CreateComponentInfo: *c_void, CreateDecoder: *c_void, CreateEncoder: *c_void, CreatePalette: *c_void, CreateFormatConverter: fn (*Self, **IFormatConverter) callconv(.C) HRESULT, CreateBitmapScaler: *c_void, CreateBitmapClipper: *c_void, CreateBitmapFlipRotator: *c_void, CreateStream: *c_void, CreateColorContext: *c_void, CreateColorTransformer: *c_void, CreateBitmap: *c_void, CreateBitmapFromSource: *c_void, CreateBitmapFromSourceRect: *c_void, CreateBitmapFromMemory: *c_void, CreateBitmapFromHBITMAP: *c_void, CreateBitmapFromHICON: *c_void, CreateComponentEnumerator: *c_void, CreateFastMetadataEncoderFromDecoder: *c_void, CreateFastMetadataEncoderFromFrameDecode: *c_void, CreateQueryWriter: *c_void, CreateQueryWriterFromReader: *c_void, }, usingnamespace os.IUnknown.Methods(Self); usingnamespace IImagingFactory.Methods(Self); fn Methods(comptime T: type) type { return extern struct { pub inline fn CreateDecoderFromFilename( self: *T, wzFilename: os.LPCWSTR, pguidVendor: ?*const os.GUID, dwDesiredAccess: os.DWORD, metadataOptions: DecodeOptions, ppIDecoder: **IBitmapDecoder, ) HRESULT { return self.vtbl.CreateDecoderFromFilename( self, wzFilename, pguidVendor, dwDesiredAccess, metadataOptions, ppIDecoder, ); } pub inline fn CreateFormatConverter( self: *T, ppIFormatConverter: **IFormatConverter, ) HRESULT { return self.vtbl.CreateFormatConverter(self, ppIFormatConverter); } }; } }; pub const CLSID_ImagingFactory = os.GUID{ .Data1 = 0xcacaf262, .Data2 = 0x9370, .Data3 = 0x4615, .Data4 = .{ 0xa1, 0x3b, 0x9f, 0x55, 0x39, 0xda, 0x4c, 0xa }, }; pub const IID_IImagingFactory = os.GUID{ .Data1 = 0xec5ec8a9, .Data2 = 0xc395, .Data3 = 0x4314, .Data4 = .{ 0x9c, 0x77, 0x54, 0xd7, 0xa9, 0x35, 0xff, 0x70 }, }; pub const GUID_PixelFormat24bppRGB = os.GUID{ .Data1 = 0x6fddc324, .Data2 = 0x4e03, .Data3 = 0x4bfe, .Data4 = .{ 0xb1, 0x85, 0x3d, 0x77, 0x76, 0x8d, 0xc9, 0x0d }, }; pub const GUID_PixelFormat32bppRGB = os.GUID{ .Data1 = 0xd98c6b95, .Data2 = 0x3efe, .Data3 = 0x47d6, .Data4 = .{ 0xbb, 0x25, 0xeb, 0x17, 0x48, 0xab, 0x0c, 0xf1 }, }; pub const GUID_PixelFormat32bppRGBA = os.GUID{ .Data1 = 0xf5c7ad2d, .Data2 = 0x6a8d, .Data3 = 0x43dd, .Data4 = .{ 0xa7, 0xa8, 0xa2, 0x99, 0x35, 0x26, 0x1a, 0xe9 }, }; pub const GUID_PixelFormat32bppPRGBA = os.GUID{ .Data1 = 0x3cc4a650, .Data2 = 0xa527, .Data3 = 0x4d37, .Data4 = .{ 0xa9, 0x16, 0x31, 0x42, 0xc7, 0xeb, 0xed, 0xba }, }; pub const GUID_PixelFormat24bppBGR = os.GUID{ .Data1 = 0x6fddc324, .Data2 = 0x4e03, .Data3 = 0x4bfe, .Data4 = .{ 0xb1, 0x85, 0x3d, 0x77, 0x76, 0x8d, 0xc9, 0x0c }, }; pub const GUID_PixelFormat32bppBGR = os.GUID{ .Data1 = 0x6fddc324, .Data2 = 0x4e03, .Data3 = 0x4bfe, .Data4 = .{ 0xb1, 0x85, 0x3d, 0x77, 0x76, 0x8d, 0xc9, 0x0e }, }; pub const GUID_PixelFormat32bppBGRA = os.GUID{ .Data1 = 0x6fddc324, .Data2 = 0x4e03, .Data3 = 0x4bfe, .Data4 = .{ 0xb1, 0x85, 0x3d, 0x77, 0x76, 0x8d, 0xc9, 0x0f }, }; pub const GUID_PixelFormat32bppPBGRA = os.GUID{ .Data1 = 0x6fddc324, .Data2 = 0x4e03, .Data3 = 0x4bfe, .Data4 = .{ 0xb1, 0x85, 0x3d, 0x77, 0x76, 0x8d, 0xc9, 0x10 }, }; pub const GUID_PixelFormat8bppGray = os.GUID{ .Data1 = 0x6fddc324, .Data2 = 0x4e03, .Data3 = 0x4bfe, .Data4 = .{ 0xb1, 0x85, 0x3d, 0x77, 0x76, 0x8d, 0xc9, 0x08 }, }; pub const GUID_PixelFormat8bppAlpha = os.GUID{ .Data1 = 0xe6cd0116, .Data2 = 0xeeba, .Data3 = 0x4161, .Data4 = .{ 0xaa, 0x85, 0x27, 0xdd, 0x9f, 0xb3, 0xa8, 0x95 }, };
src/windows/wincodec.zig
const std = @import("std"); const c = @import("c.zig"); const git = @import("../git.zig"); pub fn blobFilterOptions(self: git.BlobFilterOptions) c.git_blob_filter_options { return .{ .version = c.GIT_BLOB_FILTER_OPTIONS_VERSION, .flags = @bitCast(u32, self.flags), .commit_id = @ptrCast(?*c.git_oid, self.commit_id), }; } pub fn describeOptions(self: git.DescribeOptions) c.git_describe_options { return .{ .version = c.GIT_DESCRIBE_OPTIONS_VERSION, .max_candidates_tags = self.max_candidate_tags, .describe_strategy = @enumToInt(self.describe_strategy), .pattern = if (self.pattern) |slice| slice.ptr else null, .only_follow_first_parent = @boolToInt(self.only_follow_first_parent), .show_commit_oid_as_fallback = @boolToInt(self.show_commit_oid_as_fallback), }; } pub fn describeFormatOptions(self: git.DescribeFormatOptions) c.git_describe_format_options { return .{ .version = c.GIT_DESCRIBE_FORMAT_OPTIONS_VERSION, .abbreviated_size = self.abbreviated_size, .always_use_long_format = @boolToInt(self.always_use_long_format), .dirty_suffix = if (self.dirty_suffix) |slice| slice.ptr else null, }; } pub fn filterOptions(self: git.FilterOptions) c.git_filter_options { return .{ .version = c.GIT_FILTER_OPTIONS_VERSION, .flags = @bitCast(u32, self.flags), .commit_id = @ptrCast(?*c.git_oid, self.commit_id), }; } pub fn repositoryInitOptions(self: git.RepositoryInitOptions) c.git_repository_init_options { return .{ .version = c.GIT_REPOSITORY_INIT_OPTIONS_VERSION, .flags = self.flags.toInt(), .mode = self.mode.toInt(), .workdir_path = if (self.workdir_path) |slice| slice.ptr else null, .description = if (self.description) |slice| slice.ptr else null, .template_path = if (self.template_path) |slice| slice.ptr else null, .initial_head = if (self.initial_head) |slice| slice.ptr else null, .origin_url = if (self.origin_url) |slice| slice.ptr else null, }; } pub fn hashsigOptions(self: git.HashsigOptions) c.git_hashsig_option_t { var ret: c.git_hashsig_option_t = 0; if (self.allow_small_files) { ret |= c.GIT_HASHSIG_ALLOW_SMALL_FILES; } switch (self.whitespace_mode) { .normal => ret |= c.GIT_HASHSIG_NORMAL, .ignore_whitespace => ret |= c.GIT_HASHSIG_IGNORE_WHITESPACE, .smart_whitespace => ret |= c.GIT_HASHSIG_SMART_WHITESPACE, } return ret; } pub fn mergeOptions(self: git.MergeOptions) c.git_merge_options { return .{ .version = c.GIT_MERGE_OPTIONS_VERSION, .flags = @bitCast(u32, self.flags), .rename_threshold = self.rename_threshold, .target_limit = self.target_limit, .metric = @ptrCast(?*c.git_diff_similarity_metric, self.metric), .recursion_limit = self.recursion_limit, .default_driver = if (self.default_driver) |ptr| ptr.ptr else null, .file_favor = @enumToInt(self.file_favor), .file_flags = @bitCast(u32, self.file_flags), }; } pub fn fileStatusOptions(self: git.FileStatusOptions) c.git_status_options { return .{ .version = c.GIT_STATUS_OPTIONS_VERSION, .show = @enumToInt(self.show), .flags = @bitCast(c_int, self.flags), .pathspec = @bitCast(c.git_strarray, self.pathspec), .baseline = @ptrCast(?*c.git_tree, self.baseline), }; } pub fn applyOptions(self: git.ApplyOptions) c.git_apply_options { return .{ .version = c.GIT_APPLY_OPTIONS_VERSION, .delta_cb = @ptrCast(c.git_apply_delta_cb, self.delta_cb), .hunk_cb = @ptrCast(c.git_apply_hunk_cb, self.hunk_cb), .payload = null, .flags = @bitCast(c_uint, self.flags), }; } pub fn applyOptionsWithUserData(comptime T: type, self: git.ApplyOptionsWithUserData(T)) c.git_apply_options { return .{ .version = c.GIT_APPLY_OPTIONS_VERSION, .delta_cb = @ptrCast(c.git_apply_delta_cb, self.delta_cb), .hunk_cb = @ptrCast(c.git_apply_hunk_cb, self.hunk_cb), .payload = self.payload, .flags = @bitCast(c_uint, self.flags), }; } pub fn blameOptions(self: git.BlameOptions) c.git_blame_options { return .{ .version = c.GIT_BLAME_OPTIONS_VERSION, .flags = @bitCast(u32, self.flags), .min_match_characters = self.min_match_characters, .newest_commit = @bitCast(c.git_oid, self.newest_commit), .oldest_commit = @bitCast(c.git_oid, self.oldest_commit), .min_line = self.min_line, .max_line = self.max_line, }; } pub fn checkoutOptions(self: git.CheckoutOptions) c.git_checkout_options { return .{ .version = c.GIT_CHECKOUT_OPTIONS_VERSION, .checkout_strategy = @bitCast(c_uint, self.checkout_strategy), .disable_filters = @boolToInt(self.disable_filters), .dir_mode = self.dir_mode, .file_mode = self.file_mode, .file_open_flags = self.file_open_flags, .notify_flags = @bitCast(c_uint, self.notify_flags), .notify_cb = @ptrCast(c.git_checkout_notify_cb, self.notify_cb), .notify_payload = self.notify_payload, .progress_cb = @ptrCast(c.git_checkout_progress_cb, self.progress_cb), .progress_payload = self.progress_payload, .paths = @bitCast(c.git_strarray, self.paths), .baseline = @ptrCast(?*c.git_tree, self.baseline), .baseline_index = @ptrCast(?*c.git_index, self.baseline_index), .target_directory = if (self.target_directory) |ptr| ptr.ptr else null, .ancestor_label = if (self.ancestor_label) |ptr| ptr.ptr else null, .our_label = if (self.our_label) |ptr| ptr.ptr else null, .their_label = if (self.their_label) |ptr| ptr.ptr else null, .perfdata_cb = @ptrCast(c.git_checkout_perfdata_cb, self.perfdata_cb), .perfdata_payload = self.perfdata_payload, }; } pub fn cherrypickOptions(self: git.CherrypickOptions) c.git_cherrypick_options { return .{ .version = c.GIT_CHERRYPICK_OPTIONS_VERSION, .mainline = @boolToInt(self.mainline), .merge_opts = mergeOptions(self.merge_options), .checkout_opts = checkoutOptions(self.checkout_options), }; } pub fn attributeOptions(self: git.AttributeOptions) c.git_attr_options { return .{ .version = c.GIT_ATTR_OPTIONS_VERSION, .flags = attributeFlags(self.flags), .commit_id = @ptrCast(*c.git_oid, self.commit_id), }; } pub fn attributeFlags(self: git.AttributeFlags) c_uint { var result: c_uint = 0; switch (self.location) { .file_then_index => {}, .index_then_file => result |= c.GIT_ATTR_CHECK_INDEX_THEN_FILE, .index_only => result |= c.GIT_ATTR_CHECK_INDEX_ONLY, } if (self.extended.no_system) { result |= c.GIT_ATTR_CHECK_NO_SYSTEM; } if (self.extended.include_head) { result |= c.GIT_ATTR_CHECK_INCLUDE_HEAD; } if (self.extended.include_commit) { result |= c.GIT_ATTR_CHECK_INCLUDE_COMMIT; } return result; } pub fn worktreeAddOptions(self: git.WorktreeAddOptions) c.git_worktree_add_options { return .{ .version = c.GIT_WORKTREE_ADD_OPTIONS_VERSION, .lock = @boolToInt(self.lock), .ref = @ptrCast(?*c.git_reference, self.ref), }; } pub fn revertOptions(self: git.RevertOptions) c.git_revert_options { return .{ .version = c.GIT_REVERT_OPTIONS_VERSION, .mainline = @boolToInt(self.mainline), .merge_opts = mergeOptions(self.merge_options), .checkout_opts = checkoutOptions(self.checkout_options), }; } pub fn fetchOptions(self: git.FetchOptions) c.git_fetch_options { return .{ .version = c.GIT_FETCH_OPTIONS_VERSION, .callbacks = @bitCast(c.git_remote_callbacks, self.callbacks), .prune = @enumToInt(self.prune), .update_fetchhead = @boolToInt(self.update_fetchhead), .download_tags = @enumToInt(self.download_tags), .proxy_opts = proxyOptions(self.proxy_opts), .custom_headers = @bitCast(c.git_strarray, self.custom_headers), }; } pub fn cloneOptions(self: git.CloneOptions) c.git_clone_options { return .{ .version = c.GIT_CHECKOUT_OPTIONS_VERSION, .checkout_opts = checkoutOptions(self.checkout_options), .fetch_opts = fetchOptions(self.fetch_options), .bare = @boolToInt(self.bare), .local = @enumToInt(self.local), .checkout_branch = if (self.checkout_branch) |b| b.ptr else null, .repository_cb = @ptrCast(c.git_repository_create_cb, self.repository_cb), .repository_cb_payload = self.repository_cb_payload, .remote_cb = @ptrCast(c.git_remote_create_cb, self.remote_cb), .remote_cb_payload = self.remote_cb_payload, }; } pub fn proxyOptions(self: git.ProxyOptions) c.git_proxy_options { return .{ .version = c.GIT_PROXY_OPTIONS_VERSION, .@"type" = @enumToInt(self.proxy_type), .url = if (self.url) |s| s.ptr else null, .credentials = @ptrCast(c.git_credential_acquire_cb, self.credentials), .payload = self.payload, .certificate_check = @ptrCast(c.git_transport_certificate_check_cb, self.certificate_check), }; } pub fn createOptions(self: git.RemoteCreateOptions) c.git_remote_create_options { return .{ .version = c.GIT_STATUS_OPTIONS_VERSION, .repository = @ptrCast(?*c.git_repository, self.repository), .name = if (self.name) |ptr| ptr.ptr else null, .fetchspec = if (self.fetchspec) |ptr| ptr.ptr else null, .flags = @bitCast(c_uint, self.flags), }; } pub fn pushOptions(self: git.PushOptions) c.git_push_options { return .{ .version = c.GIT_PUSH_OPTIONS_VERSION, .pb_parallelism = self.pb_parallelism, .callbacks = @bitCast(c.git_remote_callbacks, self.callbacks), .proxy_opts = proxyOptions(self.proxy_opts), .custom_headers = @bitCast(c.git_strarray, self.custom_headers), }; } pub fn pruneOptions(self: git.PruneOptions) c.git_worktree_prune_options { return .{ .version = c.GIT_WORKTREE_PRUNE_OPTIONS_VERSION, .flags = @bitCast(u32, self), }; } comptime { std.testing.refAllDecls(@This()); }
src/internal/make_c_option.zig
const std = @import("std"); const ascii = std.ascii; const mem = std.mem; const os = std.os; const expect = std.testing.expect; /// Parsed option struct. pub const Option = struct { /// Option character. opt: u8, /// Option argument, if any. arg: ?[]const u8 = null, }; pub const Error = error{ InvalidOption, MissingArgument }; pub const OptionsIterator = struct { argv: [][*:0]const u8, opts: []const u8, /// Index of the current element of the argv vector. optind: usize = 1, optpos: usize = 1, /// Current option character. optopt: u8 = undefined, pub fn next(self: *OptionsIterator) Error!?Option { if (self.optind == self.argv.len) return null; const arg = self.argv[self.optind]; if (mem.eql(u8, mem.span(arg), "--")) { self.optind += 1; return null; } if (arg[0] != '-' or !ascii.isAlNum(arg[1])) return null; self.optopt = arg[self.optpos]; const maybe_idx = mem.indexOfScalar(u8, self.opts, self.optopt); if (maybe_idx) |idx| { if (idx < self.opts.len - 1 and self.opts[idx + 1] == ':') { if (arg[self.optpos + 1] != 0) { const res = Option{ .opt = self.optopt, .arg = mem.span(arg + self.optpos + 1), }; self.optind += 1; self.optpos = 1; return res; } else if (self.optind + 1 < self.argv.len) { const res = Option{ .opt = self.optopt, .arg = mem.span(self.argv[self.optind + 1]), }; self.optind += 2; self.optpos = 1; return res; } else return Error.MissingArgument; } else { self.optpos += 1; if (arg[self.optpos] == 0) { self.optind += 1; self.optpos = 1; } return Option{ .opt = self.optopt }; } } else return Error.InvalidOption; } /// Return remaining arguments, if any. pub fn args(self: *OptionsIterator) ?[][*:0]const u8 { if (self.optind < self.argv.len) return self.argv[self.optind..] else return null; } }; fn getoptArgv(argv: [][*:0]const u8, optstring: []const u8) OptionsIterator { return OptionsIterator{ .argv = argv, .opts = optstring, }; } /// Parse os.argv according to the optstring. pub fn getopt(optstring: []const u8) OptionsIterator { // https://github.com/ziglang/zig/issues/8808 const argv: [][*:0]const u8 = os.argv; return getoptArgv(argv, optstring); } test "no args separate" { var argv = [_][*:0]const u8{ "getopt", "-a", "-b", }; const expected = [_]Option{ .{ .opt = 'a' }, .{ .opt = 'b' }, }; var opts = getoptArgv(&argv, "ab"); var i: usize = 0; while (try opts.next()) |opt| : (i += 1) { try expect(opt.opt == expected[i].opt); if (opt.arg != null and expected[i].arg != null) { try expect(mem.eql(u8, opt.arg.?, expected[i].arg.?)); } else { try expect(opt.arg == null and expected[i].arg == null); } } try expect(opts.args() == null); } test "no args joined" { var argv = [_][*:0]const u8{ "getopt", "-abc", }; const expected = [_]Option{ .{ .opt = 'a' }, .{ .opt = 'b' }, .{ .opt = 'c' }, }; var opts = getoptArgv(&argv, "abc"); var i: usize = 0; while (try opts.next()) |opt| : (i += 1) { try expect(opt.opt == expected[i].opt); if (opt.arg != null and expected[i].arg != null) { try expect(mem.eql(u8, opt.arg.?, expected[i].arg.?)); } else { try expect(opt.arg == null and expected[i].arg == null); } } } test "with args separate" { var argv = [_][*:0]const u8{ "getopt", "-a10", "-b", "-c", "42", }; const expected = [_]Option{ .{ .opt = 'a', .arg = "10", }, .{ .opt = 'b' }, .{ .opt = 'c', .arg = "42", }, }; var opts = getoptArgv(&argv, "a:bc:"); var i: usize = 0; while (try opts.next()) |opt| : (i += 1) { try expect(opt.opt == expected[i].opt); if (opt.arg != null and expected[i].arg != null) { try expect(mem.eql(u8, opt.arg.?, expected[i].arg.?)); } else { try expect(opt.arg == null and expected[i].arg == null); } } } test "with args joined" { var argv = [_][*:0]const u8{ "getopt", "-a10", "-bc", "42", }; const expected = [_]Option{ .{ .opt = 'a', .arg = "10", }, .{ .opt = 'b' }, .{ .opt = 'c', .arg = "42", }, }; var opts = getoptArgv(&argv, "a:bc:"); var i: usize = 0; while (try opts.next()) |opt| : (i += 1) { try expect(opt.opt == expected[i].opt); if (opt.arg != null and expected[i].arg != null) { try expect(mem.eql(u8, opt.arg.?, expected[i].arg.?)); } else { try expect(opt.arg == null and expected[i].arg == null); } } } test "invalid option" { var argv = [_][*:0]const u8{ "getopt", "-az", }; var opts = getoptArgv(&argv, "a"); // -a is ok try expect((try opts.next()).?.opt == 'a'); const maybe_opt = opts.next(); if (maybe_opt) { unreachable; } else |err| { try expect(err == Error.InvalidOption); try expect(opts.optopt == 'z'); } } test "missing argument" { var argv = [_][*:0]const u8{ "getopt", "-az", }; var opts = getoptArgv(&argv, "az:"); // -a is ok try expect((try opts.next()).?.opt == 'a'); const maybe_opt = opts.next(); if (maybe_opt) { unreachable; } else |err| { try expect(err == Error.MissingArgument); try expect(opts.optopt == 'z'); } } test "positional args" { var argv = [_][*:0]const u8{ "getopt", "-abc10", "-d", "foo", "bar", }; const expected = [_]Option{ .{ .opt = 'a' }, .{ .opt = 'b' }, .{ .opt = 'c', .arg = "10", }, .{ .opt = 'd' }, }; var opts = getoptArgv(&argv, "abc:d"); var i: usize = 0; while (try opts.next()) |opt| : (i += 1) { try expect(opt.opt == expected[i].opt); if (opt.arg != null and expected[i].arg != null) { try expect(mem.eql(u8, opt.arg.?, expected[i].arg.?)); } else { try expect(opt.arg == null and expected[i].arg == null); } } try expect(mem.eql([*:0]const u8, opts.args().?, &[_][*:0]const u8{ "foo", "bar" })); } test "positional args with separator" { var argv = [_][*:0]const u8{ "getopt", "-ab", "--", "foo", "bar", }; const expected = [_]Option{ .{ .opt = 'a' }, .{ .opt = 'b' }, }; var opts = getoptArgv(&argv, "ab"); var i: usize = 0; while (try opts.next()) |opt| : (i += 1) { try expect(opt.opt == expected[i].opt); if (opt.arg != null and expected[i].arg != null) { try expect(mem.eql(u8, opt.arg.?, expected[i].arg.?)); } else { try expect(opt.arg == null and expected[i].arg == null); } } try expect(mem.eql([*:0]const u8, opts.args().?, &[_][*:0]const u8{ "foo", "bar" })); }
getopt.zig
const std = @import("std"); pub const csi = "\x1b["; /// Sequence to set foreground color using 256 colors table pub const fg_256 = "38;5;"; /// Sequence to set foreground color using 256 colors table pub const bg_256 = "48;5;"; /// Sequence to set foreground color using 256 colors table pub const fg_rgb = "38;2;"; /// Sequence to set foreground color using 256 colors table pub const bg_rgb = "48;2;"; /// Sequence to reset color and style pub const reset_all = "0m"; /// Sequence to clear from cursor until end of screen pub const clear_screen_from_cursor = "0J"; /// Sequence to clear from beginning to cursor. pub const clear_screen_to_cursor = "1J"; /// Sequence to clear all screen pub const clear_all = "2J"; /// Clear from cursor to end of line pub const clear_line_from_cursor = "0K"; /// Clear start of line to the cursor pub const clear_line_to_cursor = "1K"; /// Clear entire line pub const clear_line = "2K"; /// Returns the ANSI sequence as a []const u8 pub const reset = "0m"; /// Returns the ANSI sequence to set bold mode pub const style_bold = "1m"; pub const style_no_bold = "22m"; /// Returnstyle_s the ANSI sequence to set dim mode pub const style_dim = "2m"; pub const style_no_dim = "22m"; /// Returnstyle_s the ANSI sequence to set italic mode pub const style_italic = "3m"; pub const style_no_italic = "23m"; /// Returnstyle_s the ANSI sequence to set underline mode pub const style_underline = "4m"; pub const style_no_underline = "24m"; /// Returnstyle_s the ANSI sequence to set blinking mode pub const style_blinking = "5m"; pub const style_no_blinking = "25m"; /// Returnstyle_s the ANSI sequence to set reverse mode pub const style_reverse = "7m"; pub const style_no_reverse = "27m"; /// Returnstyle_s the ANSI sequence to set hidden/invisible mode pub const style_invisible = "8m"; pub const style_no_invisible = "28m"; /// Returnstyle_s the ANSI sequence to set strikethrough mode pub const style_strikethrough = "9m"; pub const style_no_strikethrough = "29m"; pub inline fn comptimeCsi(comptime fmt: []const u8, args: anytype) []const u8 { const str = "\x1b[" ++ fmt; return std.fmt.comptimePrint(str, args); }
src/utils.zig
const std = @import("std"); const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; const Tag = std.meta.Tag; const Foo = union { float: f64, int: i32, }; test "basic unions" { var foo = Foo{ .int = 1 }; try expect(foo.int == 1); foo = Foo{ .float = 12.34 }; try expect(foo.float == 12.34); } test "init union with runtime value" { var foo: Foo = undefined; setFloat(&foo, 12.34); try expect(foo.float == 12.34); setInt(&foo, 42); try expect(foo.int == 42); } fn setFloat(foo: *Foo, x: f64) void { foo.* = Foo{ .float = x }; } fn setInt(foo: *Foo, x: i32) void { foo.* = Foo{ .int = x }; } test "comptime union field access" { comptime { var foo = Foo{ .int = 0 }; try expect(foo.int == 0); foo = Foo{ .float = 42.42 }; try expect(foo.float == 42.42); } } const FooExtern = extern union { float: f64, int: i32, }; test "basic extern unions" { var foo = FooExtern{ .int = 1 }; try expect(foo.int == 1); foo.float = 12.34; try expect(foo.float == 12.34); } const ExternPtrOrInt = extern union { ptr: *u8, int: u64, }; test "extern union size" { comptime try expect(@sizeOf(ExternPtrOrInt) == 8); } test "0-sized extern union definition" { const U = extern union { a: void, const f = 1; }; try expect(U.f == 1); } const Value = union(enum) { Int: u64, Array: [9]u8, }; const Agg = struct { val1: Value, val2: Value, }; const v1 = Value{ .Int = 1234 }; const v2 = Value{ .Array = [_]u8{3} ** 9 }; const err = @as(anyerror!Agg, Agg{ .val1 = v1, .val2 = v2, }); const array = [_]Value{ v1, v2, v1, v2 }; test "unions embedded in aggregate types" { switch (array[1]) { Value.Array => |arr| try expect(arr[4] == 3), else => unreachable, } switch ((err catch unreachable).val1) { Value.Int => |x| try expect(x == 1234), else => unreachable, } } test "access a member of tagged union with conflicting enum tag name" { const Bar = union(enum) { A: A, B: B, const A = u8; const B = void; }; comptime try expect(Bar.A == u8); } test "constant tagged union with payload" { var empty = TaggedUnionWithPayload{ .Empty = {} }; var full = TaggedUnionWithPayload{ .Full = 13 }; shouldBeEmpty(empty); shouldBeNotEmpty(full); } fn shouldBeEmpty(x: TaggedUnionWithPayload) void { switch (x) { TaggedUnionWithPayload.Empty => {}, else => unreachable, } } fn shouldBeNotEmpty(x: TaggedUnionWithPayload) void { switch (x) { TaggedUnionWithPayload.Empty => unreachable, else => {}, } } const TaggedUnionWithPayload = union(enum) { Empty: void, Full: i32, }; test "union alignment" { comptime { try expect(@alignOf(AlignTestTaggedUnion) >= @alignOf([9]u8)); try expect(@alignOf(AlignTestTaggedUnion) >= @alignOf(u64)); } } const AlignTestTaggedUnion = union(enum) { A: [9]u8, B: u64, }; const Letter = enum { A, B, C }; const Payload = union(Letter) { A: i32, B: f64, C: bool, }; test "union with specified enum tag" { try doTest(); comptime try doTest(); } test "packed union generates correctly aligned LLVM type" { const U = packed union { f1: fn () error{TestUnexpectedResult}!void, f2: u32, }; var foo = [_]U{ U{ .f1 = doTest }, U{ .f2 = 0 }, }; try foo[0].f1(); } fn doTest() error{TestUnexpectedResult}!void { try expect((try bar(Payload{ .A = 1234 })) == -10); } fn bar(value: Payload) error{TestUnexpectedResult}!i32 { try expect(@as(Letter, value) == Letter.A); return switch (value) { Payload.A => |x| return x - 1244, Payload.B => |x| if (x == 12.34) @as(i32, 20) else 21, Payload.C => |x| if (x) @as(i32, 30) else 31, }; } fn testComparison() !void { var x = Payload{ .A = 42 }; try expect(x == .A); try expect(x != .B); try expect(x != .C); try expect((x == .B) == false); try expect((x == .C) == false); try expect((x != .A) == false); } test "comparison between union and enum literal" { try testComparison(); comptime try testComparison(); } const TheTag = enum { A, B, C }; const TheUnion = union(TheTag) { A: i32, B: i32, C: i32, }; test "cast union to tag type of union" { try testCastUnionToTag(); comptime try testCastUnionToTag(); } fn testCastUnionToTag() !void { var u = TheUnion{ .B = 1234 }; try expect(@as(TheTag, u) == TheTag.B); } test "union field access gives the enum values" { try expect(TheUnion.A == TheTag.A); try expect(TheUnion.B == TheTag.B); try expect(TheUnion.C == TheTag.C); } test "cast tag type of union to union" { var x: Value2 = Letter2.B; try expect(@as(Letter2, x) == Letter2.B); } const Letter2 = enum { A, B, C }; const Value2 = union(Letter2) { A: i32, B, C, }; test "implicit cast union to its tag type" { var x: Value2 = Letter2.B; try expect(x == Letter2.B); try giveMeLetterB(x); } fn giveMeLetterB(x: Letter2) !void { try expect(x == Value2.B); } // TODO it looks like this test intended to test packed unions, but this is not a packed // union. go through git history and find out what happened. pub const PackThis = union(enum) { Invalid: bool, StringLiteral: u2, }; test "constant packed union" { try testConstPackedUnion(&[_]PackThis{PackThis{ .StringLiteral = 1 }}); } fn testConstPackedUnion(expected_tokens: []const PackThis) !void { try expect(expected_tokens[0].StringLiteral == 1); } const MultipleChoice = union(enum(u32)) { A = 20, B = 40, C = 60, D = 1000, }; test "simple union(enum(u32))" { var x = MultipleChoice.C; try expect(x == MultipleChoice.C); try expect(@enumToInt(@as(Tag(MultipleChoice), x)) == 60); } const PackedPtrOrInt = packed union { ptr: *u8, int: u64, }; test "packed union size" { comptime try expect(@sizeOf(PackedPtrOrInt) == 8); } const ZeroBits = union { OnlyField: void, }; test "union with only 1 field which is void should be zero bits" { comptime try expect(@sizeOf(ZeroBits) == 0); } test "tagged union initialization with runtime void" { try expect(testTaggedUnionInit({})); } const TaggedUnionWithAVoid = union(enum) { A, B: i32, }; fn testTaggedUnionInit(x: anytype) bool { const y = TaggedUnionWithAVoid{ .A = x }; return @as(Tag(TaggedUnionWithAVoid), y) == TaggedUnionWithAVoid.A; } pub const UnionEnumNoPayloads = union(enum) { A, B }; test "tagged union with no payloads" { const a = UnionEnumNoPayloads{ .B = {} }; switch (a) { Tag(UnionEnumNoPayloads).A => @panic("wrong"), Tag(UnionEnumNoPayloads).B => {}, } } test "union with only 1 field casted to its enum type" { const Literal = union(enum) { Number: f64, Bool: bool, }; const Expr = union(enum) { Literal: Literal, }; var e = Expr{ .Literal = Literal{ .Bool = true } }; const ExprTag = Tag(Expr); comptime try expect(Tag(ExprTag) == u0); var t = @as(ExprTag, e); try expect(t == Expr.Literal); } test "union with one member defaults to u0 tag type" { const U0 = union(enum) { X: u32, }; comptime try expect(Tag(Tag(U0)) == u0); } const Foo1 = union(enum) { f: struct { x: usize, }, }; var glbl: Foo1 = undefined; test "global union with single field is correctly initialized" { glbl = Foo1{ .f = @typeInfo(Foo1).Union.fields[0].field_type{ .x = 123 }, }; try expect(glbl.f.x == 123); } pub const FooUnion = union(enum) { U0: usize, U1: u8, }; var glbl_array: [2]FooUnion = undefined; test "initialize global array of union" { glbl_array[1] = FooUnion{ .U1 = 2 }; glbl_array[0] = FooUnion{ .U0 = 1 }; try expect(glbl_array[0].U0 == 1); try expect(glbl_array[1].U1 == 2); } test "update the tag value for zero-sized unions" { const S = union(enum) { U0: void, U1: void, }; var x = S{ .U0 = {} }; try expect(x == .U0); x = S{ .U1 = {} }; try expect(x == .U1); } test "union initializer generates padding only if needed" { const U = union(enum) { A: u24, }; var v = U{ .A = 532 }; try expect(v.A == 532); } test "runtime tag name with single field" { const U = union(enum) { A: i32, }; var v = U{ .A = 42 }; try expect(std.mem.eql(u8, @tagName(v), "A")); } test "method call on an empty union" { const S = struct { const MyUnion = union(MyUnionTag) { pub const MyUnionTag = enum { X1, X2 }; X1: [0]u8, X2: [0]u8, pub fn useIt(self: *@This()) bool { _ = self; return true; } }; fn doTheTest() !void { var u = MyUnion{ .X1 = [0]u8{} }; try expect(u.useIt()); } }; try S.doTheTest(); comptime try S.doTheTest(); } const Point = struct { x: u64, y: u64, }; const TaggedFoo = union(enum) { One: i32, Two: Point, Three: void, }; const FooNoVoid = union(enum) { One: i32, Two: Point, }; const Baz = enum { A, B, C, D }; test "tagged union type" { const foo1 = TaggedFoo{ .One = 13 }; const foo2 = TaggedFoo{ .Two = Point{ .x = 1234, .y = 5678, }, }; try expect(foo1.One == 13); try expect(foo2.Two.x == 1234 and foo2.Two.y == 5678); const baz = Baz.B; try expect(baz == Baz.B); try expect(@typeInfo(TaggedFoo).Union.fields.len == 3); try expect(@typeInfo(Baz).Enum.fields.len == 4); try expect(@sizeOf(TaggedFoo) == @sizeOf(FooNoVoid)); try expect(@sizeOf(Baz) == 1); } test "tagged union as return value" { switch (returnAnInt(13)) { TaggedFoo.One => |value| try expect(value == 13), else => unreachable, } } fn returnAnInt(x: i32) TaggedFoo { return TaggedFoo{ .One = x }; } test "tagged union with all void fields but a meaningful tag" { const S = struct { const B = union(enum) { c: C, None, }; const A = struct { b: B, }; const C = struct {}; fn doTheTest() !void { var a: A = A{ .b = B{ .c = C{} } }; try expect(@as(Tag(B), a.b) == Tag(B).c); a = A{ .b = B.None }; try expect(@as(Tag(B), a.b) == Tag(B).None); } }; try S.doTheTest(); // TODO enable the test at comptime too //comptime try S.doTheTest(); }
test/behavior/union.zig
const kernel = @import("../../kernel.zig"); const Physical = kernel.arch.Physical; const TODO = kernel.TODO; const log = kernel.log.scoped(.memory_map); var available: BootloaderMemoryRegionGroup = undefined; var reserved: BootloaderMemoryRegionGroup = undefined; pub const BootloaderMemoryRegionGroup = struct { array: [64]RegionDescriptor, count: u64, }; const RegionDescriptor = kernel.arch.Physical.Region.Descriptor; pub const MemoryMap = struct { available: []RegionDescriptor, reserved: []RegionDescriptor, }; pub fn get() MemoryMap { const memory_properties = kernel.arch.device_tree.find_property("memory", "reg", .start, null, null) orelse @panic("not found"); var bytes_processed: u64 = 0; var memory_map: MemoryMap = undefined; memory_map.available.ptr = &available.array; memory_map.available.len = 0; memory_map.reserved.ptr = &reserved.array; memory_map.reserved.len = 0; while (bytes_processed < memory_properties.value.len) { memory_map.available.len += 1; var region = &memory_map.available[memory_map.available.len - 1]; region.address = kernel.arch.dt_read_int(u64, memory_properties.value[bytes_processed..]); bytes_processed += @sizeOf(u64); const region_size = kernel.arch.dt_read_int(u64, memory_properties.value[bytes_processed..]); kernel.assert(@src(), region_size % kernel.arch.page_size == 0); region.page_count = region_size / kernel.arch.page_size; bytes_processed += @sizeOf(u64); } if (kernel.arch.device_tree.find_node("reserved-memory", .exact)) |find_result| { var parser = find_result.parser; while (parser.get_subnode()) |subnode_name| { log.debug("Getting subnode: {s}", .{subnode_name}); if (parser.find_property_in_current_node("reg")) |reserved_memory_prop| { bytes_processed = 0; while (bytes_processed < reserved_memory_prop.value.len) { memory_map.reserved.len += 1; var region = &memory_map.reserved[memory_map.reserved.len - 1]; region.address = kernel.arch.dt_read_int(u64, reserved_memory_prop.value[bytes_processed..]); bytes_processed += @sizeOf(u64); const region_size = kernel.arch.dt_read_int(u64, reserved_memory_prop.value[bytes_processed..]); kernel.assert(@src(), region_size % kernel.arch.page_size == 0); region.page_count = region_size / kernel.arch.page_size; bytes_processed += @sizeOf(u64); } } } } log.debug("Regions:", .{}); for (memory_map.available) |region, i| { log.debug("[{}] (0x{x}, {})", .{ i, region.address, region.page_count }); } log.debug("Reserved regions:", .{}); for (memory_map.reserved) |region, i| { log.debug("[{}] (0x{x}, {})", .{ i, region.address, region.page_count }); } return memory_map; }
src/kernel/arch/riscv64/memory_map.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const gzip = std.compress.gzip; const Fs = @import("Fs.zig"); const DatasetAttributes = @import("dataset_attributes.zig").DatasetAttributes; const CompressionType = @import("dataset_attributes.zig").CompressionType; const util = @import("util.zig"); const c = @cImport({ @cDefine("LZ4LIB_API", {}); @cInclude("lz4.h"); }); const lz4Magic = [_]u8{ 0x4C, 0x5A, 0x34, 0x42, 0x6C, 0x6F, 0x63, 0x6B, 0x26 }; // Lz4Block& pub fn Datablock(comptime SourceType: type) type { return struct { allocator: Allocator, source: ?SourceType, stream: std.io.StreamSource, attributes: ?DatasetAttributes(SourceType), datasetPath: []const u8, size: []u32, elementsNo: u32, gridPosition: []i64, len: usize, mode: u2, const Self = @This(); pub fn init( a: Allocator, source: ?SourceType, datasetPath: []const u8, gridPosition: []i64, attributes: ?DatasetAttributes(SourceType), ) !Self { var d_block = Self{ .allocator = a, .source = source, .stream = if (source) |s| blk: { switch (SourceType) { std.fs.File => break :blk std.io.StreamSource{ .file = s }, []u8 => break :blk std.io.StreamSource{ .buffer = std.io.fixedBufferStream(s) }, []const u8 => break :blk std.io.StreamSource{ .const_buffer = std.io.fixedBufferStream(s) }, else => unreachable, } } else undefined, .attributes = attributes, .datasetPath = datasetPath, .gridPosition = gridPosition, .size = &[_]u32{}, .elementsNo = undefined, .len = 0, .mode = undefined, }; if (source) |_| { try d_block.initChunk(); } return d_block; } pub fn deinit(self: *Self) void { switch (SourceType) { std.fs.File => self.source.?.close(), []u8 => { if (self.source) |s| self.allocator.free(s); }, []const u8 => {}, else => unreachable, } if (self.size.len > 0) { self.allocator.free(self.size); } } pub const Writer = std.io.Writer(*Self, anyerror, write); pub fn write(self: *Self, bytes: []const u8) !usize { // if source is slice, set up an arraylist to have a writer. var array_list: std.ArrayList(u8) = undefined; var w = switch (SourceType) { std.fs.File, []const u8 => self.stream.writer(), []u8 => blk: { array_list = std.ArrayList(u8).init(self.allocator); break :blk array_list.writer(); }, else => unreachable, }; defer { switch (SourceType) { std.fs.File, []const u8 => {}, []u8 => { self.source = array_list.toOwnedSlice(); self.stream = std.io.StreamSource{ .buffer = std.io.fixedBufferStream(self.source.?) }; }, else => unreachable, } } // write the header var sizes = self.attributes.?.blockSize; var dims = self.attributes.?.dimensions; try w.writeIntBig(u16, @intCast(u16, self.mode)); if (self.mode < 2) { try w.writeIntBig(u16, @intCast(u16, sizes.len)); for (sizes) |s| { try w.writeIntBig(u32, @intCast(u32, s)); } if (self.mode == 1) { try w.writeIntBig(u32, totalElements(u64, dims)); } } else { try w.writeIntBig(u32, totalElements(u64, dims)); } // now the data if (self.attributes) |attr| { switch (attr.compression.type) { CompressionType.raw => { var n = try w.write(bytes); self.len = n; return n; }, CompressionType.gzip => unreachable, CompressionType.bzip2 => unreachable, CompressionType.blosc => unreachable, CompressionType.lz4 => { // TODO: use lz4 compress bound func to comput dest size var dest_size_c = c.LZ4_compressBound(@intCast(c_int, bytes.len)); var dest_size = @intCast(usize, dest_size_c); var dest_buf = try self.allocator.alloc(u8, dest_size); defer self.allocator.free(dest_buf); var comp_c = c.LZ4_compress_default( bytes.ptr, dest_buf.ptr, @intCast(c_int, bytes.len), dest_size_c, ); // if compression failed use the original length var comp: i32 = if (comp_c == 0) @intCast(i32, bytes.len) else @intCast(i32, comp_c); // 21 bytes lz4 header: // 9 bytes: magic + token (Lz4Block&) // 4 bytes: compressed length // 4 bytes: decompressed length // 4 bytes: checksum // // // TODO: group in a buffer and write once _ = try w.write(&lz4Magic); _ = try w.writeIntLittle(i32, comp); _ = try w.writeIntLittle(i32, @intCast(i32, bytes.len)); _ = try w.writeIntLittle(i32, 0x0000); // TODO compute checksum var comp_buf = dest_buf[0..@intCast(usize, comp)]; _ = try w.write(comp_buf); // signal end of lz4 block _ = try w.write(&lz4Magic); _ = try w.writeIntLittle(i32, comp); _ = try w.writeIntLittle(i32, 0x0000); _ = try w.writeIntLittle(i32, 0x0000); // TODO compute checksum var compr_len = @intCast(usize, comp); if (compr_len <= bytes.len) { self.len = compr_len; } else { self.len = bytes.len; } return compr_len; }, CompressionType.xz => unreachable, } } else return @as(usize, 0); } pub fn writer(self: *Self, mode: u2) Writer { self.mode = mode; return .{ .context = self }; } pub const Reader = std.io.Reader(*Self, anyerror, read); pub fn read(self: *Self, buffer: []u8) !usize { if (self.attributes) |attr| { switch (attr.compression.type) { CompressionType.raw => { return self.stream.read(buffer); }, CompressionType.gzip => { var gzip_reader = try gzip.gzipStream(self.allocator, self.stream.reader()); return gzip_reader.read(buffer); }, CompressionType.bzip2 => unreachable, CompressionType.blosc => unreachable, CompressionType.lz4 => { var current_byte: usize = 0; var decompressed: c_int = 0; while (true) { // each lz4 block is preceeded by // 'Lz4Block' (8 bytes) + 1 byte token var s = self.seeker(); try s.seekBy(9); var r = self.stream.reader(); // compressedLength(4 bytes) // decompressedLength(4 bytes) // checksum 4 bytes var comp_size = try r.readIntLittle(i32); var decomp_size = try r.readIntLittle(i32); // var checksum = try r.readIntLittle(i32); try s.seekBy(4); if (decomp_size == 0) { break; } var comp_buf = try self.allocator.alloc(u8, @intCast(usize, comp_size)); defer self.allocator.free(comp_buf); _ = try r.read(comp_buf); var res = c.LZ4_decompress_safe( comp_buf.ptr, buffer.ptr + current_byte, @intCast(c_int, comp_size), @intCast(c_int, decomp_size), ); if (res < 0) { return error.LZ4DecompressionError; } decompressed += res; current_byte += @intCast(usize, decomp_size); } return @intCast(usize, decompressed); }, CompressionType.xz => unreachable, } } else return @as(usize, 0); } pub fn reader(self: *Self) Reader { return .{ .context = self }; } pub const SeekableStream = std.io.SeekableStream( *Self, anyerror, anyerror, seekTo, seekBy, getPos, getEndPos, ); pub fn seekTo(self: *Self, offset: u64) !void { return self.stream.seekTo(offset); } pub fn seekBy(self: *Self, offset: i64) !void { return self.stream.seekBy(offset); } pub fn getPos(self: *Self) !u64 { return self.stream.getPos(); } pub fn getEndPos(self: *Self) !u64 { return self.stream.getEndPos(); } pub fn seeker(self: *Self) SeekableStream { return .{ .context = self }; } fn initChunk(self: *Self) !void { // early return in case the file is empty switch (SourceType) { []const u8, std.fs.File => { var size = try self.seeker().getEndPos(); if (size == 0) return; }, []u8 => { if (self.source.?.len == 0) return; }, else => unreachable, } var r = self.stream.reader(); var mode = try r.readIntBig(u16); var block_size: []u32 = undefined; var elements_no: u32 = undefined; // The mode defines the content of the header of the datablock: // // - 0: This is the default mode, in which the encoded mode is followed by // the number of dimensions (uint16 big endian) and the size of each // dimension (uint32 big endian for each dimension). // - 1: The encoded mode is followed by the number of dimensions (uint16 big endian), // the size of each dimension (uint32 big endian for each dimension), and // finally the total number of elements in the datablock (uint32 big endian). // - 2: The encoded mode is only followed by the total number of elements in the // datablock (uint32 big endian). This mode is not documented on the original // repository, but from the java implementation we can see that this mode is // used for data of type OBJECT. if (mode < 2) { var dim_no = try r.readIntBig(u16); block_size = try self.allocator.alloc(u32, dim_no); var i: u16 = 0; while (i < dim_no) : (i += 1) { var dim_size = try r.readIntBig(u32); block_size[i] = dim_size; } if (mode == 0) { elements_no = totalElements(u32, block_size); } else { // mode == 1 elements_no = try r.readIntBig(u32); } } else { // mode == 2 elements_no = try r.readIntBig(u32); } var len: u32 = 1; for (block_size) |dim_size| { if (dim_size > 0) { len *= dim_size; } } self.len = @intCast(usize, len); self.elementsNo = elements_no; self.size = block_size; } }; } test "raw file" { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = gpa.allocator(); comptime var buff_size = util.pathBufferSize(); var path_buffer: [buff_size]u8 = undefined; var full_path = try std.fs.realpath("testdata/lynx_raw", &path_buffer); var fs = try Fs.init(allocator, full_path); var fs_path = try std.fs.path.join(allocator, &[_][]const u8{ full_path, "data.n5/0/0/0/0/0/0/1" }); std.fs.deleteFileAbsolute(fs_path) catch {}; var d_attr = try fs.datasetAttributes("0/0"); var grid_position = [_]i64{ 0, 0, 0, 0, 1 }; var d_block = try fs.getBlock("0/0", &grid_position, d_attr); var deadbeef = &[_]u8{ 0xDE, 0xAD, 0xBE, 0xEF }; _ = try d_block.writer(0).write(deadbeef); d_block.deinit(); d_block = try fs.getBlock("0/0", &grid_position, d_attr); var out_buf = try allocator.alloc(u8, deadbeef.len); _ = try d_block.reader().read(out_buf); try std.testing.expect(std.mem.eql(u8, out_buf, deadbeef)); allocator.free(out_buf); d_block.deinit(); d_attr.deinit(); fs.deinit(); try std.fs.deleteFileAbsolute(fs_path); allocator.free(fs_path); try std.testing.expect(!gpa.deinit()); } test "LZ4 file" { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = gpa.allocator(); comptime var buff_size = util.pathBufferSize(); var path_buffer: [buff_size]u8 = undefined; var full_path = try std.fs.realpath("testdata/lynx_lz4", &path_buffer); var fs = try Fs.init(allocator, full_path); var fs_path = try std.fs.path.join(allocator, &[_][]const u8{ full_path, "data.n5/0/0/0/0/0/0/1" }); std.fs.deleteFileAbsolute(fs_path) catch {}; var d_attr = try fs.datasetAttributes("0/0"); var grid_position = [_]i64{ 0, 0, 0, 0, 1 }; var d_block = try fs.getBlock("0/0", &grid_position, d_attr); var deadbeef = &[_]u8{ 0xDE, 0xAD, 0xBE, 0xEF }; _ = try d_block.writer(0).write(deadbeef); d_block.deinit(); d_block = try fs.getBlock("0/0", &grid_position, d_attr); var out_buf = try allocator.alloc(u8, deadbeef.len); _ = try d_block.reader().read(out_buf); try std.testing.expect(std.mem.eql(u8, out_buf, deadbeef)); allocator.free(out_buf); d_block.deinit(); d_attr.deinit(); fs.deinit(); try std.fs.deleteFileAbsolute(fs_path); allocator.free(fs_path); try std.testing.expect(!gpa.deinit()); } test "raw bytes" { var attr = "{\"dataType\":\"uint8\",\"compression\":{\"type\":\"raw\"},\"blockSize\":[512,512,1,1,1],\"dimensions\":[1920,1080,3,1,1]}"; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var allocator = gpa.allocator(); var d_attr = try DatasetAttributes([]u8).init(allocator, attr); var d_block = try Datablock([]u8).init(allocator, null, &.{}, &.{}, d_attr); var deadbeef = &[_]u8{ 0xDE, 0xAD, 0xBE, 0xEF }; _ = try d_block.writer(0).write(deadbeef); var out_buf = try allocator.alloc(u8, d_block.len); try d_block.initChunk(); _ = try d_block.reader().read(out_buf); try std.testing.expect(std.mem.eql(u8, out_buf, deadbeef)); allocator.free(out_buf); d_block.deinit(); d_attr.deinit(); try std.testing.expect(!gpa.deinit()); } test "LZ4 bytes" { var attr = "{\"dataType\":\"uint8\",\"compression\":{\"type\":\"lz4\",\"blockSize\":65536},\"blockSize\":[512,512,1,1,1],\"dimensions\":[1920,1080,3,1,1]}"; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var allocator = gpa.allocator(); var d_attr = try DatasetAttributes([]u8).init(allocator, attr); var d_block = try Datablock([]u8).init(allocator, null, &.{}, &.{}, d_attr); var deadbeef = &[_]u8{ 0xDE, 0xAD, 0xBE, 0xEF }; _ = try d_block.writer(0).write(deadbeef); var out_buf = try allocator.alloc(u8, d_block.len); try d_block.initChunk(); _ = try d_block.reader().read(out_buf); std.debug.print("{s}\n", .{std.fmt.fmtSliceHexLower(out_buf)}); try std.testing.expect(std.mem.eql(u8, out_buf, deadbeef)); allocator.free(out_buf); d_block.deinit(); d_attr.deinit(); try std.testing.expect(!gpa.deinit()); } fn totalElements(comptime T: type, dimensions: []T) u32 { if (dimensions.len == 0) return 0; var n: u32 = 1; for (dimensions) |d| { n *= @intCast(u32, d); } return n; } test "totalElements" { var dim0 = [_]u32{}; var dim1 = [_]u32{ 1, 2, 3 }; var tests = [_]struct { dimensions: []u32, expected: u32, }{ .{ .dimensions = &dim1, .expected = 6, }, .{ .dimensions = &dim0, .expected = 0, }, }; for (tests) |t| { var n = totalElements(u32, t.dimensions); try std.testing.expect(n == t.expected); } }
src/datablock.zig
const RuleSet = @import("./rules.zig").RuleSet; const Rule = @import("./rules.zig").Rule; const Attr = @import("./rules.zig").Attr; pub const rules = RuleSet{ .rules = &[_]Rule{ Rule{ .kind = 0, // drab tan .attrs = &[_]Attr{ Attr{ .kind = 1, .n = 4 }, // clear gold }, }, Rule{ .kind = 1, // clear gold .attrs = &[_]Attr{ Attr{ .kind = 92, .n = 1 }, // muted tomato Attr{ .kind = 116, .n = 3 }, // dull cyan Attr{ .kind = 410, .n = 3 }, // plaid brown }, }, Rule{ .kind = 2, // vibrant lime .attrs = &[_]Attr{ Attr{ .kind = 3, .n = 3 }, // faded gold Attr{ .kind = 4, .n = 3 }, // plaid aqua Attr{ .kind = 5, .n = 2 }, // clear black }, }, Rule{ .kind = 3, // faded gold .attrs = &[_]Attr{ Attr{ .kind = 42, .n = 4 }, // dull black }, }, Rule{ .kind = 4, // plaid aqua .attrs = &[_]Attr{ Attr{ .kind = 219, .n = 4 }, // faded turquoise Attr{ .kind = 400, .n = 3 }, // dark cyan Attr{ .kind = 435, .n = 4 }, // striped silver Attr{ .kind = 503, .n = 4 }, // shiny beige }, }, Rule{ .kind = 5, // clear black .attrs = &[_]Attr{ Attr{ .kind = 41, .n = 1 }, // plaid tomato Attr{ .kind = 243, .n = 2 }, // dull magenta Attr{ .kind = 503, .n = 5 }, // shiny beige }, }, Rule{ .kind = 6, // pale lime .attrs = &[_]Attr{ Attr{ .kind = 7, .n = 1 }, // dim salmon Attr{ .kind = 8, .n = 5 }, // faded salmon Attr{ .kind = 9, .n = 1 }, // dim turquoise }, }, Rule{ .kind = 7, // dim salmon .attrs = &[_]Attr{ Attr{ .kind = 67, .n = 4 }, // drab lime Attr{ .kind = 117, .n = 2 }, // drab black Attr{ .kind = 387, .n = 4 }, // light green }, }, Rule{ .kind = 8, // faded salmon .attrs = &[_]Attr{ Attr{ .kind = 87, .n = 5 }, // posh brown }, }, Rule{ .kind = 9, // dim turquoise .attrs = &[_]Attr{ Attr{ .kind = 42, .n = 2 }, // dull black Attr{ .kind = 305, .n = 3 }, // dull fuchsia }, }, Rule{ .kind = 10, // dull gray .attrs = &[_]Attr{ Attr{ .kind = 11, .n = 1 }, // striped gold Attr{ .kind = 12, .n = 1 }, // vibrant yellow }, }, Rule{ .kind = 11, // striped gold .attrs = &[_]Attr{ Attr{ .kind = 37, .n = 5 }, // vibrant cyan Attr{ .kind = 100, .n = 3 }, // clear blue Attr{ .kind = 110, .n = 1 }, // dull lime }, }, Rule{ .kind = 12, // vibrant yellow .attrs = &[_]Attr{ Attr{ .kind = 127, .n = 5 }, // dark red Attr{ .kind = 182, .n = 4 }, // shiny gold Attr{ .kind = 214, .n = 3 }, // light silver Attr{ .kind = 237, .n = 2 }, // faded yellow }, }, Rule{ .kind = 13, // light fuchsia .attrs = &[_]Attr{ Attr{ .kind = 14, .n = 4 }, // light lavender Attr{ .kind = 15, .n = 5 }, // faded olive Attr{ .kind = 16, .n = 4 }, // plaid cyan Attr{ .kind = 17, .n = 1 }, // striped tomato }, }, Rule{ .kind = 14, // light lavender .attrs = &[_]Attr{ Attr{ .kind = 75, .n = 3 }, // dark maroon Attr{ .kind = 128, .n = 4 }, // shiny lime Attr{ .kind = 153, .n = 2 }, // bright maroon Attr{ .kind = 214, .n = 1 }, // light silver }, }, Rule{ .kind = 15, // faded olive .attrs = &[_]Attr{ Attr{ .kind = 32, .n = 2 }, // dotted silver Attr{ .kind = 33, .n = 4 }, // clear gray }, }, Rule{ .kind = 16, // plaid cyan .attrs = &[_]Attr{ Attr{ .kind = 413, .n = 3 }, // muted yellow }, }, Rule{ .kind = 17, // striped tomato .attrs = &[_]Attr{ Attr{ .kind = 166, .n = 2 }, // drab bronze Attr{ .kind = 168, .n = 2 }, // drab chartreuse Attr{ .kind = 250, .n = 5 }, // posh lavender Attr{ .kind = 360, .n = 2 }, // dark teal }, }, Rule{ .kind = 18, // drab gold .attrs = &[_]Attr{ Attr{ .kind = 19, .n = 1 }, // clear teal }, }, Rule{ .kind = 19, // clear teal .attrs = &[_]Attr{ Attr{ .kind = 125, .n = 2 }, // light turquoise Attr{ .kind = 235, .n = 1 }, // striped white }, }, Rule{ .kind = 20, // dim red .attrs = &[_]Attr{ Attr{ .kind = 21, .n = 2 }, // dull teal }, }, Rule{ .kind = 21, // dull teal .attrs = &[_]Attr{ Attr{ .kind = 340, .n = 4 }, // dotted gold Attr{ .kind = 463, .n = 4 }, // faded maroon }, }, Rule{ .kind = 22, // striped orange .attrs = &[_]Attr{ Attr{ .kind = 23, .n = 1 }, // bright fuchsia Attr{ .kind = 24, .n = 3 }, // plaid chartreuse Attr{ .kind = 25, .n = 4 }, // dark silver Attr{ .kind = 26, .n = 5 }, // dim maroon }, }, Rule{ .kind = 23, // bright fuchsia .attrs = &[_]Attr{ Attr{ .kind = 143, .n = 5 }, // vibrant bronze Attr{ .kind = 156, .n = 3 }, // shiny chartreuse }, }, Rule{ .kind = 24, // plaid chartreuse .attrs = &[_]Attr{ Attr{ .kind = 61, .n = 1 }, // wavy yellow Attr{ .kind = 151, .n = 3 }, // mirrored olive }, }, Rule{ .kind = 25, // dark silver .attrs = &[_]Attr{ Attr{ .kind = 12, .n = 3 }, // vibrant yellow Attr{ .kind = 134, .n = 2 }, // posh gray Attr{ .kind = 182, .n = 2 }, // shiny gold Attr{ .kind = 270, .n = 4 }, // clear cyan }, }, Rule{ .kind = 26, // dim maroon .attrs = &[_]Attr{ Attr{ .kind = 101, .n = 1 }, // mirrored fuchsia Attr{ .kind = 193, .n = 3 }, // pale salmon Attr{ .kind = 272, .n = 3 }, // dim coral Attr{ .kind = 325, .n = 4 }, // drab red }, }, Rule{ .kind = 27, // shiny violet .attrs = &[_]Attr{ Attr{ .kind = 28, .n = 1 }, // clear orange Attr{ .kind = 29, .n = 4 }, // muted olive Attr{ .kind = 30, .n = 4 }, // dark chartreuse Attr{ .kind = 31, .n = 4 }, // shiny indigo }, }, Rule{ .kind = 28, // clear orange .attrs = &[_]Attr{ Attr{ .kind = 116, .n = 3 }, // dull cyan Attr{ .kind = 250, .n = 1 }, // posh lavender Attr{ .kind = 267, .n = 5 }, // posh plum }, }, Rule{ .kind = 29, // muted olive .attrs = &[_]Attr{ Attr{ .kind = 87, .n = 1 }, // posh brown Attr{ .kind = 100, .n = 4 }, // clear blue Attr{ .kind = 141, .n = 2 }, // striped chartreuse Attr{ .kind = 250, .n = 1 }, // posh lavender }, }, Rule{ .kind = 30, // dark chartreuse .attrs = &[_]Attr{ Attr{ .kind = 14, .n = 1 }, // light lavender Attr{ .kind = 75, .n = 2 }, // dark maroon Attr{ .kind = 117, .n = 1 }, // drab black Attr{ .kind = 540, .n = 1 }, // dim blue }, }, Rule{ .kind = 31, // shiny indigo .attrs = &[_]Attr{ Attr{ .kind = 19, .n = 4 }, // clear teal Attr{ .kind = 252, .n = 4 }, // vibrant purple Attr{ .kind = 317, .n = 1 }, // pale teal Attr{ .kind = 410, .n = 3 }, // plaid brown }, }, Rule{ .kind = 32, // dotted silver .attrs = &[_]Attr{ Attr{ .kind = 40, .n = 3 }, // dull orange }, }, Rule{ .kind = 33, // clear gray .attrs = &[_]Attr{ Attr{ .kind = 116, .n = 2 }, // dull cyan Attr{ .kind = 140, .n = 3 }, // muted gold Attr{ .kind = 153, .n = 3 }, // bright maroon Attr{ .kind = 194, .n = 1 }, // bright red }, }, Rule{ .kind = 34, // dotted lime .attrs = &[_]Attr{ Attr{ .kind = 22, .n = 1 }, // striped orange Attr{ .kind = 35, .n = 1 }, // dark turquoise Attr{ .kind = 36, .n = 2 }, // shiny teal Attr{ .kind = 37, .n = 2 }, // vibrant cyan }, }, Rule{ .kind = 35, // dark turquoise .attrs = &[_]Attr{ Attr{ .kind = 59, .n = 1 }, // dotted violet }, }, Rule{ .kind = 36, // shiny teal .attrs = &[_]Attr{ Attr{ .kind = 140, .n = 4 }, // muted gold Attr{ .kind = 141, .n = 3 }, // striped chartreuse }, }, Rule{ .kind = 37, // vibrant cyan .attrs = &[_]Attr{}, }, Rule{ .kind = 38, // drab magenta .attrs = &[_]Attr{ Attr{ .kind = 39, .n = 4 }, // bright yellow Attr{ .kind = 40, .n = 5 }, // dull orange Attr{ .kind = 41, .n = 5 }, // plaid tomato }, }, Rule{ .kind = 39, // bright yellow .attrs = &[_]Attr{ Attr{ .kind = 177, .n = 5 }, // posh white Attr{ .kind = 390, .n = 1 }, // pale beige Attr{ .kind = 488, .n = 3 }, // dim lime }, }, Rule{ .kind = 40, // dull orange .attrs = &[_]Attr{ Attr{ .kind = 8, .n = 4 }, // faded salmon Attr{ .kind = 92, .n = 5 }, // muted tomato Attr{ .kind = 110, .n = 5 }, // dull lime Attr{ .kind = 344, .n = 5 }, // bright chartreuse }, }, Rule{ .kind = 41, // plaid tomato .attrs = &[_]Attr{ Attr{ .kind = 118, .n = 3 }, // dark green }, }, Rule{ .kind = 42, // dull black .attrs = &[_]Attr{ Attr{ .kind = 43, .n = 4 }, // light olive }, }, Rule{ .kind = 43, // light olive .attrs = &[_]Attr{ Attr{ .kind = 100, .n = 4 }, // clear blue Attr{ .kind = 186, .n = 1 }, // clear purple }, }, Rule{ .kind = 44, // posh turquoise .attrs = &[_]Attr{ Attr{ .kind = 45, .n = 1 }, // muted salmon Attr{ .kind = 46, .n = 1 }, // muted black Attr{ .kind = 47, .n = 5 }, // shiny turquoise }, }, Rule{ .kind = 45, // muted salmon .attrs = &[_]Attr{ Attr{ .kind = 357, .n = 1 }, // vibrant indigo }, }, Rule{ .kind = 46, // muted black .attrs = &[_]Attr{ Attr{ .kind = 24, .n = 5 }, // plaid chartreuse Attr{ .kind = 106, .n = 2 }, // wavy beige Attr{ .kind = 319, .n = 3 }, // light magenta }, }, Rule{ .kind = 47, // shiny turquoise .attrs = &[_]Attr{ Attr{ .kind = 236, .n = 4 }, // faded teal }, }, Rule{ .kind = 48, // muted purple .attrs = &[_]Attr{ Attr{ .kind = 49, .n = 5 }, // dotted red }, }, Rule{ .kind = 49, // dotted red .attrs = &[_]Attr{ Attr{ .kind = 29, .n = 5 }, // muted olive Attr{ .kind = 249, .n = 3 }, // bright tomato Attr{ .kind = 250, .n = 1 }, // posh lavender Attr{ .kind = 463, .n = 2 }, // faded maroon }, }, Rule{ .kind = 50, // striped black .attrs = &[_]Attr{ Attr{ .kind = 35, .n = 3 }, // dark turquoise Attr{ .kind = 51, .n = 1 }, // striped fuchsia Attr{ .kind = 52, .n = 4 }, // drab indigo }, }, Rule{ .kind = 51, // striped fuchsia .attrs = &[_]Attr{ Attr{ .kind = 116, .n = 5 }, // dull cyan Attr{ .kind = 129, .n = 2 }, // posh black Attr{ .kind = 143, .n = 2 }, // vibrant bronze Attr{ .kind = 250, .n = 4 }, // posh lavender }, }, Rule{ .kind = 52, // drab indigo .attrs = &[_]Attr{ Attr{ .kind = 97, .n = 4 }, // light beige }, }, Rule{ .kind = 53, // drab brown .attrs = &[_]Attr{ Attr{ .kind = 33, .n = 3 }, // clear gray Attr{ .kind = 54, .n = 1 }, // light gray Attr{ .kind = 55, .n = 1 }, // dull coral }, }, Rule{ .kind = 54, // light gray .attrs = &[_]Attr{ Attr{ .kind = 3, .n = 1 }, // faded gold Attr{ .kind = 78, .n = 3 }, // dark plum Attr{ .kind = 86, .n = 2 }, // vibrant silver }, }, Rule{ .kind = 55, // dull coral .attrs = &[_]Attr{ Attr{ .kind = 45, .n = 4 }, // muted salmon Attr{ .kind = 352, .n = 1 }, // bright gray Attr{ .kind = 438, .n = 1 }, // bright tan }, }, Rule{ .kind = 56, // pale purple .attrs = &[_]Attr{ Attr{ .kind = 57, .n = 5 }, // mirrored black Attr{ .kind = 58, .n = 4 }, // wavy crimson }, }, Rule{ .kind = 57, // mirrored black .attrs = &[_]Attr{ Attr{ .kind = 397, .n = 1 }, // mirrored turquoise Attr{ .kind = 482, .n = 3 }, // light white Attr{ .kind = 486, .n = 1 }, // muted magenta Attr{ .kind = 546, .n = 4 }, // bright plum }, }, Rule{ .kind = 58, // wavy crimson .attrs = &[_]Attr{ Attr{ .kind = 102, .n = 5 }, // muted beige Attr{ .kind = 103, .n = 2 }, // dark olive }, }, Rule{ .kind = 59, // dotted violet .attrs = &[_]Attr{ Attr{ .kind = 214, .n = 4 }, // light silver }, }, Rule{ .kind = 60, // clear lavender .attrs = &[_]Attr{ Attr{ .kind = 8, .n = 2 }, // faded salmon Attr{ .kind = 43, .n = 1 }, // light olive Attr{ .kind = 61, .n = 4 }, // wavy yellow Attr{ .kind = 62, .n = 4 }, // plaid red }, }, Rule{ .kind = 61, // wavy yellow .attrs = &[_]Attr{ Attr{ .kind = 237, .n = 5 }, // faded yellow Attr{ .kind = 250, .n = 2 }, // posh lavender }, }, Rule{ .kind = 62, // plaid red .attrs = &[_]Attr{ Attr{ .kind = 48, .n = 2 }, // muted purple Attr{ .kind = 126, .n = 3 }, // mirrored chartreuse Attr{ .kind = 217, .n = 2 }, // pale olive }, }, Rule{ .kind = 63, // bright coral .attrs = &[_]Attr{ Attr{ .kind = 64, .n = 2 }, // bright brown }, }, Rule{ .kind = 64, // bright brown .attrs = &[_]Attr{ Attr{ .kind = 132, .n = 4 }, // shiny orange Attr{ .kind = 235, .n = 3 }, // striped white }, }, Rule{ .kind = 65, // posh coral .attrs = &[_]Attr{ Attr{ .kind = 21, .n = 4 }, // dull teal Attr{ .kind = 66, .n = 4 }, // bright aqua }, }, Rule{ .kind = 66, // bright aqua .attrs = &[_]Attr{ Attr{ .kind = 59, .n = 5 }, // dotted violet Attr{ .kind = 194, .n = 4 }, // bright red Attr{ .kind = 438, .n = 5 }, // bright tan }, }, Rule{ .kind = 67, // drab lime .attrs = &[_]Attr{ Attr{ .kind = 68, .n = 4 }, // striped tan Attr{ .kind = 69, .n = 4 }, // muted violet }, }, Rule{ .kind = 68, // striped tan .attrs = &[_]Attr{ Attr{ .kind = 75, .n = 4 }, // dark maroon Attr{ .kind = 151, .n = 5 }, // mirrored olive }, }, Rule{ .kind = 69, // muted violet .attrs = &[_]Attr{ Attr{ .kind = 45, .n = 3 }, // muted salmon Attr{ .kind = 127, .n = 1 }, // dark red Attr{ .kind = 257, .n = 1 }, // clear tomato }, }, Rule{ .kind = 70, // striped brown .attrs = &[_]Attr{ Attr{ .kind = 28, .n = 4 }, // clear orange Attr{ .kind = 71, .n = 1 }, // dark lime }, }, Rule{ .kind = 71, // dark lime .attrs = &[_]Attr{ Attr{ .kind = 155, .n = 3 }, // wavy brown }, }, Rule{ .kind = 72, // wavy bronze .attrs = &[_]Attr{ Attr{ .kind = 65, .n = 2 }, // posh coral Attr{ .kind = 73, .n = 3 }, // mirrored silver }, }, Rule{ .kind = 73, // mirrored silver .attrs = &[_]Attr{ Attr{ .kind = 41, .n = 4 }, // plaid tomato Attr{ .kind = 142, .n = 5 }, // dotted salmon }, }, Rule{ .kind = 74, // dim black .attrs = &[_]Attr{ Attr{ .kind = 75, .n = 1 }, // dark maroon Attr{ .kind = 76, .n = 4 }, // muted lavender Attr{ .kind = 77, .n = 3 }, // bright cyan Attr{ .kind = 78, .n = 3 }, // dark plum }, }, Rule{ .kind = 75, // dark maroon .attrs = &[_]Attr{ Attr{ .kind = 141, .n = 2 }, // striped chartreuse Attr{ .kind = 153, .n = 5 }, // bright maroon Attr{ .kind = 249, .n = 2 }, // bright tomato }, }, Rule{ .kind = 76, // muted lavender .attrs = &[_]Attr{ Attr{ .kind = 87, .n = 5 }, // posh brown Attr{ .kind = 100, .n = 3 }, // clear blue Attr{ .kind = 144, .n = 3 }, // striped blue }, }, Rule{ .kind = 77, // bright cyan .attrs = &[_]Attr{ Attr{ .kind = 1, .n = 2 }, // clear gold Attr{ .kind = 64, .n = 3 }, // bright brown Attr{ .kind = 235, .n = 4 }, // striped white Attr{ .kind = 377, .n = 3 }, // dark yellow }, }, Rule{ .kind = 78, // dark plum .attrs = &[_]Attr{ Attr{ .kind = 92, .n = 2 }, // muted tomato Attr{ .kind = 141, .n = 4 }, // striped chartreuse Attr{ .kind = 182, .n = 3 }, // shiny gold }, }, Rule{ .kind = 79, // posh yellow .attrs = &[_]Attr{ Attr{ .kind = 41, .n = 3 }, // plaid tomato Attr{ .kind = 80, .n = 4 }, // dull plum Attr{ .kind = 81, .n = 5 }, // shiny blue }, }, Rule{ .kind = 80, // dull plum .attrs = &[_]Attr{ Attr{ .kind = 51, .n = 4 }, // striped fuchsia Attr{ .kind = 318, .n = 2 }, // light coral Attr{ .kind = 364, .n = 3 }, // dark violet Attr{ .kind = 403, .n = 4 }, // mirrored cyan }, }, Rule{ .kind = 81, // shiny blue .attrs = &[_]Attr{ Attr{ .kind = 237, .n = 4 }, // faded yellow Attr{ .kind = 438, .n = 5 }, // bright tan }, }, Rule{ .kind = 82, // pale violet .attrs = &[_]Attr{ Attr{ .kind = 62, .n = 1 }, // plaid red Attr{ .kind = 83, .n = 2 }, // posh fuchsia }, }, Rule{ .kind = 83, // posh fuchsia .attrs = &[_]Attr{ Attr{ .kind = 134, .n = 5 }, // posh gray }, }, Rule{ .kind = 84, // mirrored bronze .attrs = &[_]Attr{ Attr{ .kind = 85, .n = 4 }, // striped lavender }, }, Rule{ .kind = 85, // striped lavender .attrs = &[_]Attr{ Attr{ .kind = 33, .n = 4 }, // clear gray Attr{ .kind = 152, .n = 5 }, // drab beige Attr{ .kind = 251, .n = 1 }, // striped bronze Attr{ .kind = 254, .n = 3 }, // muted teal }, }, Rule{ .kind = 86, // vibrant silver .attrs = &[_]Attr{ Attr{ .kind = 32, .n = 4 }, // dotted silver Attr{ .kind = 87, .n = 4 }, // posh brown Attr{ .kind = 88, .n = 4 }, // clear indigo Attr{ .kind = 89, .n = 5 }, // drab lavender }, }, Rule{ .kind = 87, // posh brown .attrs = &[_]Attr{ Attr{ .kind = 116, .n = 3 }, // dull cyan }, }, Rule{ .kind = 88, // clear indigo .attrs = &[_]Attr{ Attr{ .kind = 177, .n = 1 }, // posh white Attr{ .kind = 197, .n = 5 }, // drab plum }, }, Rule{ .kind = 89, // drab lavender .attrs = &[_]Attr{ Attr{ .kind = 334, .n = 3 }, // pale maroon }, }, Rule{ .kind = 90, // dark brown .attrs = &[_]Attr{ Attr{ .kind = 69, .n = 1 }, // muted violet Attr{ .kind = 91, .n = 1 }, // mirrored plum Attr{ .kind = 92, .n = 3 }, // muted tomato }, }, Rule{ .kind = 91, // mirrored plum .attrs = &[_]Attr{ Attr{ .kind = 35, .n = 1 }, // dark turquoise Attr{ .kind = 289, .n = 1 }, // plaid black }, }, Rule{ .kind = 92, // muted tomato .attrs = &[_]Attr{ Attr{ .kind = 100, .n = 5 }, // clear blue Attr{ .kind = 101, .n = 5 }, // mirrored fuchsia }, }, Rule{ .kind = 93, // wavy green .attrs = &[_]Attr{ Attr{ .kind = 94, .n = 2 }, // posh bronze Attr{ .kind = 95, .n = 3 }, // dull purple Attr{ .kind = 96, .n = 1 }, // wavy red }, }, Rule{ .kind = 94, // posh bronze .attrs = &[_]Attr{ Attr{ .kind = 51, .n = 1 }, // striped fuchsia Attr{ .kind = 142, .n = 5 }, // dotted salmon Attr{ .kind = 251, .n = 3 }, // striped bronze }, }, Rule{ .kind = 95, // dull purple .attrs = &[_]Attr{ Attr{ .kind = 140, .n = 4 }, // muted gold Attr{ .kind = 264, .n = 2 }, // faded beige }, }, Rule{ .kind = 96, // wavy red .attrs = &[_]Attr{ Attr{ .kind = 14, .n = 4 }, // light lavender Attr{ .kind = 152, .n = 5 }, // drab beige }, }, Rule{ .kind = 97, // light beige .attrs = &[_]Attr{ Attr{ .kind = 98, .n = 3 }, // light maroon Attr{ .kind = 99, .n = 3 }, // vibrant orange Attr{ .kind = 100, .n = 4 }, // clear blue Attr{ .kind = 101, .n = 3 }, // mirrored fuchsia }, }, Rule{ .kind = 98, // light maroon .attrs = &[_]Attr{ Attr{ .kind = 126, .n = 4 }, // mirrored chartreuse Attr{ .kind = 146, .n = 1 }, // faded magenta }, }, Rule{ .kind = 99, // vibrant orange .attrs = &[_]Attr{ Attr{ .kind = 31, .n = 3 }, // shiny indigo Attr{ .kind = 68, .n = 4 }, // striped tan Attr{ .kind = 249, .n = 2 }, // bright tomato Attr{ .kind = 266, .n = 2 }, // dotted turquoise }, }, Rule{ .kind = 100, // clear blue .attrs = &[_]Attr{}, }, Rule{ .kind = 101, // mirrored fuchsia .attrs = &[_]Attr{ Attr{ .kind = 33, .n = 3 }, // clear gray }, }, Rule{ .kind = 102, // muted beige .attrs = &[_]Attr{ Attr{ .kind = 14, .n = 2 }, // light lavender Attr{ .kind = 185, .n = 1 }, // vibrant violet Attr{ .kind = 246, .n = 4 }, // wavy maroon }, }, Rule{ .kind = 103, // dark olive .attrs = &[_]Attr{ Attr{ .kind = 140, .n = 4 }, // muted gold Attr{ .kind = 156, .n = 1 }, // shiny chartreuse }, }, Rule{ .kind = 104, // clear tan .attrs = &[_]Attr{ Attr{ .kind = 61, .n = 1 }, // wavy yellow }, }, Rule{ .kind = 105, // posh lime .attrs = &[_]Attr{ Attr{ .kind = 106, .n = 3 }, // wavy beige }, }, Rule{ .kind = 106, // wavy beige .attrs = &[_]Attr{ Attr{ .kind = 45, .n = 4 }, // muted salmon Attr{ .kind = 248, .n = 4 }, // plaid yellow Attr{ .kind = 312, .n = 1 }, // dark bronze }, }, Rule{ .kind = 107, // pale blue .attrs = &[_]Attr{ Attr{ .kind = 88, .n = 4 }, // clear indigo Attr{ .kind = 108, .n = 5 }, // dull aqua Attr{ .kind = 109, .n = 4 }, // pale crimson Attr{ .kind = 110, .n = 3 }, // dull lime }, }, Rule{ .kind = 108, // dull aqua .attrs = &[_]Attr{ Attr{ .kind = 14, .n = 2 }, // light lavender Attr{ .kind = 95, .n = 4 }, // dull purple }, }, Rule{ .kind = 109, // pale crimson .attrs = &[_]Attr{ Attr{ .kind = 126, .n = 5 }, // mirrored chartreuse }, }, Rule{ .kind = 110, // dull lime .attrs = &[_]Attr{ Attr{ .kind = 37, .n = 3 }, // vibrant cyan Attr{ .kind = 59, .n = 2 }, // dotted violet }, }, Rule{ .kind = 111, // wavy silver .attrs = &[_]Attr{ Attr{ .kind = 112, .n = 1 }, // pale cyan }, }, Rule{ .kind = 112, // pale cyan .attrs = &[_]Attr{ Attr{ .kind = 103, .n = 1 }, // dark olive Attr{ .kind = 441, .n = 3 }, // muted white }, }, Rule{ .kind = 113, // striped beige .attrs = &[_]Attr{ Attr{ .kind = 33, .n = 1 }, // clear gray Attr{ .kind = 114, .n = 4 }, // dim plum }, }, Rule{ .kind = 114, // dim plum .attrs = &[_]Attr{ Attr{ .kind = 137, .n = 4 }, // plaid plum Attr{ .kind = 161, .n = 5 }, // light salmon Attr{ .kind = 519, .n = 2 }, // posh crimson }, }, Rule{ .kind = 115, // dim gold .attrs = &[_]Attr{ Attr{ .kind = 116, .n = 3 }, // dull cyan Attr{ .kind = 117, .n = 3 }, // drab black Attr{ .kind = 118, .n = 4 }, // dark green }, }, Rule{ .kind = 116, // dull cyan .attrs = &[_]Attr{}, }, Rule{ .kind = 117, // drab black .attrs = &[_]Attr{ Attr{ .kind = 201, .n = 1 }, // vibrant black }, }, Rule{ .kind = 118, // dark green .attrs = &[_]Attr{ Attr{ .kind = 51, .n = 3 }, // striped fuchsia Attr{ .kind = 129, .n = 1 }, // posh black }, }, Rule{ .kind = 119, // vibrant teal .attrs = &[_]Attr{ Attr{ .kind = 120, .n = 5 }, // clear green Attr{ .kind = 121, .n = 4 }, // light violet Attr{ .kind = 122, .n = 2 }, // bright beige }, }, Rule{ .kind = 120, // clear green .attrs = &[_]Attr{ Attr{ .kind = 183, .n = 4 }, // dim orange Attr{ .kind = 279, .n = 2 }, // faded aqua Attr{ .kind = 280, .n = 3 }, // vibrant olive }, }, Rule{ .kind = 121, // light violet .attrs = &[_]Attr{ Attr{ .kind = 17, .n = 2 }, // striped tomato Attr{ .kind = 328, .n = 3 }, // muted red Attr{ .kind = 480, .n = 4 }, // clear magenta Attr{ .kind = 491, .n = 1 }, // mirrored beige }, }, Rule{ .kind = 122, // bright beige .attrs = &[_]Attr{ Attr{ .kind = 302, .n = 3 }, // posh magenta Attr{ .kind = 321, .n = 2 }, // clear yellow Attr{ .kind = 583, .n = 1 }, // faded plum }, }, Rule{ .kind = 123, // light tan .attrs = &[_]Attr{ Attr{ .kind = 124, .n = 5 }, // pale red Attr{ .kind = 125, .n = 3 }, // light turquoise Attr{ .kind = 126, .n = 2 }, // mirrored chartreuse }, }, Rule{ .kind = 124, // pale red .attrs = &[_]Attr{ Attr{ .kind = 129, .n = 3 }, // posh black Attr{ .kind = 143, .n = 2 }, // vibrant bronze Attr{ .kind = 249, .n = 4 }, // bright tomato }, }, Rule{ .kind = 125, // light turquoise .attrs = &[_]Attr{ Attr{ .kind = 127, .n = 4 }, // dark red Attr{ .kind = 143, .n = 1 }, // vibrant bronze Attr{ .kind = 177, .n = 5 }, // posh white }, }, Rule{ .kind = 126, // mirrored chartreuse .attrs = &[_]Attr{ Attr{ .kind = 35, .n = 3 }, // dark turquoise Attr{ .kind = 289, .n = 5 }, // plaid black Attr{ .kind = 435, .n = 4 }, // striped silver Attr{ .kind = 442, .n = 2 }, // posh maroon }, }, Rule{ .kind = 127, // dark red .attrs = &[_]Attr{ Attr{ .kind = 100, .n = 3 }, // clear blue Attr{ .kind = 128, .n = 5 }, // shiny lime Attr{ .kind = 129, .n = 1 }, // posh black }, }, Rule{ .kind = 128, // shiny lime .attrs = &[_]Attr{}, }, Rule{ .kind = 129, // posh black .attrs = &[_]Attr{}, }, Rule{ .kind = 130, // posh salmon .attrs = &[_]Attr{ Attr{ .kind = 35, .n = 5 }, // dark turquoise Attr{ .kind = 86, .n = 1 }, // vibrant silver Attr{ .kind = 131, .n = 1 }, // plaid salmon Attr{ .kind = 132, .n = 1 }, // shiny orange }, }, Rule{ .kind = 131, // plaid salmon .attrs = &[_]Attr{ Attr{ .kind = 36, .n = 3 }, // shiny teal }, }, Rule{ .kind = 132, // shiny orange .attrs = &[_]Attr{ Attr{ .kind = 37, .n = 3 }, // vibrant cyan Attr{ .kind = 68, .n = 2 }, // striped tan Attr{ .kind = 96, .n = 1 }, // wavy red Attr{ .kind = 344, .n = 3 }, // bright chartreuse }, }, Rule{ .kind = 133, // mirrored yellow .attrs = &[_]Attr{ Attr{ .kind = 90, .n = 1 }, // dark brown Attr{ .kind = 134, .n = 5 }, // posh gray Attr{ .kind = 135, .n = 1 }, // shiny silver }, }, Rule{ .kind = 134, // posh gray .attrs = &[_]Attr{ Attr{ .kind = 194, .n = 3 }, // bright red Attr{ .kind = 463, .n = 3 }, // faded maroon }, }, Rule{ .kind = 135, // shiny silver .attrs = &[_]Attr{ Attr{ .kind = 80, .n = 3 }, // dull plum Attr{ .kind = 251, .n = 4 }, // striped bronze Attr{ .kind = 299, .n = 4 }, // posh tomato Attr{ .kind = 357, .n = 5 }, // vibrant indigo }, }, Rule{ .kind = 136, // dark fuchsia .attrs = &[_]Attr{ Attr{ .kind = 137, .n = 1 }, // plaid plum }, }, Rule{ .kind = 137, // plaid plum .attrs = &[_]Attr{ Attr{ .kind = 161, .n = 1 }, // light salmon Attr{ .kind = 162, .n = 2 }, // shiny brown Attr{ .kind = 237, .n = 5 }, // faded yellow }, }, Rule{ .kind = 138, // bright bronze .attrs = &[_]Attr{ Attr{ .kind = 35, .n = 4 }, // dark turquoise }, }, Rule{ .kind = 139, // posh silver .attrs = &[_]Attr{ Attr{ .kind = 108, .n = 3 }, // dull aqua Attr{ .kind = 134, .n = 3 }, // posh gray Attr{ .kind = 140, .n = 1 }, // muted gold Attr{ .kind = 141, .n = 2 }, // striped chartreuse }, }, Rule{ .kind = 140, // muted gold .attrs = &[_]Attr{}, }, Rule{ .kind = 141, // striped chartreuse .attrs = &[_]Attr{ Attr{ .kind = 37, .n = 1 }, // vibrant cyan Attr{ .kind = 129, .n = 4 }, // posh black Attr{ .kind = 344, .n = 2 }, // bright chartreuse }, }, Rule{ .kind = 142, // dotted salmon .attrs = &[_]Attr{ Attr{ .kind = 51, .n = 4 }, // striped fuchsia Attr{ .kind = 143, .n = 2 }, // vibrant bronze Attr{ .kind = 144, .n = 3 }, // striped blue }, }, Rule{ .kind = 143, // vibrant bronze .attrs = &[_]Attr{ Attr{ .kind = 100, .n = 5 }, // clear blue }, }, Rule{ .kind = 144, // striped blue .attrs = &[_]Attr{ Attr{ .kind = 37, .n = 4 }, // vibrant cyan Attr{ .kind = 110, .n = 2 }, // dull lime Attr{ .kind = 141, .n = 3 }, // striped chartreuse Attr{ .kind = 438, .n = 4 }, // bright tan }, }, Rule{ .kind = 145, // dark orange .attrs = &[_]Attr{ Attr{ .kind = 146, .n = 5 }, // faded magenta }, }, Rule{ .kind = 146, // faded magenta .attrs = &[_]Attr{ Attr{ .kind = 182, .n = 2 }, // shiny gold Attr{ .kind = 208, .n = 2 }, // mirrored lavender Attr{ .kind = 357, .n = 4 }, // vibrant indigo }, }, Rule{ .kind = 147, // bright silver .attrs = &[_]Attr{ Attr{ .kind = 148, .n = 5 }, // drab silver }, }, Rule{ .kind = 148, // drab silver .attrs = &[_]Attr{ Attr{ .kind = 261, .n = 2 }, // plaid lime Attr{ .kind = 544, .n = 2 }, // plaid white }, }, Rule{ .kind = 149, // posh orange .attrs = &[_]Attr{ Attr{ .kind = 123, .n = 5 }, // light tan Attr{ .kind = 150, .n = 4 }, // plaid tan }, }, Rule{ .kind = 150, // plaid tan .attrs = &[_]Attr{ Attr{ .kind = 30, .n = 4 }, // dark chartreuse Attr{ .kind = 106, .n = 1 }, // wavy beige }, }, Rule{ .kind = 151, // mirrored olive .attrs = &[_]Attr{ Attr{ .kind = 116, .n = 4 }, // dull cyan Attr{ .kind = 129, .n = 4 }, // posh black Attr{ .kind = 141, .n = 2 }, // striped chartreuse }, }, Rule{ .kind = 152, // drab beige .attrs = &[_]Attr{ Attr{ .kind = 118, .n = 2 }, // dark green Attr{ .kind = 153, .n = 2 }, // bright maroon }, }, Rule{ .kind = 153, // bright maroon .attrs = &[_]Attr{}, }, Rule{ .kind = 154, // muted bronze .attrs = &[_]Attr{ Attr{ .kind = 88, .n = 2 }, // clear indigo Attr{ .kind = 120, .n = 1 }, // clear green }, }, Rule{ .kind = 155, // wavy brown .attrs = &[_]Attr{ Attr{ .kind = 87, .n = 4 }, // posh brown Attr{ .kind = 208, .n = 4 }, // mirrored lavender Attr{ .kind = 519, .n = 3 }, // posh crimson }, }, Rule{ .kind = 156, // shiny chartreuse .attrs = &[_]Attr{ Attr{ .kind = 100, .n = 1 }, // clear blue Attr{ .kind = 129, .n = 5 }, // posh black }, }, Rule{ .kind = 157, // dull white .attrs = &[_]Attr{ Attr{ .kind = 98, .n = 1 }, // light maroon Attr{ .kind = 158, .n = 2 }, // muted crimson }, }, Rule{ .kind = 158, // muted crimson .attrs = &[_]Attr{ Attr{ .kind = 197, .n = 5 }, // drab plum }, }, Rule{ .kind = 159, // shiny gray .attrs = &[_]Attr{ Attr{ .kind = 22, .n = 1 }, // striped orange Attr{ .kind = 26, .n = 2 }, // dim maroon }, }, Rule{ .kind = 160, // dotted orange .attrs = &[_]Attr{ Attr{ .kind = 21, .n = 1 }, // dull teal Attr{ .kind = 45, .n = 4 }, // muted salmon Attr{ .kind = 161, .n = 1 }, // light salmon Attr{ .kind = 162, .n = 4 }, // shiny brown }, }, Rule{ .kind = 161, // light salmon .attrs = &[_]Attr{ Attr{ .kind = 45, .n = 2 }, // muted salmon Attr{ .kind = 87, .n = 3 }, // posh brown }, }, Rule{ .kind = 162, // shiny brown .attrs = &[_]Attr{ Attr{ .kind = 277, .n = 2 }, // dull green Attr{ .kind = 278, .n = 3 }, // wavy lime }, }, Rule{ .kind = 163, // clear olive .attrs = &[_]Attr{ Attr{ .kind = 164, .n = 3 }, // mirrored tan Attr{ .kind = 165, .n = 5 }, // pale tan }, }, Rule{ .kind = 164, // mirrored tan .attrs = &[_]Attr{ Attr{ .kind = 8, .n = 3 }, // faded salmon Attr{ .kind = 87, .n = 2 }, // posh brown Attr{ .kind = 127, .n = 3 }, // dark red }, }, Rule{ .kind = 165, // pale tan .attrs = &[_]Attr{ Attr{ .kind = 217, .n = 1 }, // pale olive Attr{ .kind = 245, .n = 4 }, // mirrored teal }, }, Rule{ .kind = 166, // drab bronze .attrs = &[_]Attr{ Attr{ .kind = 118, .n = 1 }, // dark green Attr{ .kind = 167, .n = 1 }, // drab teal }, }, Rule{ .kind = 167, // drab teal .attrs = &[_]Attr{ Attr{ .kind = 23, .n = 4 }, // bright fuchsia }, }, Rule{ .kind = 168, // drab chartreuse .attrs = &[_]Attr{ Attr{ .kind = 169, .n = 4 }, // dim beige }, }, Rule{ .kind = 169, // dim beige .attrs = &[_]Attr{ Attr{ .kind = 135, .n = 2 }, // shiny silver Attr{ .kind = 308, .n = 3 }, // vibrant maroon Attr{ .kind = 346, .n = 4 }, // faded lavender }, }, Rule{ .kind = 170, // faded cyan .attrs = &[_]Attr{ Attr{ .kind = 1, .n = 5 }, // clear gold }, }, Rule{ .kind = 171, // plaid fuchsia .attrs = &[_]Attr{ Attr{ .kind = 172, .n = 2 }, // pale yellow }, }, Rule{ .kind = 172, // pale yellow .attrs = &[_]Attr{ Attr{ .kind = 19, .n = 1 }, // clear teal Attr{ .kind = 94, .n = 2 }, // posh bronze Attr{ .kind = 197, .n = 4 }, // drab plum Attr{ .kind = 381, .n = 4 }, // faded purple }, }, Rule{ .kind = 173, // light gold .attrs = &[_]Attr{ Attr{ .kind = 8, .n = 2 }, // faded salmon Attr{ .kind = 112, .n = 5 }, // pale cyan Attr{ .kind = 174, .n = 1 }, // posh olive Attr{ .kind = 175, .n = 5 }, // pale tomato }, }, Rule{ .kind = 174, // posh olive .attrs = &[_]Attr{ Attr{ .kind = 33, .n = 3 }, // clear gray Attr{ .kind = 208, .n = 5 }, // mirrored lavender }, }, Rule{ .kind = 175, // pale tomato .attrs = &[_]Attr{ Attr{ .kind = 101, .n = 1 }, // mirrored fuchsia }, }, Rule{ .kind = 176, // pale bronze .attrs = &[_]Attr{ Attr{ .kind = 177, .n = 2 }, // posh white }, }, Rule{ .kind = 177, // posh white .attrs = &[_]Attr{ Attr{ .kind = 336, .n = 5 }, // vibrant gold }, }, Rule{ .kind = 178, // shiny coral .attrs = &[_]Attr{ Attr{ .kind = 179, .n = 2 }, // plaid crimson Attr{ .kind = 180, .n = 1 }, // clear turquoise }, }, Rule{ .kind = 179, // plaid crimson .attrs = &[_]Attr{ Attr{ .kind = 220, .n = 4 }, // pale chartreuse Attr{ .kind = 357, .n = 3 }, // vibrant indigo }, }, Rule{ .kind = 180, // clear turquoise .attrs = &[_]Attr{ Attr{ .kind = 68, .n = 3 }, // striped tan Attr{ .kind = 164, .n = 2 }, // mirrored tan Attr{ .kind = 289, .n = 4 }, // plaid black }, }, Rule{ .kind = 181, // vibrant green .attrs = &[_]Attr{ Attr{ .kind = 24, .n = 3 }, // plaid chartreuse Attr{ .kind = 182, .n = 4 }, // shiny gold Attr{ .kind = 183, .n = 2 }, // dim orange Attr{ .kind = 184, .n = 4 }, // dark tomato }, }, Rule{ .kind = 182, // shiny gold .attrs = &[_]Attr{ Attr{ .kind = 29, .n = 1 }, // muted olive Attr{ .kind = 49, .n = 5 }, // dotted red Attr{ .kind = 197, .n = 1 }, // drab plum }, }, Rule{ .kind = 183, // dim orange .attrs = &[_]Attr{ Attr{ .kind = 264, .n = 1 }, // faded beige }, }, Rule{ .kind = 184, // dark tomato .attrs = &[_]Attr{ Attr{ .kind = 140, .n = 4 }, // muted gold Attr{ .kind = 182, .n = 3 }, // shiny gold Attr{ .kind = 194, .n = 3 }, // bright red }, }, Rule{ .kind = 185, // vibrant violet .attrs = &[_]Attr{ Attr{ .kind = 66, .n = 5 }, // bright aqua Attr{ .kind = 186, .n = 5 }, // clear purple }, }, Rule{ .kind = 186, // clear purple .attrs = &[_]Attr{ Attr{ .kind = 156, .n = 1 }, // shiny chartreuse }, }, Rule{ .kind = 187, // muted fuchsia .attrs = &[_]Attr{ Attr{ .kind = 39, .n = 2 }, // bright yellow }, }, Rule{ .kind = 188, // bright olive .attrs = &[_]Attr{ Attr{ .kind = 4, .n = 5 }, // plaid aqua Attr{ .kind = 42, .n = 5 }, // dull black Attr{ .kind = 189, .n = 5 }, // bright gold Attr{ .kind = 190, .n = 1 }, // mirrored indigo }, }, Rule{ .kind = 189, // bright gold .attrs = &[_]Attr{ Attr{ .kind = 102, .n = 1 }, // muted beige Attr{ .kind = 303, .n = 4 }, // pale green Attr{ .kind = 361, .n = 2 }, // faded indigo Attr{ .kind = 362, .n = 5 }, // mirrored orange }, }, Rule{ .kind = 190, // mirrored indigo .attrs = &[_]Attr{ Attr{ .kind = 373, .n = 3 }, // dim crimson }, }, Rule{ .kind = 191, // mirrored maroon .attrs = &[_]Attr{ Attr{ .kind = 192, .n = 2 }, // dull chartreuse }, }, Rule{ .kind = 192, // dull chartreuse .attrs = &[_]Attr{ Attr{ .kind = 129, .n = 5 }, // posh black Attr{ .kind = 246, .n = 5 }, // wavy maroon Attr{ .kind = 358, .n = 1 }, // shiny purple Attr{ .kind = 438, .n = 2 }, // bright tan }, }, Rule{ .kind = 193, // pale salmon .attrs = &[_]Attr{ Attr{ .kind = 45, .n = 1 }, // muted salmon Attr{ .kind = 140, .n = 1 }, // muted gold Attr{ .kind = 164, .n = 5 }, // mirrored tan Attr{ .kind = 194, .n = 5 }, // bright red }, }, Rule{ .kind = 194, // bright red .attrs = &[_]Attr{}, }, Rule{ .kind = 195, // faded brown .attrs = &[_]Attr{ Attr{ .kind = 25, .n = 2 }, // dark silver Attr{ .kind = 29, .n = 2 }, // muted olive Attr{ .kind = 40, .n = 5 }, // dull orange Attr{ .kind = 41, .n = 3 }, // plaid tomato }, }, Rule{ .kind = 196, // dark lavender .attrs = &[_]Attr{ Attr{ .kind = 115, .n = 1 }, // dim gold Attr{ .kind = 184, .n = 4 }, // dark tomato Attr{ .kind = 197, .n = 2 }, // drab plum Attr{ .kind = 198, .n = 3 }, // vibrant gray }, }, Rule{ .kind = 197, // drab plum .attrs = &[_]Attr{ Attr{ .kind = 29, .n = 1 }, // muted olive Attr{ .kind = 68, .n = 1 }, // striped tan Attr{ .kind = 143, .n = 5 }, // vibrant bronze }, }, Rule{ .kind = 198, // vibrant gray .attrs = &[_]Attr{ Attr{ .kind = 12, .n = 3 }, // vibrant yellow Attr{ .kind = 19, .n = 2 }, // clear teal }, }, Rule{ .kind = 199, // plaid coral .attrs = &[_]Attr{ Attr{ .kind = 8, .n = 2 }, // faded salmon Attr{ .kind = 200, .n = 3 }, // striped turquoise }, }, Rule{ .kind = 200, // striped turquoise .attrs = &[_]Attr{ Attr{ .kind = 116, .n = 5 }, // dull cyan Attr{ .kind = 139, .n = 5 }, // posh silver Attr{ .kind = 210, .n = 2 }, // faded violet Attr{ .kind = 239, .n = 4 }, // bright violet }, }, Rule{ .kind = 201, // vibrant black .attrs = &[_]Attr{ Attr{ .kind = 439, .n = 2 }, // mirrored green }, }, Rule{ .kind = 202, // shiny black .attrs = &[_]Attr{ Attr{ .kind = 134, .n = 3 }, // posh gray Attr{ .kind = 203, .n = 3 }, // shiny olive Attr{ .kind = 204, .n = 4 }, // dull violet Attr{ .kind = 205, .n = 4 }, // vibrant plum }, }, Rule{ .kind = 203, // shiny olive .attrs = &[_]Attr{ Attr{ .kind = 285, .n = 1 }, // plaid beige }, }, Rule{ .kind = 204, // dull violet .attrs = &[_]Attr{ Attr{ .kind = 201, .n = 1 }, // vibrant black }, }, Rule{ .kind = 205, // vibrant plum .attrs = &[_]Attr{ Attr{ .kind = 179, .n = 4 }, // plaid crimson Attr{ .kind = 219, .n = 3 }, // faded turquoise }, }, Rule{ .kind = 206, // muted plum .attrs = &[_]Attr{ Attr{ .kind = 78, .n = 1 }, // dark plum Attr{ .kind = 162, .n = 1 }, // shiny brown Attr{ .kind = 175, .n = 5 }, // pale tomato Attr{ .kind = 204, .n = 4 }, // dull violet }, }, Rule{ .kind = 207, // shiny lavender .attrs = &[_]Attr{ Attr{ .kind = 208, .n = 4 }, // mirrored lavender }, }, Rule{ .kind = 208, // mirrored lavender .attrs = &[_]Attr{ Attr{ .kind = 153, .n = 5 }, // bright maroon Attr{ .kind = 197, .n = 4 }, // drab plum Attr{ .kind = 210, .n = 1 }, // faded violet Attr{ .kind = 251, .n = 5 }, // striped bronze }, }, Rule{ .kind = 209, // mirrored blue .attrs = &[_]Attr{ Attr{ .kind = 210, .n = 1 }, // faded violet Attr{ .kind = 211, .n = 2 }, // plaid olive }, }, Rule{ .kind = 210, // faded violet .attrs = &[_]Attr{ Attr{ .kind = 68, .n = 1 }, // striped tan }, }, Rule{ .kind = 211, // plaid olive .attrs = &[_]Attr{ Attr{ .kind = 23, .n = 1 }, // bright fuchsia Attr{ .kind = 95, .n = 5 }, // dull purple Attr{ .kind = 101, .n = 1 }, // mirrored fuchsia }, }, Rule{ .kind = 212, // dotted aqua .attrs = &[_]Attr{ Attr{ .kind = 213, .n = 3 }, // shiny yellow }, }, Rule{ .kind = 213, // shiny yellow .attrs = &[_]Attr{ Attr{ .kind = 86, .n = 4 }, // vibrant silver Attr{ .kind = 115, .n = 4 }, // dim gold Attr{ .kind = 377, .n = 1 }, // dark yellow }, }, Rule{ .kind = 214, // light silver .attrs = &[_]Attr{}, }, Rule{ .kind = 215, // bright orange .attrs = &[_]Attr{ Attr{ .kind = 11, .n = 3 }, // striped gold Attr{ .kind = 59, .n = 5 }, // dotted violet }, }, Rule{ .kind = 216, // dim indigo .attrs = &[_]Attr{ Attr{ .kind = 87, .n = 5 }, // posh brown Attr{ .kind = 217, .n = 1 }, // pale olive Attr{ .kind = 218, .n = 1 }, // light indigo }, }, Rule{ .kind = 217, // pale olive .attrs = &[_]Attr{ Attr{ .kind = 75, .n = 4 }, // dark maroon Attr{ .kind = 363, .n = 1 }, // clear red }, }, Rule{ .kind = 218, // light indigo .attrs = &[_]Attr{ Attr{ .kind = 74, .n = 3 }, // dim black Attr{ .kind = 146, .n = 4 }, // faded magenta Attr{ .kind = 345, .n = 2 }, // dim purple }, }, Rule{ .kind = 219, // faded turquoise .attrs = &[_]Attr{ Attr{ .kind = 43, .n = 4 }, // light olive Attr{ .kind = 220, .n = 3 }, // pale chartreuse }, }, Rule{ .kind = 220, // pale chartreuse .attrs = &[_]Attr{ Attr{ .kind = 340, .n = 4 }, // dotted gold Attr{ .kind = 396, .n = 4 }, // faded crimson Attr{ .kind = 519, .n = 4 }, // posh crimson }, }, Rule{ .kind = 221, // wavy teal .attrs = &[_]Attr{ Attr{ .kind = 222, .n = 3 }, // clear brown Attr{ .kind = 223, .n = 3 }, // dark beige }, }, Rule{ .kind = 222, // clear brown .attrs = &[_]Attr{ Attr{ .kind = 29, .n = 2 }, // muted olive Attr{ .kind = 260, .n = 5 }, // plaid gold }, }, Rule{ .kind = 223, // dark beige .attrs = &[_]Attr{ Attr{ .kind = 108, .n = 2 }, // dull aqua Attr{ .kind = 271, .n = 2 }, // drab blue }, }, Rule{ .kind = 224, // dotted bronze .attrs = &[_]Attr{ Attr{ .kind = 155, .n = 1 }, // wavy brown }, }, Rule{ .kind = 225, // posh purple .attrs = &[_]Attr{ Attr{ .kind = 31, .n = 2 }, // shiny indigo Attr{ .kind = 153, .n = 5 }, // bright maroon Attr{ .kind = 226, .n = 1 }, // clear silver }, }, Rule{ .kind = 226, // clear silver .attrs = &[_]Attr{ Attr{ .kind = 200, .n = 2 }, // striped turquoise }, }, Rule{ .kind = 227, // mirrored crimson .attrs = &[_]Attr{ Attr{ .kind = 76, .n = 4 }, // muted lavender Attr{ .kind = 151, .n = 2 }, // mirrored olive Attr{ .kind = 220, .n = 3 }, // pale chartreuse Attr{ .kind = 228, .n = 4 }, // plaid bronze }, }, Rule{ .kind = 228, // plaid bronze .attrs = &[_]Attr{ Attr{ .kind = 93, .n = 1 }, // wavy green Attr{ .kind = 297, .n = 5 }, // bright blue Attr{ .kind = 480, .n = 3 }, // clear magenta }, }, Rule{ .kind = 229, // wavy fuchsia .attrs = &[_]Attr{ Attr{ .kind = 109, .n = 2 }, // pale crimson Attr{ .kind = 197, .n = 2 }, // drab plum Attr{ .kind = 230, .n = 1 }, // plaid magenta Attr{ .kind = 231, .n = 1 }, // drab aqua }, }, Rule{ .kind = 230, // plaid magenta .attrs = &[_]Attr{ Attr{ .kind = 264, .n = 2 }, // faded beige Attr{ .kind = 351, .n = 2 }, // vibrant coral Attr{ .kind = 387, .n = 2 }, // light green Attr{ .kind = 523, .n = 1 }, // dim teal }, }, Rule{ .kind = 231, // drab aqua .attrs = &[_]Attr{ Attr{ .kind = 77, .n = 5 }, // bright cyan Attr{ .kind = 106, .n = 1 }, // wavy beige Attr{ .kind = 441, .n = 1 }, // muted white }, }, Rule{ .kind = 232, // striped yellow .attrs = &[_]Attr{ Attr{ .kind = 233, .n = 4 }, // dark coral Attr{ .kind = 234, .n = 5 }, // dim silver }, }, Rule{ .kind = 233, // dark coral .attrs = &[_]Attr{ Attr{ .kind = 88, .n = 3 }, // clear indigo Attr{ .kind = 116, .n = 5 }, // dull cyan Attr{ .kind = 236, .n = 5 }, // faded teal }, }, Rule{ .kind = 234, // dim silver .attrs = &[_]Attr{ Attr{ .kind = 12, .n = 1 }, // vibrant yellow Attr{ .kind = 257, .n = 1 }, // clear tomato }, }, Rule{ .kind = 235, // striped white .attrs = &[_]Attr{ Attr{ .kind = 12, .n = 3 }, // vibrant yellow Attr{ .kind = 129, .n = 2 }, // posh black Attr{ .kind = 236, .n = 4 }, // faded teal Attr{ .kind = 237, .n = 1 }, // faded yellow }, }, Rule{ .kind = 236, // faded teal .attrs = &[_]Attr{ Attr{ .kind = 36, .n = 5 }, // shiny teal Attr{ .kind = 66, .n = 4 }, // bright aqua Attr{ .kind = 194, .n = 2 }, // bright red Attr{ .kind = 268, .n = 2 }, // dotted beige }, }, Rule{ .kind = 237, // faded yellow .attrs = &[_]Attr{ Attr{ .kind = 23, .n = 5 }, // bright fuchsia Attr{ .kind = 129, .n = 4 }, // posh black Attr{ .kind = 344, .n = 2 }, // bright chartreuse }, }, Rule{ .kind = 238, // faded blue .attrs = &[_]Attr{ Attr{ .kind = 45, .n = 4 }, // muted salmon Attr{ .kind = 88, .n = 5 }, // clear indigo Attr{ .kind = 239, .n = 3 }, // bright violet Attr{ .kind = 240, .n = 4 }, // dark purple }, }, Rule{ .kind = 239, // bright violet .attrs = &[_]Attr{ Attr{ .kind = 92, .n = 1 }, // muted tomato Attr{ .kind = 128, .n = 1 }, // shiny lime }, }, Rule{ .kind = 240, // dark purple .attrs = &[_]Attr{ Attr{ .kind = 51, .n = 4 }, // striped fuchsia Attr{ .kind = 156, .n = 2 }, // shiny chartreuse Attr{ .kind = 214, .n = 5 }, // light silver Attr{ .kind = 270, .n = 5 }, // clear cyan }, }, Rule{ .kind = 241, // dim aqua .attrs = &[_]Attr{ Attr{ .kind = 62, .n = 5 }, // plaid red Attr{ .kind = 134, .n = 4 }, // posh gray Attr{ .kind = 242, .n = 1 }, // clear bronze Attr{ .kind = 243, .n = 4 }, // dull magenta }, }, Rule{ .kind = 242, // clear bronze .attrs = &[_]Attr{ Attr{ .kind = 33, .n = 3 }, // clear gray Attr{ .kind = 169, .n = 1 }, // dim beige }, }, Rule{ .kind = 243, // dull magenta .attrs = &[_]Attr{ Attr{ .kind = 192, .n = 2 }, // dull chartreuse Attr{ .kind = 522, .n = 5 }, // vibrant beige }, }, Rule{ .kind = 244, // shiny magenta .attrs = &[_]Attr{ Attr{ .kind = 245, .n = 2 }, // mirrored teal }, }, Rule{ .kind = 245, // mirrored teal .attrs = &[_]Attr{ Attr{ .kind = 131, .n = 3 }, // plaid salmon Attr{ .kind = 410, .n = 5 }, // plaid brown }, }, Rule{ .kind = 246, // wavy maroon .attrs = &[_]Attr{ Attr{ .kind = 116, .n = 1 }, // dull cyan Attr{ .kind = 125, .n = 2 }, // light turquoise Attr{ .kind = 232, .n = 2 }, // striped yellow }, }, Rule{ .kind = 247, // plaid teal .attrs = &[_]Attr{ Attr{ .kind = 43, .n = 5 }, // light olive Attr{ .kind = 181, .n = 2 }, // vibrant green Attr{ .kind = 248, .n = 4 }, // plaid yellow }, }, Rule{ .kind = 248, // plaid yellow .attrs = &[_]Attr{ Attr{ .kind = 185, .n = 1 }, // vibrant violet Attr{ .kind = 351, .n = 3 }, // vibrant coral Attr{ .kind = 403, .n = 5 }, // mirrored cyan Attr{ .kind = 499, .n = 5 }, // dim cyan }, }, Rule{ .kind = 249, // bright tomato .attrs = &[_]Attr{ Attr{ .kind = 100, .n = 3 }, // clear blue Attr{ .kind = 128, .n = 5 }, // shiny lime Attr{ .kind = 153, .n = 3 }, // bright maroon Attr{ .kind = 250, .n = 5 }, // posh lavender }, }, Rule{ .kind = 250, // posh lavender .attrs = &[_]Attr{ Attr{ .kind = 128, .n = 2 }, // shiny lime Attr{ .kind = 194, .n = 3 }, // bright red Attr{ .kind = 344, .n = 2 }, // bright chartreuse }, }, Rule{ .kind = 251, // striped bronze .attrs = &[_]Attr{ Attr{ .kind = 14, .n = 2 }, // light lavender Attr{ .kind = 29, .n = 5 }, // muted olive Attr{ .kind = 127, .n = 5 }, // dark red Attr{ .kind = 134, .n = 4 }, // posh gray }, }, Rule{ .kind = 252, // vibrant purple .attrs = &[_]Attr{ Attr{ .kind = 61, .n = 4 }, // wavy yellow Attr{ .kind = 80, .n = 1 }, // dull plum }, }, Rule{ .kind = 253, // posh aqua .attrs = &[_]Attr{ Attr{ .kind = 175, .n = 3 }, // pale tomato Attr{ .kind = 247, .n = 2 }, // plaid teal Attr{ .kind = 254, .n = 4 }, // muted teal }, }, Rule{ .kind = 254, // muted teal .attrs = &[_]Attr{ Attr{ .kind = 40, .n = 5 }, // dull orange Attr{ .kind = 140, .n = 2 }, // muted gold Attr{ .kind = 141, .n = 4 }, // striped chartreuse Attr{ .kind = 439, .n = 1 }, // mirrored green }, }, Rule{ .kind = 255, // faded fuchsia .attrs = &[_]Attr{ Attr{ .kind = 18, .n = 5 }, // drab gold Attr{ .kind = 196, .n = 3 }, // dark lavender Attr{ .kind = 256, .n = 4 }, // plaid green }, }, Rule{ .kind = 256, // plaid green .attrs = &[_]Attr{ Attr{ .kind = 14, .n = 5 }, // light lavender Attr{ .kind = 137, .n = 4 }, // plaid plum Attr{ .kind = 267, .n = 3 }, // posh plum Attr{ .kind = 281, .n = 5 }, // mirrored violet }, }, Rule{ .kind = 257, // clear tomato .attrs = &[_]Attr{ Attr{ .kind = 251, .n = 2 }, // striped bronze }, }, Rule{ .kind = 258, // dim olive .attrs = &[_]Attr{ Attr{ .kind = 114, .n = 4 }, // dim plum Attr{ .kind = 259, .n = 2 }, // clear violet Attr{ .kind = 260, .n = 3 }, // plaid gold Attr{ .kind = 261, .n = 3 }, // plaid lime }, }, Rule{ .kind = 259, // clear violet .attrs = &[_]Attr{ Attr{ .kind = 150, .n = 1 }, // plaid tan Attr{ .kind = 161, .n = 2 }, // light salmon }, }, Rule{ .kind = 260, // plaid gold .attrs = &[_]Attr{ Attr{ .kind = 193, .n = 1 }, // pale salmon Attr{ .kind = 285, .n = 4 }, // plaid beige }, }, Rule{ .kind = 261, // plaid lime .attrs = &[_]Attr{ Attr{ .kind = 179, .n = 5 }, // plaid crimson Attr{ .kind = 312, .n = 5 }, // dark bronze }, }, Rule{ .kind = 262, // striped teal .attrs = &[_]Attr{ Attr{ .kind = 263, .n = 2 }, // bright lavender Attr{ .kind = 264, .n = 5 }, // faded beige Attr{ .kind = 265, .n = 5 }, // clear beige Attr{ .kind = 266, .n = 4 }, // dotted turquoise }, }, Rule{ .kind = 263, // bright lavender .attrs = &[_]Attr{ Attr{ .kind = 441, .n = 1 }, // muted white }, }, Rule{ .kind = 264, // faded beige .attrs = &[_]Attr{ Attr{ .kind = 23, .n = 1 }, // bright fuchsia Attr{ .kind = 29, .n = 5 }, // muted olive Attr{ .kind = 153, .n = 4 }, // bright maroon }, }, Rule{ .kind = 265, // clear beige .attrs = &[_]Attr{ Attr{ .kind = 194, .n = 5 }, // bright red }, }, Rule{ .kind = 266, // dotted turquoise .attrs = &[_]Attr{ Attr{ .kind = 23, .n = 2 }, // bright fuchsia Attr{ .kind = 186, .n = 1 }, // clear purple }, }, Rule{ .kind = 267, // posh plum .attrs = &[_]Attr{ Attr{ .kind = 64, .n = 3 }, // bright brown }, }, Rule{ .kind = 268, // dotted beige .attrs = &[_]Attr{ Attr{ .kind = 29, .n = 5 }, // muted olive Attr{ .kind = 37, .n = 2 }, // vibrant cyan Attr{ .kind = 125, .n = 4 }, // light turquoise }, }, Rule{ .kind = 269, // striped indigo .attrs = &[_]Attr{ Attr{ .kind = 33, .n = 3 }, // clear gray Attr{ .kind = 211, .n = 4 }, // plaid olive Attr{ .kind = 261, .n = 3 }, // plaid lime Attr{ .kind = 270, .n = 5 }, // clear cyan }, }, Rule{ .kind = 270, // clear cyan .attrs = &[_]Attr{ Attr{ .kind = 29, .n = 5 }, // muted olive Attr{ .kind = 118, .n = 1 }, // dark green Attr{ .kind = 153, .n = 3 }, // bright maroon Attr{ .kind = 358, .n = 3 }, // shiny purple }, }, Rule{ .kind = 271, // drab blue .attrs = &[_]Attr{ Attr{ .kind = 272, .n = 2 }, // dim coral Attr{ .kind = 273, .n = 4 }, // plaid purple }, }, Rule{ .kind = 272, // dim coral .attrs = &[_]Attr{ Attr{ .kind = 235, .n = 2 }, // striped white }, }, Rule{ .kind = 273, // plaid purple .attrs = &[_]Attr{ Attr{ .kind = 59, .n = 4 }, // dotted violet Attr{ .kind = 441, .n = 1 }, // muted white }, }, Rule{ .kind = 274, // vibrant red .attrs = &[_]Attr{ Attr{ .kind = 194, .n = 2 }, // bright red Attr{ .kind = 275, .n = 2 }, // pale gray Attr{ .kind = 276, .n = 4 }, // wavy tomato }, }, Rule{ .kind = 275, // pale gray .attrs = &[_]Attr{ Attr{ .kind = 30, .n = 5 }, // dark chartreuse Attr{ .kind = 68, .n = 2 }, // striped tan Attr{ .kind = 336, .n = 3 }, // vibrant gold Attr{ .kind = 395, .n = 4 }, // vibrant brown }, }, Rule{ .kind = 276, // wavy tomato .attrs = &[_]Attr{ Attr{ .kind = 0, .n = 1 }, // drab tan Attr{ .kind = 101, .n = 3 }, // mirrored fuchsia Attr{ .kind = 153, .n = 1 }, // bright maroon }, }, Rule{ .kind = 277, // dull green .attrs = &[_]Attr{ Attr{ .kind = 151, .n = 4 }, // mirrored olive Attr{ .kind = 325, .n = 3 }, // drab red Attr{ .kind = 410, .n = 3 }, // plaid brown Attr{ .kind = 487, .n = 4 }, // muted turquoise }, }, Rule{ .kind = 278, // wavy lime .attrs = &[_]Attr{ Attr{ .kind = 64, .n = 2 }, // bright brown Attr{ .kind = 103, .n = 1 }, // dark olive Attr{ .kind = 194, .n = 5 }, // bright red }, }, Rule{ .kind = 279, // faded aqua .attrs = &[_]Attr{ Attr{ .kind = 32, .n = 2 }, // dotted silver Attr{ .kind = 66, .n = 3 }, // bright aqua Attr{ .kind = 152, .n = 2 }, // drab beige Attr{ .kind = 197, .n = 3 }, // drab plum }, }, Rule{ .kind = 280, // vibrant olive .attrs = &[_]Attr{ Attr{ .kind = 336, .n = 4 }, // vibrant gold }, }, Rule{ .kind = 281, // mirrored violet .attrs = &[_]Attr{ Attr{ .kind = 278, .n = 5 }, // wavy lime Attr{ .kind = 282, .n = 1 }, // wavy chartreuse }, }, Rule{ .kind = 282, // wavy chartreuse .attrs = &[_]Attr{ Attr{ .kind = 32, .n = 4 }, // dotted silver Attr{ .kind = 174, .n = 5 }, // posh olive Attr{ .kind = 325, .n = 3 }, // drab red }, }, Rule{ .kind = 283, // light brown .attrs = &[_]Attr{ Attr{ .kind = 196, .n = 5 }, // dark lavender }, }, Rule{ .kind = 284, // plaid blue .attrs = &[_]Attr{ Attr{ .kind = 285, .n = 3 }, // plaid beige Attr{ .kind = 286, .n = 5 }, // dotted teal }, }, Rule{ .kind = 285, // plaid beige .attrs = &[_]Attr{ Attr{ .kind = 482, .n = 2 }, // light white }, }, Rule{ .kind = 286, // dotted teal .attrs = &[_]Attr{ Attr{ .kind = 156, .n = 5 }, // shiny chartreuse }, }, Rule{ .kind = 287, // dim green .attrs = &[_]Attr{ Attr{ .kind = 54, .n = 1 }, // light gray Attr{ .kind = 288, .n = 5 }, // bright green }, }, Rule{ .kind = 288, // bright green .attrs = &[_]Attr{ Attr{ .kind = 24, .n = 3 }, // plaid chartreuse Attr{ .kind = 183, .n = 5 }, // dim orange Attr{ .kind = 243, .n = 4 }, // dull magenta }, }, Rule{ .kind = 289, // plaid black .attrs = &[_]Attr{ Attr{ .kind = 23, .n = 4 }, // bright fuchsia Attr{ .kind = 118, .n = 5 }, // dark green Attr{ .kind = 128, .n = 2 }, // shiny lime }, }, Rule{ .kind = 290, // dull salmon .attrs = &[_]Attr{ Attr{ .kind = 291, .n = 3 }, // faded lime Attr{ .kind = 292, .n = 1 }, // striped gray Attr{ .kind = 293, .n = 3 }, // dull gold }, }, Rule{ .kind = 291, // faded lime .attrs = &[_]Attr{ Attr{ .kind = 345, .n = 1 }, // dim purple Attr{ .kind = 395, .n = 2 }, // vibrant brown }, }, Rule{ .kind = 292, // striped gray .attrs = &[_]Attr{ Attr{ .kind = 41, .n = 3 }, // plaid tomato }, }, Rule{ .kind = 293, // dull gold .attrs = &[_]Attr{ Attr{ .kind = 160, .n = 2 }, // dotted orange Attr{ .kind = 315, .n = 4 }, // pale gold Attr{ .kind = 423, .n = 5 }, // light yellow }, }, Rule{ .kind = 294, // wavy plum .attrs = &[_]Attr{ Attr{ .kind = 175, .n = 3 }, // pale tomato Attr{ .kind = 295, .n = 4 }, // shiny green Attr{ .kind = 296, .n = 2 }, // dull crimson }, }, Rule{ .kind = 295, // shiny green .attrs = &[_]Attr{ Attr{ .kind = 236, .n = 1 }, // faded teal Attr{ .kind = 276, .n = 4 }, // wavy tomato Attr{ .kind = 335, .n = 2 }, // striped crimson Attr{ .kind = 470, .n = 3 }, // muted maroon }, }, Rule{ .kind = 296, // dull crimson .attrs = &[_]Attr{ Attr{ .kind = 178, .n = 3 }, // shiny coral Attr{ .kind = 268, .n = 4 }, // dotted beige Attr{ .kind = 272, .n = 5 }, // dim coral Attr{ .kind = 398, .n = 2 }, // faded tomato }, }, Rule{ .kind = 297, // bright blue .attrs = &[_]Attr{ Attr{ .kind = 117, .n = 5 }, // drab black Attr{ .kind = 298, .n = 5 }, // dull lavender }, }, Rule{ .kind = 298, // dull lavender .attrs = &[_]Attr{ Attr{ .kind = 193, .n = 4 }, // pale salmon Attr{ .kind = 466, .n = 4 }, // mirrored brown }, }, Rule{ .kind = 299, // posh tomato .attrs = &[_]Attr{ Attr{ .kind = 66, .n = 4 }, // bright aqua Attr{ .kind = 180, .n = 4 }, // clear turquoise Attr{ .kind = 300, .n = 2 }, // dim chartreuse }, }, Rule{ .kind = 300, // dim chartreuse .attrs = &[_]Attr{ Attr{ .kind = 151, .n = 2 }, // mirrored olive Attr{ .kind = 182, .n = 3 }, // shiny gold }, }, Rule{ .kind = 301, // dotted lavender .attrs = &[_]Attr{ Attr{ .kind = 96, .n = 4 }, // wavy red }, }, Rule{ .kind = 302, // posh magenta .attrs = &[_]Attr{ Attr{ .kind = 43, .n = 3 }, // light olive }, }, Rule{ .kind = 303, // pale green .attrs = &[_]Attr{ Attr{ .kind = 109, .n = 3 }, // pale crimson Attr{ .kind = 276, .n = 3 }, // wavy tomato Attr{ .kind = 304, .n = 4 }, // plaid indigo }, }, Rule{ .kind = 304, // plaid indigo .attrs = &[_]Attr{ Attr{ .kind = 59, .n = 1 }, // dotted violet Attr{ .kind = 151, .n = 1 }, // mirrored olive Attr{ .kind = 164, .n = 3 }, // mirrored tan Attr{ .kind = 200, .n = 1 }, // striped turquoise }, }, Rule{ .kind = 305, // dull fuchsia .attrs = &[_]Attr{ Attr{ .kind = 1, .n = 2 }, // clear gold }, }, Rule{ .kind = 306, // light plum .attrs = &[_]Attr{ Attr{ .kind = 78, .n = 5 }, // dark plum Attr{ .kind = 235, .n = 1 }, // striped white }, }, Rule{ .kind = 307, // dotted olive .attrs = &[_]Attr{ Attr{ .kind = 308, .n = 5 }, // vibrant maroon }, }, Rule{ .kind = 308, // vibrant maroon .attrs = &[_]Attr{ Attr{ .kind = 1, .n = 1 }, // clear gold Attr{ .kind = 347, .n = 3 }, // bright purple }, }, Rule{ .kind = 309, // dim yellow .attrs = &[_]Attr{ Attr{ .kind = 277, .n = 2 }, // dull green }, }, Rule{ .kind = 310, // bright indigo .attrs = &[_]Attr{ Attr{ .kind = 161, .n = 4 }, // light salmon Attr{ .kind = 173, .n = 3 }, // light gold Attr{ .kind = 211, .n = 4 }, // plaid olive Attr{ .kind = 311, .n = 3 }, // wavy lavender }, }, Rule{ .kind = 311, // wavy lavender .attrs = &[_]Attr{ Attr{ .kind = 100, .n = 4 }, // clear blue Attr{ .kind = 115, .n = 1 }, // dim gold Attr{ .kind = 146, .n = 3 }, // faded magenta Attr{ .kind = 179, .n = 1 }, // plaid crimson }, }, Rule{ .kind = 312, // dark bronze .attrs = &[_]Attr{ Attr{ .kind = 37, .n = 1 }, // vibrant cyan Attr{ .kind = 156, .n = 4 }, // shiny chartreuse Attr{ .kind = 413, .n = 1 }, // muted yellow Attr{ .kind = 502, .n = 1 }, // pale white }, }, Rule{ .kind = 313, // striped aqua .attrs = &[_]Attr{ Attr{ .kind = 25, .n = 1 }, // dark silver Attr{ .kind = 103, .n = 5 }, // dark olive Attr{ .kind = 314, .n = 4 }, // dull tomato Attr{ .kind = 315, .n = 5 }, // pale gold }, }, Rule{ .kind = 314, // dull tomato .attrs = &[_]Attr{ Attr{ .kind = 76, .n = 2 }, // muted lavender Attr{ .kind = 98, .n = 2 }, // light maroon Attr{ .kind = 195, .n = 1 }, // faded brown Attr{ .kind = 328, .n = 1 }, // muted red }, }, Rule{ .kind = 315, // pale gold .attrs = &[_]Attr{ Attr{ .kind = 161, .n = 5 }, // light salmon Attr{ .kind = 197, .n = 3 }, // drab plum }, }, Rule{ .kind = 316, // dull maroon .attrs = &[_]Attr{ Attr{ .kind = 317, .n = 2 }, // pale teal Attr{ .kind = 318, .n = 5 }, // light coral Attr{ .kind = 319, .n = 4 }, // light magenta }, }, Rule{ .kind = 317, // pale teal .attrs = &[_]Attr{ Attr{ .kind = 66, .n = 5 }, // bright aqua Attr{ .kind = 100, .n = 4 }, // clear blue Attr{ .kind = 125, .n = 3 }, // light turquoise Attr{ .kind = 358, .n = 3 }, // shiny purple }, }, Rule{ .kind = 318, // light coral .attrs = &[_]Attr{ Attr{ .kind = 152, .n = 5 }, // drab beige Attr{ .kind = 186, .n = 4 }, // clear purple }, }, Rule{ .kind = 319, // light magenta .attrs = &[_]Attr{ Attr{ .kind = 59, .n = 5 }, // dotted violet Attr{ .kind = 194, .n = 3 }, // bright red Attr{ .kind = 396, .n = 2 }, // faded crimson Attr{ .kind = 397, .n = 5 }, // mirrored turquoise }, }, Rule{ .kind = 320, // muted tan .attrs = &[_]Attr{ Attr{ .kind = 114, .n = 2 }, // dim plum Attr{ .kind = 304, .n = 4 }, // plaid indigo Attr{ .kind = 321, .n = 2 }, // clear yellow Attr{ .kind = 322, .n = 2 }, // dotted crimson }, }, Rule{ .kind = 321, // clear yellow .attrs = &[_]Attr{ Attr{ .kind = 28, .n = 2 }, // clear orange }, }, Rule{ .kind = 322, // dotted crimson .attrs = &[_]Attr{ Attr{ .kind = 11, .n = 3 }, // striped gold Attr{ .kind = 377, .n = 3 }, // dark yellow }, }, Rule{ .kind = 323, // dull beige .attrs = &[_]Attr{ Attr{ .kind = 70, .n = 1 }, // striped brown Attr{ .kind = 79, .n = 3 }, // posh yellow Attr{ .kind = 93, .n = 4 }, // wavy green Attr{ .kind = 324, .n = 3 }, // posh cyan }, }, Rule{ .kind = 324, // posh cyan .attrs = &[_]Attr{ Attr{ .kind = 233, .n = 5 }, // dark coral Attr{ .kind = 237, .n = 1 }, // faded yellow }, }, Rule{ .kind = 325, // drab red .attrs = &[_]Attr{ Attr{ .kind = 87, .n = 2 }, // posh brown Attr{ .kind = 278, .n = 2 }, // wavy lime }, }, Rule{ .kind = 326, // drab gray .attrs = &[_]Attr{ Attr{ .kind = 133, .n = 1 }, // mirrored yellow Attr{ .kind = 327, .n = 2 }, // plaid turquoise }, }, Rule{ .kind = 327, // plaid turquoise .attrs = &[_]Attr{ Attr{ .kind = 92, .n = 5 }, // muted tomato Attr{ .kind = 347, .n = 1 }, // bright purple }, }, Rule{ .kind = 328, // muted red .attrs = &[_]Attr{ Attr{ .kind = 80, .n = 5 }, // dull plum Attr{ .kind = 135, .n = 1 }, // shiny silver Attr{ .kind = 329, .n = 2 }, // pale coral }, }, Rule{ .kind = 329, // pale coral .attrs = &[_]Attr{ Attr{ .kind = 49, .n = 4 }, // dotted red Attr{ .kind = 131, .n = 1 }, // plaid salmon }, }, Rule{ .kind = 330, // drab green .attrs = &[_]Attr{ Attr{ .kind = 100, .n = 5 }, // clear blue Attr{ .kind = 162, .n = 4 }, // shiny brown Attr{ .kind = 232, .n = 3 }, // striped yellow }, }, Rule{ .kind = 331, // dim gray .attrs = &[_]Attr{ Attr{ .kind = 114, .n = 1 }, // dim plum Attr{ .kind = 246, .n = 5 }, // wavy maroon Attr{ .kind = 332, .n = 3 }, // light tomato }, }, Rule{ .kind = 332, // light tomato .attrs = &[_]Attr{ Attr{ .kind = 75, .n = 4 }, // dark maroon Attr{ .kind = 124, .n = 2 }, // pale red Attr{ .kind = 127, .n = 4 }, // dark red }, }, Rule{ .kind = 333, // dark white .attrs = &[_]Attr{ Attr{ .kind = 283, .n = 3 }, // light brown }, }, Rule{ .kind = 334, // pale maroon .attrs = &[_]Attr{ Attr{ .kind = 33, .n = 2 }, // clear gray Attr{ .kind = 125, .n = 4 }, // light turquoise Attr{ .kind = 143, .n = 5 }, // vibrant bronze Attr{ .kind = 438, .n = 4 }, // bright tan }, }, Rule{ .kind = 335, // striped crimson .attrs = &[_]Attr{ Attr{ .kind = 318, .n = 5 }, // light coral }, }, Rule{ .kind = 336, // vibrant gold .attrs = &[_]Attr{ Attr{ .kind = 40, .n = 4 }, // dull orange Attr{ .kind = 51, .n = 2 }, // striped fuchsia Attr{ .kind = 144, .n = 2 }, // striped blue }, }, Rule{ .kind = 337, // muted lime .attrs = &[_]Attr{ Attr{ .kind = 102, .n = 1 }, // muted beige Attr{ .kind = 338, .n = 4 }, // drab cyan }, }, Rule{ .kind = 338, // drab cyan .attrs = &[_]Attr{ Attr{ .kind = 96, .n = 5 }, // wavy red Attr{ .kind = 100, .n = 5 }, // clear blue Attr{ .kind = 438, .n = 4 }, // bright tan }, }, Rule{ .kind = 339, // drab purple .attrs = &[_]Attr{ Attr{ .kind = 340, .n = 4 }, // dotted gold }, }, Rule{ .kind = 340, // dotted gold .attrs = &[_]Attr{ Attr{ .kind = 61, .n = 1 }, // wavy yellow Attr{ .kind = 103, .n = 4 }, // dark olive }, }, Rule{ .kind = 341, // dotted green .attrs = &[_]Attr{ Attr{ .kind = 342, .n = 1 }, // wavy blue }, }, Rule{ .kind = 342, // wavy blue .attrs = &[_]Attr{ Attr{ .kind = 61, .n = 4 }, // wavy yellow }, }, Rule{ .kind = 343, // bright black .attrs = &[_]Attr{ Attr{ .kind = 186, .n = 1 }, // clear purple Attr{ .kind = 282, .n = 4 }, // wavy chartreuse }, }, Rule{ .kind = 344, // bright chartreuse .attrs = &[_]Attr{}, }, Rule{ .kind = 345, // dim purple .attrs = &[_]Attr{ Attr{ .kind = 66, .n = 3 }, // bright aqua Attr{ .kind = 101, .n = 4 }, // mirrored fuchsia Attr{ .kind = 299, .n = 5 }, // posh tomato Attr{ .kind = 346, .n = 2 }, // faded lavender }, }, Rule{ .kind = 346, // faded lavender .attrs = &[_]Attr{ Attr{ .kind = 128, .n = 5 }, // shiny lime }, }, Rule{ .kind = 347, // bright purple .attrs = &[_]Attr{ Attr{ .kind = 103, .n = 1 }, // dark olive Attr{ .kind = 210, .n = 1 }, // faded violet Attr{ .kind = 403, .n = 4 }, // mirrored cyan }, }, Rule{ .kind = 348, // pale fuchsia .attrs = &[_]Attr{ Attr{ .kind = 349, .n = 2 }, // dark magenta }, }, Rule{ .kind = 349, // dark magenta .attrs = &[_]Attr{ Attr{ .kind = 125, .n = 1 }, // light turquoise Attr{ .kind = 410, .n = 4 }, // plaid brown }, }, Rule{ .kind = 350, // bright salmon .attrs = &[_]Attr{ Attr{ .kind = 106, .n = 4 }, // wavy beige Attr{ .kind = 351, .n = 2 }, // vibrant coral Attr{ .kind = 352, .n = 3 }, // bright gray Attr{ .kind = 353, .n = 1 }, // faded green }, }, Rule{ .kind = 351, // vibrant coral .attrs = &[_]Attr{ Attr{ .kind = 22, .n = 1 }, // striped orange Attr{ .kind = 47, .n = 3 }, // shiny turquoise }, }, Rule{ .kind = 352, // bright gray .attrs = &[_]Attr{ Attr{ .kind = 59, .n = 3 }, // dotted violet Attr{ .kind = 95, .n = 1 }, // dull purple Attr{ .kind = 192, .n = 2 }, // dull chartreuse }, }, Rule{ .kind = 353, // faded green .attrs = &[_]Attr{ Attr{ .kind = 177, .n = 1 }, // posh white Attr{ .kind = 322, .n = 1 }, // dotted crimson }, }, Rule{ .kind = 354, // bright magenta .attrs = &[_]Attr{ Attr{ .kind = 51, .n = 1 }, // striped fuchsia Attr{ .kind = 191, .n = 1 }, // mirrored maroon Attr{ .kind = 355, .n = 3 }, // vibrant crimson }, }, Rule{ .kind = 355, // vibrant crimson .attrs = &[_]Attr{ Attr{ .kind = 99, .n = 4 }, // vibrant orange Attr{ .kind = 449, .n = 4 }, // shiny plum }, }, Rule{ .kind = 356, // striped red .attrs = &[_]Attr{ Attr{ .kind = 233, .n = 3 }, // dark coral Attr{ .kind = 289, .n = 3 }, // plaid black Attr{ .kind = 357, .n = 4 }, // vibrant indigo }, }, Rule{ .kind = 357, // vibrant indigo .attrs = &[_]Attr{ Attr{ .kind = 23, .n = 3 }, // bright fuchsia Attr{ .kind = 66, .n = 3 }, // bright aqua Attr{ .kind = 140, .n = 2 }, // muted gold Attr{ .kind = 194, .n = 1 }, // bright red }, }, Rule{ .kind = 358, // shiny purple .attrs = &[_]Attr{ Attr{ .kind = 75, .n = 5 }, // dark maroon Attr{ .kind = 100, .n = 1 }, // clear blue Attr{ .kind = 141, .n = 4 }, // striped chartreuse }, }, Rule{ .kind = 359, // muted gray .attrs = &[_]Attr{ Attr{ .kind = 62, .n = 4 }, // plaid red Attr{ .kind = 351, .n = 3 }, // vibrant coral Attr{ .kind = 360, .n = 4 }, // dark teal }, }, Rule{ .kind = 360, // dark teal .attrs = &[_]Attr{ Attr{ .kind = 47, .n = 4 }, // shiny turquoise Attr{ .kind = 353, .n = 5 }, // faded green }, }, Rule{ .kind = 361, // faded indigo .attrs = &[_]Attr{ Attr{ .kind = 526, .n = 1 }, // dull brown }, }, Rule{ .kind = 362, // mirrored orange .attrs = &[_]Attr{ Attr{ .kind = 92, .n = 4 }, // muted tomato }, }, Rule{ .kind = 363, // clear red .attrs = &[_]Attr{ Attr{ .kind = 41, .n = 3 }, // plaid tomato Attr{ .kind = 364, .n = 2 }, // dark violet }, }, Rule{ .kind = 364, // dark violet .attrs = &[_]Attr{ Attr{ .kind = 11, .n = 3 }, // striped gold Attr{ .kind = 143, .n = 1 }, // vibrant bronze Attr{ .kind = 194, .n = 4 }, // bright red }, }, Rule{ .kind = 365, // striped purple .attrs = &[_]Attr{ Attr{ .kind = 250, .n = 3 }, // posh lavender }, }, Rule{ .kind = 366, // plaid violet .attrs = &[_]Attr{ Attr{ .kind = 367, .n = 5 }, // mirrored gold }, }, Rule{ .kind = 367, // mirrored gold .attrs = &[_]Attr{ Attr{ .kind = 145, .n = 2 }, // dark orange }, }, Rule{ .kind = 368, // shiny crimson .attrs = &[_]Attr{ Attr{ .kind = 343, .n = 4 }, // bright black Attr{ .kind = 369, .n = 2 }, // wavy purple Attr{ .kind = 370, .n = 1 }, // dark crimson }, }, Rule{ .kind = 369, // wavy purple .attrs = &[_]Attr{ Attr{ .kind = 15, .n = 3 }, // faded olive Attr{ .kind = 115, .n = 5 }, // dim gold Attr{ .kind = 395, .n = 2 }, // vibrant brown Attr{ .kind = 526, .n = 1 }, // dull brown }, }, Rule{ .kind = 370, // dark crimson .attrs = &[_]Attr{ Attr{ .kind = 201, .n = 2 }, // vibrant black Attr{ .kind = 259, .n = 4 }, // clear violet Attr{ .kind = 357, .n = 2 }, // vibrant indigo }, }, Rule{ .kind = 371, // posh gold .attrs = &[_]Attr{ Attr{ .kind = 372, .n = 4 }, // dull yellow }, }, Rule{ .kind = 372, // dull yellow .attrs = &[_]Attr{ Attr{ .kind = 135, .n = 4 }, // shiny silver Attr{ .kind = 208, .n = 1 }, // mirrored lavender Attr{ .kind = 298, .n = 2 }, // dull lavender Attr{ .kind = 442, .n = 2 }, // posh maroon }, }, Rule{ .kind = 373, // dim crimson .attrs = &[_]Attr{ Attr{ .kind = 374, .n = 3 }, // drab white }, }, Rule{ .kind = 374, // drab white .attrs = &[_]Attr{ Attr{ .kind = 213, .n = 5 }, // shiny yellow }, }, Rule{ .kind = 375, // posh red .attrs = &[_]Attr{ Attr{ .kind = 277, .n = 3 }, // dull green Attr{ .kind = 356, .n = 1 }, // striped red }, }, Rule{ .kind = 376, // drab turquoise .attrs = &[_]Attr{ Attr{ .kind = 40, .n = 3 }, // dull orange Attr{ .kind = 265, .n = 5 }, // clear beige Attr{ .kind = 295, .n = 3 }, // shiny green Attr{ .kind = 377, .n = 5 }, // dark yellow }, }, Rule{ .kind = 377, // dark yellow .attrs = &[_]Attr{ Attr{ .kind = 110, .n = 3 }, // dull lime Attr{ .kind = 152, .n = 4 }, // drab beige Attr{ .kind = 182, .n = 4 }, // shiny gold Attr{ .kind = 410, .n = 1 }, // plaid brown }, }, Rule{ .kind = 378, // light bronze .attrs = &[_]Attr{ Attr{ .kind = 183, .n = 1 }, // dim orange Attr{ .kind = 193, .n = 2 }, // pale salmon Attr{ .kind = 230, .n = 3 }, // plaid magenta Attr{ .kind = 379, .n = 2 }, // vibrant blue }, }, Rule{ .kind = 379, // vibrant blue .attrs = &[_]Attr{ Attr{ .kind = 148, .n = 2 }, // drab silver Attr{ .kind = 213, .n = 5 }, // shiny yellow Attr{ .kind = 291, .n = 1 }, // faded lime Attr{ .kind = 412, .n = 1 }, // faded black }, }, Rule{ .kind = 380, // dotted cyan .attrs = &[_]Attr{ Attr{ .kind = 381, .n = 1 }, // faded purple Attr{ .kind = 382, .n = 4 }, // drab crimson }, }, Rule{ .kind = 381, // faded purple .attrs = &[_]Attr{ Attr{ .kind = 106, .n = 3 }, // wavy beige Attr{ .kind = 135, .n = 5 }, // shiny silver }, }, Rule{ .kind = 382, // drab crimson .attrs = &[_]Attr{ Attr{ .kind = 123, .n = 1 }, // light tan Attr{ .kind = 277, .n = 3 }, // dull green Attr{ .kind = 342, .n = 1 }, // wavy blue }, }, Rule{ .kind = 383, // drab fuchsia .attrs = &[_]Attr{ Attr{ .kind = 131, .n = 4 }, // plaid salmon }, }, Rule{ .kind = 384, // clear maroon .attrs = &[_]Attr{ Attr{ .kind = 103, .n = 1 }, // dark olive Attr{ .kind = 385, .n = 4 }, // dotted white Attr{ .kind = 386, .n = 1 }, // dull red }, }, Rule{ .kind = 385, // dotted white .attrs = &[_]Attr{ Attr{ .kind = 87, .n = 2 }, // posh brown }, }, Rule{ .kind = 386, // dull red .attrs = &[_]Attr{ Attr{ .kind = 91, .n = 4 }, // mirrored plum Attr{ .kind = 342, .n = 5 }, // wavy blue Attr{ .kind = 387, .n = 3 }, // light green Attr{ .kind = 554, .n = 3 }, // mirrored purple }, }, Rule{ .kind = 387, // light green .attrs = &[_]Attr{ Attr{ .kind = 308, .n = 5 }, // vibrant maroon Attr{ .kind = 402, .n = 3 }, // muted indigo }, }, Rule{ .kind = 388, // wavy aqua .attrs = &[_]Attr{ Attr{ .kind = 179, .n = 4 }, // plaid crimson Attr{ .kind = 389, .n = 5 }, // dull tan }, }, Rule{ .kind = 389, // dull tan .attrs = &[_]Attr{ Attr{ .kind = 143, .n = 1 }, // vibrant bronze Attr{ .kind = 322, .n = 3 }, // dotted crimson Attr{ .kind = 374, .n = 1 }, // drab white }, }, Rule{ .kind = 390, // pale beige .attrs = &[_]Attr{ Attr{ .kind = 113, .n = 5 }, // striped beige Attr{ .kind = 346, .n = 2 }, // faded lavender Attr{ .kind = 391, .n = 1 }, // light teal }, }, Rule{ .kind = 391, // light teal .attrs = &[_]Attr{ Attr{ .kind = 196, .n = 5 }, // dark lavender }, }, Rule{ .kind = 392, // light aqua .attrs = &[_]Attr{ Attr{ .kind = 237, .n = 3 }, // faded yellow }, }, Rule{ .kind = 393, // dim tan .attrs = &[_]Attr{ Attr{ .kind = 277, .n = 1 }, // dull green Attr{ .kind = 333, .n = 5 }, // dark white Attr{ .kind = 394, .n = 5 }, // light orange }, }, Rule{ .kind = 394, // light orange .attrs = &[_]Attr{ Attr{ .kind = 115, .n = 1 }, // dim gold Attr{ .kind = 446, .n = 2 }, // dark gold }, }, Rule{ .kind = 395, // vibrant brown .attrs = &[_]Attr{ Attr{ .kind = 41, .n = 2 }, // plaid tomato }, }, Rule{ .kind = 396, // faded crimson .attrs = &[_]Attr{ Attr{ .kind = 153, .n = 5 }, // bright maroon }, }, Rule{ .kind = 397, // mirrored turquoise .attrs = &[_]Attr{ Attr{ .kind = 25, .n = 4 }, // dark silver Attr{ .kind = 77, .n = 4 }, // bright cyan Attr{ .kind = 125, .n = 1 }, // light turquoise Attr{ .kind = 318, .n = 3 }, // light coral }, }, Rule{ .kind = 398, // faded tomato .attrs = &[_]Attr{ Attr{ .kind = 106, .n = 2 }, // wavy beige }, }, Rule{ .kind = 399, // wavy black .attrs = &[_]Attr{ Attr{ .kind = 363, .n = 3 }, // clear red Attr{ .kind = 400, .n = 3 }, // dark cyan }, }, Rule{ .kind = 400, // dark cyan .attrs = &[_]Attr{ Attr{ .kind = 264, .n = 4 }, // faded beige }, }, Rule{ .kind = 401, // dim brown .attrs = &[_]Attr{ Attr{ .kind = 236, .n = 4 }, // faded teal }, }, Rule{ .kind = 402, // muted indigo .attrs = &[_]Attr{ Attr{ .kind = 8, .n = 5 }, // faded salmon Attr{ .kind = 91, .n = 1 }, // mirrored plum Attr{ .kind = 275, .n = 5 }, // pale gray }, }, Rule{ .kind = 403, // mirrored cyan .attrs = &[_]Attr{ Attr{ .kind = 23, .n = 3 }, // bright fuchsia Attr{ .kind = 68, .n = 4 }, // striped tan Attr{ .kind = 236, .n = 5 }, // faded teal Attr{ .kind = 251, .n = 3 }, // striped bronze }, }, Rule{ .kind = 404, // vibrant tan .attrs = &[_]Attr{ Attr{ .kind = 234, .n = 1 }, // dim silver Attr{ .kind = 405, .n = 2 }, // clear white }, }, Rule{ .kind = 405, // clear white .attrs = &[_]Attr{ Attr{ .kind = 15, .n = 4 }, // faded olive }, }, Rule{ .kind = 406, // shiny white .attrs = &[_]Attr{ Attr{ .kind = 0, .n = 1 }, // drab tan Attr{ .kind = 3, .n = 2 }, // faded gold Attr{ .kind = 224, .n = 1 }, // dotted bronze }, }, Rule{ .kind = 407, // drab orange .attrs = &[_]Attr{ Attr{ .kind = 193, .n = 3 }, // pale salmon Attr{ .kind = 310, .n = 3 }, // bright indigo }, }, Rule{ .kind = 408, // striped green .attrs = &[_]Attr{ Attr{ .kind = 249, .n = 2 }, // bright tomato Attr{ .kind = 334, .n = 4 }, // pale maroon Attr{ .kind = 409, .n = 4 }, // muted brown }, }, Rule{ .kind = 409, // muted brown .attrs = &[_]Attr{ Attr{ .kind = 196, .n = 2 }, // dark lavender Attr{ .kind = 300, .n = 2 }, // dim chartreuse }, }, Rule{ .kind = 410, // plaid brown .attrs = &[_]Attr{ Attr{ .kind = 68, .n = 5 }, // striped tan Attr{ .kind = 75, .n = 2 }, // dark maroon Attr{ .kind = 110, .n = 3 }, // dull lime Attr{ .kind = 300, .n = 4 }, // dim chartreuse }, }, Rule{ .kind = 411, // drab yellow .attrs = &[_]Attr{ Attr{ .kind = 91, .n = 1 }, // mirrored plum Attr{ .kind = 256, .n = 1 }, // plaid green Attr{ .kind = 412, .n = 5 }, // faded black }, }, Rule{ .kind = 412, // faded black .attrs = &[_]Attr{ Attr{ .kind = 279, .n = 1 }, // faded aqua Attr{ .kind = 352, .n = 3 }, // bright gray }, }, Rule{ .kind = 413, // muted yellow .attrs = &[_]Attr{ Attr{ .kind = 25, .n = 3 }, // dark silver Attr{ .kind = 125, .n = 4 }, // light turquoise Attr{ .kind = 128, .n = 2 }, // shiny lime Attr{ .kind = 235, .n = 2 }, // striped white }, }, Rule{ .kind = 414, // dark aqua .attrs = &[_]Attr{ Attr{ .kind = 415, .n = 4 }, // dull blue Attr{ .kind = 416, .n = 5 }, // mirrored white }, }, Rule{ .kind = 415, // dull blue .attrs = &[_]Attr{ Attr{ .kind = 32, .n = 1 }, // dotted silver Attr{ .kind = 45, .n = 3 }, // muted salmon Attr{ .kind = 236, .n = 2 }, // faded teal Attr{ .kind = 522, .n = 2 }, // vibrant beige }, }, Rule{ .kind = 416, // mirrored white .attrs = &[_]Attr{ Attr{ .kind = 64, .n = 4 }, // bright brown Attr{ .kind = 435, .n = 2 }, // striped silver }, }, Rule{ .kind = 417, // muted blue .attrs = &[_]Attr{ Attr{ .kind = 101, .n = 3 }, // mirrored fuchsia }, }, Rule{ .kind = 418, // muted coral .attrs = &[_]Attr{ Attr{ .kind = 58, .n = 2 }, // wavy crimson Attr{ .kind = 302, .n = 5 }, // posh magenta Attr{ .kind = 395, .n = 4 }, // vibrant brown Attr{ .kind = 419, .n = 1 }, // pale plum }, }, Rule{ .kind = 419, // pale plum .attrs = &[_]Attr{ Attr{ .kind = 0, .n = 1 }, // drab tan Attr{ .kind = 179, .n = 3 }, // plaid crimson Attr{ .kind = 245, .n = 5 }, // mirrored teal }, }, Rule{ .kind = 420, // muted green .attrs = &[_]Attr{ Attr{ .kind = 109, .n = 4 }, // pale crimson Attr{ .kind = 159, .n = 4 }, // shiny gray Attr{ .kind = 232, .n = 4 }, // striped yellow Attr{ .kind = 350, .n = 1 }, // bright salmon }, }, Rule{ .kind = 421, // dim violet .attrs = &[_]Attr{ Attr{ .kind = 204, .n = 3 }, // dull violet Attr{ .kind = 422, .n = 4 }, // faded tan Attr{ .kind = 423, .n = 1 }, // light yellow }, }, Rule{ .kind = 422, // faded tan .attrs = &[_]Attr{ Attr{ .kind = 77, .n = 3 }, // bright cyan Attr{ .kind = 152, .n = 4 }, // drab beige Attr{ .kind = 200, .n = 3 }, // striped turquoise Attr{ .kind = 276, .n = 1 }, // wavy tomato }, }, Rule{ .kind = 423, // light yellow .attrs = &[_]Attr{ Attr{ .kind = 1, .n = 4 }, // clear gold Attr{ .kind = 49, .n = 1 }, // dotted red Attr{ .kind = 110, .n = 3 }, // dull lime Attr{ .kind = 510, .n = 3 }, // pale turquoise }, }, Rule{ .kind = 424, // clear fuchsia .attrs = &[_]Attr{ Attr{ .kind = 197, .n = 2 }, // drab plum }, }, Rule{ .kind = 425, // posh violet .attrs = &[_]Attr{ Attr{ .kind = 192, .n = 5 }, // dull chartreuse Attr{ .kind = 318, .n = 2 }, // light coral Attr{ .kind = 403, .n = 5 }, // mirrored cyan }, }, Rule{ .kind = 426, // dotted fuchsia .attrs = &[_]Attr{ Attr{ .kind = 111, .n = 3 }, // wavy silver Attr{ .kind = 335, .n = 5 }, // striped crimson Attr{ .kind = 404, .n = 2 }, // vibrant tan }, }, Rule{ .kind = 427, // dotted plum .attrs = &[_]Attr{ Attr{ .kind = 54, .n = 2 }, // light gray Attr{ .kind = 175, .n = 2 }, // pale tomato Attr{ .kind = 296, .n = 5 }, // dull crimson Attr{ .kind = 428, .n = 2 }, // posh green }, }, Rule{ .kind = 428, // posh green .attrs = &[_]Attr{ Attr{ .kind = 26, .n = 5 }, // dim maroon Attr{ .kind = 208, .n = 5 }, // mirrored lavender Attr{ .kind = 311, .n = 1 }, // wavy lavender Attr{ .kind = 462, .n = 2 }, // faded gray }, }, Rule{ .kind = 429, // vibrant magenta .attrs = &[_]Attr{ Attr{ .kind = 268, .n = 4 }, // dotted beige }, }, Rule{ .kind = 430, // drab maroon .attrs = &[_]Attr{ Attr{ .kind = 116, .n = 1 }, // dull cyan Attr{ .kind = 431, .n = 1 }, // drab coral Attr{ .kind = 432, .n = 1 }, // dotted tan }, }, Rule{ .kind = 431, // drab coral .attrs = &[_]Attr{ Attr{ .kind = 11, .n = 4 }, // striped gold Attr{ .kind = 200, .n = 5 }, // striped turquoise Attr{ .kind = 397, .n = 4 }, // mirrored turquoise Attr{ .kind = 435, .n = 5 }, // striped silver }, }, Rule{ .kind = 432, // dotted tan .attrs = &[_]Attr{ Attr{ .kind = 48, .n = 1 }, // muted purple Attr{ .kind = 89, .n = 3 }, // drab lavender Attr{ .kind = 312, .n = 1 }, // dark bronze Attr{ .kind = 357, .n = 5 }, // vibrant indigo }, }, Rule{ .kind = 433, // striped cyan .attrs = &[_]Attr{ Attr{ .kind = 182, .n = 4 }, // shiny gold Attr{ .kind = 335, .n = 5 }, // striped crimson Attr{ .kind = 356, .n = 5 }, // striped red }, }, Rule{ .kind = 434, // pale silver .attrs = &[_]Attr{ Attr{ .kind = 274, .n = 5 }, // vibrant red Attr{ .kind = 363, .n = 4 }, // clear red }, }, Rule{ .kind = 435, // striped silver .attrs = &[_]Attr{ Attr{ .kind = 83, .n = 5 }, // posh fuchsia Attr{ .kind = 170, .n = 4 }, // faded cyan }, }, Rule{ .kind = 436, // vibrant chartreuse .attrs = &[_]Attr{ Attr{ .kind = 135, .n = 1 }, // shiny silver Attr{ .kind = 292, .n = 5 }, // striped gray Attr{ .kind = 437, .n = 1 }, // bright turquoise }, }, Rule{ .kind = 437, // bright turquoise .attrs = &[_]Attr{ Attr{ .kind = 166, .n = 5 }, // drab bronze }, }, Rule{ .kind = 438, // bright tan .attrs = &[_]Attr{ Attr{ .kind = 100, .n = 5 }, // clear blue Attr{ .kind = 127, .n = 2 }, // dark red Attr{ .kind = 153, .n = 3 }, // bright maroon }, }, Rule{ .kind = 439, // mirrored green .attrs = &[_]Attr{ Attr{ .kind = 96, .n = 5 }, // wavy red Attr{ .kind = 127, .n = 4 }, // dark red Attr{ .kind = 235, .n = 1 }, // striped white Attr{ .kind = 264, .n = 3 }, // faded beige }, }, Rule{ .kind = 440, // dim white .attrs = &[_]Attr{ Attr{ .kind = 11, .n = 3 }, // striped gold Attr{ .kind = 113, .n = 4 }, // striped beige Attr{ .kind = 417, .n = 2 }, // muted blue Attr{ .kind = 441, .n = 4 }, // muted white }, }, Rule{ .kind = 441, // muted white .attrs = &[_]Attr{ Attr{ .kind = 51, .n = 4 }, // striped fuchsia }, }, Rule{ .kind = 442, // posh maroon .attrs = &[_]Attr{ Attr{ .kind = 49, .n = 2 }, // dotted red Attr{ .kind = 322, .n = 5 }, // dotted crimson }, }, Rule{ .kind = 443, // posh chartreuse .attrs = &[_]Attr{ Attr{ .kind = 47, .n = 4 }, // shiny turquoise Attr{ .kind = 98, .n = 5 }, // light maroon Attr{ .kind = 134, .n = 5 }, // posh gray Attr{ .kind = 209, .n = 2 }, // mirrored blue }, }, Rule{ .kind = 444, // pale lavender .attrs = &[_]Attr{ Attr{ .kind = 10, .n = 1 }, // dull gray Attr{ .kind = 139, .n = 3 }, // posh silver Attr{ .kind = 414, .n = 3 }, // dark aqua }, }, Rule{ .kind = 445, // light blue .attrs = &[_]Attr{ Attr{ .kind = 101, .n = 2 }, // mirrored fuchsia Attr{ .kind = 139, .n = 1 }, // posh silver Attr{ .kind = 165, .n = 3 }, // pale tan Attr{ .kind = 430, .n = 4 }, // drab maroon }, }, Rule{ .kind = 446, // dark gold .attrs = &[_]Attr{ Attr{ .kind = 26, .n = 2 }, // dim maroon Attr{ .kind = 151, .n = 4 }, // mirrored olive Attr{ .kind = 174, .n = 1 }, // posh olive Attr{ .kind = 487, .n = 1 }, // muted turquoise }, }, Rule{ .kind = 447, // shiny fuchsia .attrs = &[_]Attr{ Attr{ .kind = 327, .n = 1 }, // plaid turquoise Attr{ .kind = 448, .n = 5 }, // muted orange Attr{ .kind = 449, .n = 2 }, // shiny plum }, }, Rule{ .kind = 448, // muted orange .attrs = &[_]Attr{ Attr{ .kind = 305, .n = 5 }, // dull fuchsia }, }, Rule{ .kind = 449, // shiny plum .attrs = &[_]Attr{ Attr{ .kind = 314, .n = 3 }, // dull tomato }, }, Rule{ .kind = 450, // posh blue .attrs = &[_]Attr{ Attr{ .kind = 302, .n = 5 }, // posh magenta Attr{ .kind = 451, .n = 1 }, // wavy magenta }, }, Rule{ .kind = 451, // wavy magenta .attrs = &[_]Attr{ Attr{ .kind = 64, .n = 5 }, // bright brown Attr{ .kind = 68, .n = 5 }, // striped tan Attr{ .kind = 402, .n = 1 }, // muted indigo }, }, Rule{ .kind = 452, // striped salmon .attrs = &[_]Attr{ Attr{ .kind = 178, .n = 5 }, // shiny coral Attr{ .kind = 184, .n = 1 }, // dark tomato Attr{ .kind = 453, .n = 5 }, // plaid silver }, }, Rule{ .kind = 453, // plaid silver .attrs = &[_]Attr{ Attr{ .kind = 93, .n = 2 }, // wavy green Attr{ .kind = 173, .n = 2 }, // light gold Attr{ .kind = 324, .n = 4 }, // posh cyan }, }, Rule{ .kind = 454, // dim bronze .attrs = &[_]Attr{ Attr{ .kind = 298, .n = 4 }, // dull lavender }, }, Rule{ .kind = 455, // dim tomato .attrs = &[_]Attr{ Attr{ .kind = 169, .n = 5 }, // dim beige Attr{ .kind = 456, .n = 5 }, // wavy indigo Attr{ .kind = 457, .n = 3 }, // wavy gold }, }, Rule{ .kind = 456, // wavy indigo .attrs = &[_]Attr{ Attr{ .kind = 104, .n = 1 }, // clear tan Attr{ .kind = 181, .n = 5 }, // vibrant green }, }, Rule{ .kind = 457, // wavy gold .attrs = &[_]Attr{ Attr{ .kind = 49, .n = 4 }, // dotted red Attr{ .kind = 197, .n = 3 }, // drab plum Attr{ .kind = 347, .n = 4 }, // bright purple Attr{ .kind = 496, .n = 5 }, // faded red }, }, Rule{ .kind = 458, // vibrant white .attrs = &[_]Attr{ Attr{ .kind = 139, .n = 2 }, // posh silver Attr{ .kind = 316, .n = 5 }, // dull maroon Attr{ .kind = 459, .n = 5 }, // dim magenta }, }, Rule{ .kind = 459, // dim magenta .attrs = &[_]Attr{ Attr{ .kind = 145, .n = 1 }, // dark orange Attr{ .kind = 514, .n = 2 }, // dark salmon }, }, Rule{ .kind = 460, // dark blue .attrs = &[_]Attr{ Attr{ .kind = 59, .n = 4 }, // dotted violet Attr{ .kind = 194, .n = 4 }, // bright red Attr{ .kind = 408, .n = 4 }, // striped green }, }, Rule{ .kind = 461, // plaid gray .attrs = &[_]Attr{ Attr{ .kind = 90, .n = 3 }, // dark brown Attr{ .kind = 462, .n = 4 }, // faded gray }, }, Rule{ .kind = 462, // faded gray .attrs = &[_]Attr{ Attr{ .kind = 66, .n = 1 }, // bright aqua Attr{ .kind = 114, .n = 5 }, // dim plum }, }, Rule{ .kind = 463, // faded maroon .attrs = &[_]Attr{ Attr{ .kind = 33, .n = 5 }, // clear gray Attr{ .kind = 110, .n = 5 }, // dull lime Attr{ .kind = 152, .n = 5 }, // drab beige Attr{ .kind = 289, .n = 1 }, // plaid black }, }, Rule{ .kind = 464, // clear crimson .attrs = &[_]Attr{ Attr{ .kind = 196, .n = 2 }, // dark lavender Attr{ .kind = 465, .n = 4 }, // muted aqua }, }, Rule{ .kind = 465, // muted aqua .attrs = &[_]Attr{ Attr{ .kind = 145, .n = 1 }, // dark orange Attr{ .kind = 192, .n = 4 }, // dull chartreuse Attr{ .kind = 198, .n = 5 }, // vibrant gray Attr{ .kind = 546, .n = 3 }, // bright plum }, }, Rule{ .kind = 466, // mirrored brown .attrs = &[_]Attr{ Attr{ .kind = 85, .n = 5 }, // striped lavender Attr{ .kind = 127, .n = 4 }, // dark red Attr{ .kind = 152, .n = 3 }, // drab beige Attr{ .kind = 195, .n = 4 }, // faded brown }, }, Rule{ .kind = 467, // dotted purple .attrs = &[_]Attr{ Attr{ .kind = 31, .n = 3 }, // shiny indigo Attr{ .kind = 135, .n = 5 }, // shiny silver Attr{ .kind = 416, .n = 2 }, // mirrored white }, }, Rule{ .kind = 468, // dotted indigo .attrs = &[_]Attr{ Attr{ .kind = 192, .n = 3 }, // dull chartreuse Attr{ .kind = 332, .n = 2 }, // light tomato Attr{ .kind = 352, .n = 3 }, // bright gray Attr{ .kind = 421, .n = 4 }, // dim violet }, }, Rule{ .kind = 469, // wavy orange .attrs = &[_]Attr{ Attr{ .kind = 145, .n = 5 }, // dark orange Attr{ .kind = 470, .n = 4 }, // muted maroon Attr{ .kind = 471, .n = 5 }, // clear salmon }, }, Rule{ .kind = 470, // muted maroon .attrs = &[_]Attr{ Attr{ .kind = 83, .n = 2 }, // posh fuchsia Attr{ .kind = 132, .n = 1 }, // shiny orange Attr{ .kind = 197, .n = 1 }, // drab plum }, }, Rule{ .kind = 471, // clear salmon .attrs = &[_]Attr{ Attr{ .kind = 528, .n = 3 }, // clear aqua }, }, Rule{ .kind = 472, // wavy turquoise .attrs = &[_]Attr{ Attr{ .kind = 140, .n = 4 }, // muted gold }, }, Rule{ .kind = 473, // drab salmon .attrs = &[_]Attr{ Attr{ .kind = 253, .n = 4 }, // posh aqua Attr{ .kind = 323, .n = 1 }, // dull beige Attr{ .kind = 474, .n = 4 }, // dotted yellow }, }, Rule{ .kind = 474, // dotted yellow .attrs = &[_]Attr{ Attr{ .kind = 153, .n = 3 }, // bright maroon Attr{ .kind = 230, .n = 2 }, // plaid magenta Attr{ .kind = 279, .n = 3 }, // faded aqua Attr{ .kind = 488, .n = 4 }, // dim lime }, }, Rule{ .kind = 475, // mirrored aqua .attrs = &[_]Attr{ Attr{ .kind = 174, .n = 4 }, // posh olive Attr{ .kind = 271, .n = 4 }, // drab blue Attr{ .kind = 476, .n = 5 }, // shiny bronze }, }, Rule{ .kind = 476, // shiny bronze .attrs = &[_]Attr{ Attr{ .kind = 45, .n = 4 }, // muted salmon Attr{ .kind = 73, .n = 3 }, // mirrored silver Attr{ .kind = 261, .n = 5 }, // plaid lime Attr{ .kind = 463, .n = 1 }, // faded maroon }, }, Rule{ .kind = 477, // wavy tan .attrs = &[_]Attr{ Attr{ .kind = 93, .n = 2 }, // wavy green Attr{ .kind = 195, .n = 5 }, // faded brown }, }, Rule{ .kind = 478, // mirrored magenta .attrs = &[_]Attr{ Attr{ .kind = 259, .n = 1 }, // clear violet Attr{ .kind = 289, .n = 1 }, // plaid black }, }, Rule{ .kind = 479, // mirrored lime .attrs = &[_]Attr{ Attr{ .kind = 262, .n = 5 }, // striped teal Attr{ .kind = 270, .n = 1 }, // clear cyan Attr{ .kind = 334, .n = 3 }, // pale maroon }, }, Rule{ .kind = 480, // clear magenta .attrs = &[_]Attr{ Attr{ .kind = 28, .n = 3 }, // clear orange Attr{ .kind = 137, .n = 1 }, // plaid plum }, }, Rule{ .kind = 481, // light red .attrs = &[_]Attr{ Attr{ .kind = 91, .n = 5 }, // mirrored plum Attr{ .kind = 198, .n = 5 }, // vibrant gray Attr{ .kind = 201, .n = 3 }, // vibrant black }, }, Rule{ .kind = 482, // light white .attrs = &[_]Attr{ Attr{ .kind = 152, .n = 2 }, // drab beige }, }, Rule{ .kind = 483, // vibrant salmon .attrs = &[_]Attr{ Attr{ .kind = 146, .n = 1 }, // faded magenta Attr{ .kind = 264, .n = 3 }, // faded beige }, }, Rule{ .kind = 484, // dotted magenta .attrs = &[_]Attr{ Attr{ .kind = 240, .n = 2 }, // dark purple }, }, Rule{ .kind = 485, // striped violet .attrs = &[_]Attr{ Attr{ .kind = 101, .n = 3 }, // mirrored fuchsia Attr{ .kind = 131, .n = 5 }, // plaid salmon Attr{ .kind = 396, .n = 2 }, // faded crimson Attr{ .kind = 403, .n = 4 }, // mirrored cyan }, }, Rule{ .kind = 486, // muted magenta .attrs = &[_]Attr{ Attr{ .kind = 151, .n = 5 }, // mirrored olive Attr{ .kind = 276, .n = 4 }, // wavy tomato Attr{ .kind = 289, .n = 2 }, // plaid black Attr{ .kind = 487, .n = 2 }, // muted turquoise }, }, Rule{ .kind = 487, // muted turquoise .attrs = &[_]Attr{ Attr{ .kind = 41, .n = 1 }, // plaid tomato }, }, Rule{ .kind = 488, // dim lime .attrs = &[_]Attr{ Attr{ .kind = 43, .n = 2 }, // light olive Attr{ .kind = 106, .n = 1 }, // wavy beige }, }, Rule{ .kind = 489, // dotted maroon .attrs = &[_]Attr{ Attr{ .kind = 181, .n = 3 }, // vibrant green Attr{ .kind = 490, .n = 2 }, // light purple }, }, Rule{ .kind = 490, // light purple .attrs = &[_]Attr{ Attr{ .kind = 81, .n = 4 }, // shiny blue Attr{ .kind = 141, .n = 5 }, // striped chartreuse Attr{ .kind = 278, .n = 4 }, // wavy lime Attr{ .kind = 387, .n = 3 }, // light green }, }, Rule{ .kind = 491, // mirrored beige .attrs = &[_]Attr{ Attr{ .kind = 250, .n = 1 }, // posh lavender Attr{ .kind = 321, .n = 4 }, // clear yellow Attr{ .kind = 362, .n = 3 }, // mirrored orange }, }, Rule{ .kind = 492, // vibrant lavender .attrs = &[_]Attr{ Attr{ .kind = 192, .n = 3 }, // dull chartreuse Attr{ .kind = 194, .n = 2 }, // bright red }, }, Rule{ .kind = 493, // pale brown .attrs = &[_]Attr{ Attr{ .kind = 96, .n = 5 }, // wavy red Attr{ .kind = 274, .n = 4 }, // vibrant red }, }, Rule{ .kind = 494, // vibrant fuchsia .attrs = &[_]Attr{ Attr{ .kind = 73, .n = 3 }, // mirrored silver }, }, Rule{ .kind = 495, // dull silver .attrs = &[_]Attr{ Attr{ .kind = 159, .n = 5 }, // shiny gray }, }, Rule{ .kind = 496, // faded red .attrs = &[_]Attr{ Attr{ .kind = 68, .n = 2 }, // striped tan }, }, Rule{ .kind = 497, // faded coral .attrs = &[_]Attr{ Attr{ .kind = 48, .n = 5 }, // muted purple Attr{ .kind = 144, .n = 1 }, // striped blue Attr{ .kind = 358, .n = 2 }, // shiny purple }, }, Rule{ .kind = 498, // shiny cyan .attrs = &[_]Attr{ Attr{ .kind = 126, .n = 4 }, // mirrored chartreuse Attr{ .kind = 183, .n = 2 }, // dim orange Attr{ .kind = 186, .n = 3 }, // clear purple Attr{ .kind = 360, .n = 1 }, // dark teal }, }, Rule{ .kind = 499, // dim cyan .attrs = &[_]Attr{ Attr{ .kind = 482, .n = 5 }, // light white }, }, Rule{ .kind = 500, // dotted tomato .attrs = &[_]Attr{ Attr{ .kind = 261, .n = 5 }, // plaid lime Attr{ .kind = 342, .n = 1 }, // wavy blue Attr{ .kind = 449, .n = 4 }, // shiny plum }, }, Rule{ .kind = 501, // muted cyan .attrs = &[_]Attr{ Attr{ .kind = 65, .n = 1 }, // posh coral Attr{ .kind = 153, .n = 2 }, // bright maroon Attr{ .kind = 378, .n = 3 }, // light bronze Attr{ .kind = 455, .n = 1 }, // dim tomato }, }, Rule{ .kind = 502, // pale white .attrs = &[_]Attr{ Attr{ .kind = 334, .n = 3 }, // pale maroon }, }, Rule{ .kind = 503, // shiny beige .attrs = &[_]Attr{ Attr{ .kind = 279, .n = 4 }, // faded aqua }, }, Rule{ .kind = 504, // plaid maroon .attrs = &[_]Attr{ Attr{ .kind = 107, .n = 3 }, // pale blue Attr{ .kind = 276, .n = 4 }, // wavy tomato Attr{ .kind = 505, .n = 2 }, // dotted coral }, }, Rule{ .kind = 505, // dotted coral .attrs = &[_]Attr{ Attr{ .kind = 146, .n = 2 }, // faded magenta Attr{ .kind = 222, .n = 1 }, // clear brown Attr{ .kind = 486, .n = 4 }, // muted magenta }, }, Rule{ .kind = 506, // light cyan .attrs = &[_]Attr{ Attr{ .kind = 451, .n = 1 }, // wavy magenta Attr{ .kind = 507, .n = 5 }, // shiny tomato }, }, Rule{ .kind = 507, // shiny tomato .attrs = &[_]Attr{ Attr{ .kind = 82, .n = 5 }, // pale violet }, }, Rule{ .kind = 508, // faded silver .attrs = &[_]Attr{ Attr{ .kind = 7, .n = 2 }, // dim salmon Attr{ .kind = 251, .n = 4 }, // striped bronze Attr{ .kind = 329, .n = 3 }, // pale coral }, }, Rule{ .kind = 509, // posh tan .attrs = &[_]Attr{ Attr{ .kind = 300, .n = 1 }, // dim chartreuse Attr{ .kind = 327, .n = 2 }, // plaid turquoise Attr{ .kind = 421, .n = 3 }, // dim violet Attr{ .kind = 510, .n = 4 }, // pale turquoise }, }, Rule{ .kind = 510, // pale turquoise .attrs = &[_]Attr{ Attr{ .kind = 127, .n = 2 }, // dark red Attr{ .kind = 272, .n = 4 }, // dim coral Attr{ .kind = 398, .n = 5 }, // faded tomato Attr{ .kind = 544, .n = 3 }, // plaid white }, }, Rule{ .kind = 511, // muted silver .attrs = &[_]Attr{ Attr{ .kind = 322, .n = 2 }, // dotted crimson Attr{ .kind = 409, .n = 3 }, // muted brown }, }, Rule{ .kind = 512, // clear coral .attrs = &[_]Attr{ Attr{ .kind = 33, .n = 2 }, // clear gray Attr{ .kind = 220, .n = 3 }, // pale chartreuse Attr{ .kind = 267, .n = 3 }, // posh plum Attr{ .kind = 402, .n = 4 }, // muted indigo }, }, Rule{ .kind = 513, // shiny tan .attrs = &[_]Attr{ Attr{ .kind = 43, .n = 1 }, // light olive }, }, Rule{ .kind = 514, // dark salmon .attrs = &[_]Attr{ Attr{ .kind = 21, .n = 2 }, // dull teal Attr{ .kind = 370, .n = 5 }, // dark crimson Attr{ .kind = 465, .n = 1 }, // muted aqua }, }, Rule{ .kind = 515, // plaid orange .attrs = &[_]Attr{ Attr{ .kind = 26, .n = 5 }, // dim maroon Attr{ .kind = 80, .n = 3 }, // dull plum Attr{ .kind = 463, .n = 2 }, // faded maroon }, }, Rule{ .kind = 516, // dark indigo .attrs = &[_]Attr{ Attr{ .kind = 97, .n = 4 }, // light beige Attr{ .kind = 257, .n = 1 }, // clear tomato Attr{ .kind = 365, .n = 5 }, // striped purple }, }, Rule{ .kind = 517, // dotted brown .attrs = &[_]Attr{ Attr{ .kind = 115, .n = 3 }, // dim gold Attr{ .kind = 168, .n = 3 }, // drab chartreuse }, }, Rule{ .kind = 518, // wavy gray .attrs = &[_]Attr{ Attr{ .kind = 0, .n = 2 }, // drab tan }, }, Rule{ .kind = 519, // posh crimson .attrs = &[_]Attr{ Attr{ .kind = 12, .n = 4 }, // vibrant yellow Attr{ .kind = 25, .n = 5 }, // dark silver Attr{ .kind = 134, .n = 1 }, // posh gray }, }, Rule{ .kind = 520, // drab tomato .attrs = &[_]Attr{ Attr{ .kind = 276, .n = 5 }, // wavy tomato Attr{ .kind = 371, .n = 5 }, // posh gold }, }, Rule{ .kind = 521, // bright crimson .attrs = &[_]Attr{ Attr{ .kind = 8, .n = 4 }, // faded salmon }, }, Rule{ .kind = 522, // vibrant beige .attrs = &[_]Attr{ Attr{ .kind = 249, .n = 1 }, // bright tomato Attr{ .kind = 325, .n = 2 }, // drab red Attr{ .kind = 403, .n = 4 }, // mirrored cyan }, }, Rule{ .kind = 523, // dim teal .attrs = &[_]Attr{ Attr{ .kind = 86, .n = 5 }, // vibrant silver }, }, Rule{ .kind = 524, // striped olive .attrs = &[_]Attr{ Attr{ .kind = 19, .n = 1 }, // clear teal Attr{ .kind = 421, .n = 5 }, // dim violet }, }, Rule{ .kind = 525, // light black .attrs = &[_]Attr{ Attr{ .kind = 107, .n = 2 }, // pale blue Attr{ .kind = 265, .n = 2 }, // clear beige Attr{ .kind = 491, .n = 5 }, // mirrored beige }, }, Rule{ .kind = 526, // dull brown .attrs = &[_]Attr{ Attr{ .kind = 239, .n = 4 }, // bright violet Attr{ .kind = 264, .n = 2 }, // faded beige Attr{ .kind = 299, .n = 4 }, // posh tomato }, }, Rule{ .kind = 527, // shiny salmon .attrs = &[_]Attr{ Attr{ .kind = 33, .n = 1 }, // clear gray Attr{ .kind = 173, .n = 3 }, // light gold Attr{ .kind = 439, .n = 2 }, // mirrored green }, }, Rule{ .kind = 528, // clear aqua .attrs = &[_]Attr{ Attr{ .kind = 141, .n = 5 }, // striped chartreuse Attr{ .kind = 176, .n = 1 }, // pale bronze Attr{ .kind = 332, .n = 1 }, // light tomato }, }, Rule{ .kind = 529, // clear lime .attrs = &[_]Attr{ Attr{ .kind = 196, .n = 5 }, // dark lavender Attr{ .kind = 317, .n = 2 }, // pale teal Attr{ .kind = 351, .n = 2 }, // vibrant coral }, }, Rule{ .kind = 530, // dull indigo .attrs = &[_]Attr{ Attr{ .kind = 8, .n = 1 }, // faded salmon Attr{ .kind = 37, .n = 3 }, // vibrant cyan }, }, Rule{ .kind = 531, // shiny aqua .attrs = &[_]Attr{ Attr{ .kind = 36, .n = 1 }, // shiny teal Attr{ .kind = 66, .n = 4 }, // bright aqua Attr{ .kind = 118, .n = 2 }, // dark green Attr{ .kind = 532, .n = 4 }, // wavy cyan }, }, Rule{ .kind = 532, // wavy cyan .attrs = &[_]Attr{ Attr{ .kind = 88, .n = 5 }, // clear indigo Attr{ .kind = 363, .n = 2 }, // clear red }, }, Rule{ .kind = 533, // dull bronze .attrs = &[_]Attr{ Attr{ .kind = 250, .n = 2 }, // posh lavender Attr{ .kind = 383, .n = 5 }, // drab fuchsia Attr{ .kind = 390, .n = 3 }, // pale beige }, }, Rule{ .kind = 534, // striped coral .attrs = &[_]Attr{ Attr{ .kind = 419, .n = 2 }, // pale plum Attr{ .kind = 470, .n = 5 }, // muted maroon }, }, Rule{ .kind = 535, // vibrant tomato .attrs = &[_]Attr{ Attr{ .kind = 67, .n = 4 }, // drab lime Attr{ .kind = 164, .n = 3 }, // mirrored tan Attr{ .kind = 272, .n = 3 }, // dim coral }, }, Rule{ .kind = 536, // dotted chartreuse .attrs = &[_]Attr{ Attr{ .kind = 20, .n = 4 }, // dim red Attr{ .kind = 152, .n = 3 }, // drab beige Attr{ .kind = 526, .n = 2 }, // dull brown }, }, Rule{ .kind = 537, // dull turquoise .attrs = &[_]Attr{ Attr{ .kind = 103, .n = 2 }, // dark olive Attr{ .kind = 180, .n = 3 }, // clear turquoise Attr{ .kind = 233, .n = 3 }, // dark coral Attr{ .kind = 358, .n = 3 }, // shiny purple }, }, Rule{ .kind = 538, // plaid lavender .attrs = &[_]Attr{ Attr{ .kind = 123, .n = 1 }, // light tan Attr{ .kind = 158, .n = 2 }, // muted crimson Attr{ .kind = 185, .n = 4 }, // vibrant violet Attr{ .kind = 435, .n = 3 }, // striped silver }, }, Rule{ .kind = 539, // wavy white .attrs = &[_]Attr{ Attr{ .kind = 9, .n = 3 }, // dim turquoise }, }, Rule{ .kind = 540, // dim blue .attrs = &[_]Attr{ Attr{ .kind = 153, .n = 3 }, // bright maroon }, }, Rule{ .kind = 541, // shiny red .attrs = &[_]Attr{ Attr{ .kind = 262, .n = 5 }, // striped teal Attr{ .kind = 364, .n = 1 }, // dark violet Attr{ .kind = 465, .n = 4 }, // muted aqua }, }, Rule{ .kind = 542, // pale aqua .attrs = &[_]Attr{ Attr{ .kind = 204, .n = 3 }, // dull violet Attr{ .kind = 360, .n = 3 }, // dark teal }, }, Rule{ .kind = 543, // clear chartreuse .attrs = &[_]Attr{ Attr{ .kind = 438, .n = 2 }, // bright tan }, }, Rule{ .kind = 544, // plaid white .attrs = &[_]Attr{ Attr{ .kind = 131, .n = 3 }, // plaid salmon Attr{ .kind = 289, .n = 4 }, // plaid black Attr{ .kind = 482, .n = 4 }, // light white }, }, Rule{ .kind = 545, // dotted blue .attrs = &[_]Attr{ Attr{ .kind = 263, .n = 4 }, // bright lavender }, }, Rule{ .kind = 546, // bright plum .attrs = &[_]Attr{ Attr{ .kind = 69, .n = 2 }, // muted violet Attr{ .kind = 103, .n = 3 }, // dark olive Attr{ .kind = 131, .n = 5 }, // plaid salmon Attr{ .kind = 240, .n = 1 }, // dark purple }, }, Rule{ .kind = 547, // pale black .attrs = &[_]Attr{ Attr{ .kind = 78, .n = 1 }, // dark plum }, }, Rule{ .kind = 548, // striped magenta .attrs = &[_]Attr{ Attr{ .kind = 174, .n = 2 }, // posh olive Attr{ .kind = 178, .n = 5 }, // shiny coral Attr{ .kind = 305, .n = 3 }, // dull fuchsia Attr{ .kind = 389, .n = 1 }, // dull tan }, }, Rule{ .kind = 549, // light crimson .attrs = &[_]Attr{ Attr{ .kind = 95, .n = 4 }, // dull purple }, }, Rule{ .kind = 550, // dark tan .attrs = &[_]Attr{ Attr{ .kind = 0, .n = 4 }, // drab tan Attr{ .kind = 118, .n = 4 }, // dark green Attr{ .kind = 162, .n = 1 }, // shiny brown Attr{ .kind = 271, .n = 3 }, // drab blue }, }, Rule{ .kind = 551, // drab olive .attrs = &[_]Attr{ Attr{ .kind = 12, .n = 5 }, // vibrant yellow }, }, Rule{ .kind = 552, // wavy violet .attrs = &[_]Attr{ Attr{ .kind = 178, .n = 5 }, // shiny coral }, }, Rule{ .kind = 553, // faded white .attrs = &[_]Attr{ Attr{ .kind = 119, .n = 4 }, // vibrant teal Attr{ .kind = 387, .n = 4 }, // light green Attr{ .kind = 399, .n = 5 }, // wavy black }, }, Rule{ .kind = 554, // mirrored purple .attrs = &[_]Attr{ Attr{ .kind = 120, .n = 2 }, // clear green Attr{ .kind = 330, .n = 5 }, // drab green }, }, Rule{ .kind = 555, // mirrored gray .attrs = &[_]Attr{ Attr{ .kind = 87, .n = 1 }, // posh brown Attr{ .kind = 374, .n = 3 }, // drab white }, }, Rule{ .kind = 556, // dark gray .attrs = &[_]Attr{ Attr{ .kind = 12, .n = 5 }, // vibrant yellow Attr{ .kind = 196, .n = 1 }, // dark lavender Attr{ .kind = 250, .n = 4 }, // posh lavender Attr{ .kind = 551, .n = 1 }, // drab olive }, }, Rule{ .kind = 557, // pale indigo .attrs = &[_]Attr{ Attr{ .kind = 73, .n = 4 }, // mirrored silver }, }, Rule{ .kind = 558, // bright white .attrs = &[_]Attr{ Attr{ .kind = 480, .n = 4 }, // clear magenta }, }, Rule{ .kind = 559, // striped lime .attrs = &[_]Attr{ Attr{ .kind = 394, .n = 1 }, // light orange Attr{ .kind = 488, .n = 3 }, // dim lime }, }, Rule{ .kind = 560, // mirrored tomato .attrs = &[_]Attr{ Attr{ .kind = 453, .n = 3 }, // plaid silver }, }, Rule{ .kind = 561, // wavy coral .attrs = &[_]Attr{ Attr{ .kind = 61, .n = 4 }, // wavy yellow Attr{ .kind = 553, .n = 4 }, // faded white }, }, Rule{ .kind = 562, // dim fuchsia .attrs = &[_]Attr{ Attr{ .kind = 220, .n = 3 }, // pale chartreuse Attr{ .kind = 282, .n = 2 }, // wavy chartreuse Attr{ .kind = 515, .n = 3 }, // plaid orange }, }, Rule{ .kind = 563, // light lime .attrs = &[_]Attr{ Attr{ .kind = 70, .n = 2 }, // striped brown Attr{ .kind = 288, .n = 5 }, // bright green Attr{ .kind = 328, .n = 3 }, // muted red Attr{ .kind = 519, .n = 1 }, // posh crimson }, }, Rule{ .kind = 564, // mirrored red .attrs = &[_]Attr{ Attr{ .kind = 9, .n = 5 }, // dim turquoise Attr{ .kind = 106, .n = 4 }, // wavy beige }, }, Rule{ .kind = 565, // light chartreuse .attrs = &[_]Attr{ Attr{ .kind = 61, .n = 4 }, // wavy yellow Attr{ .kind = 423, .n = 2 }, // light yellow }, }, Rule{ .kind = 566, // wavy salmon .attrs = &[_]Attr{ Attr{ .kind = 87, .n = 4 }, // posh brown Attr{ .kind = 283, .n = 1 }, // light brown Attr{ .kind = 307, .n = 3 }, // dotted olive Attr{ .kind = 394, .n = 5 }, // light orange }, }, Rule{ .kind = 567, // faded chartreuse .attrs = &[_]Attr{ Attr{ .kind = 73, .n = 4 }, // mirrored silver Attr{ .kind = 223, .n = 5 }, // dark beige Attr{ .kind = 438, .n = 4 }, // bright tan Attr{ .kind = 489, .n = 4 }, // dotted maroon }, }, Rule{ .kind = 568, // posh beige .attrs = &[_]Attr{ Attr{ .kind = 523, .n = 4 }, // dim teal }, }, Rule{ .kind = 569, // vibrant aqua .attrs = &[_]Attr{ Attr{ .kind = 46, .n = 1 }, // muted black Attr{ .kind = 444, .n = 5 }, // pale lavender Attr{ .kind = 499, .n = 3 }, // dim cyan }, }, Rule{ .kind = 570, // wavy olive .attrs = &[_]Attr{ Attr{ .kind = 147, .n = 2 }, // bright silver Attr{ .kind = 203, .n = 3 }, // shiny olive }, }, Rule{ .kind = 571, // dotted gray .attrs = &[_]Attr{ Attr{ .kind = 280, .n = 5 }, // vibrant olive Attr{ .kind = 383, .n = 4 }, // drab fuchsia }, }, Rule{ .kind = 572, // mirrored salmon .attrs = &[_]Attr{ Attr{ .kind = 357, .n = 5 }, // vibrant indigo Attr{ .kind = 361, .n = 5 }, // faded indigo }, }, Rule{ .kind = 573, // faded orange .attrs = &[_]Attr{ Attr{ .kind = 69, .n = 5 }, // muted violet Attr{ .kind = 70, .n = 5 }, // striped brown }, }, Rule{ .kind = 574, // pale orange .attrs = &[_]Attr{ Attr{ .kind = 198, .n = 4 }, // vibrant gray }, }, Rule{ .kind = 575, // posh teal .attrs = &[_]Attr{ Attr{ .kind = 142, .n = 4 }, // dotted salmon Attr{ .kind = 364, .n = 1 }, // dark violet }, }, Rule{ .kind = 576, // bright teal .attrs = &[_]Attr{ Attr{ .kind = 374, .n = 5 }, // drab white }, }, Rule{ .kind = 577, // striped maroon .attrs = &[_]Attr{ Attr{ .kind = 14, .n = 4 }, // light lavender Attr{ .kind = 525, .n = 2 }, // light black Attr{ .kind = 578, .n = 4 }, // drab violet }, }, Rule{ .kind = 578, // drab violet .attrs = &[_]Attr{ Attr{ .kind = 28, .n = 2 }, // clear orange Attr{ .kind = 126, .n = 2 }, // mirrored chartreuse Attr{ .kind = 264, .n = 1 }, // faded beige Attr{ .kind = 268, .n = 4 }, // dotted beige }, }, Rule{ .kind = 579, // pale magenta .attrs = &[_]Attr{ Attr{ .kind = 275, .n = 4 }, // pale gray }, }, Rule{ .kind = 580, // shiny maroon .attrs = &[_]Attr{ Attr{ .kind = 67, .n = 2 }, // drab lime Attr{ .kind = 192, .n = 2 }, // dull chartreuse Attr{ .kind = 522, .n = 2 }, // vibrant beige Attr{ .kind = 581, .n = 4 }, // vibrant turquoise }, }, Rule{ .kind = 581, // vibrant turquoise .attrs = &[_]Attr{ Attr{ .kind = 16, .n = 3 }, // plaid cyan Attr{ .kind = 279, .n = 3 }, // faded aqua Attr{ .kind = 421, .n = 3 }, // dim violet Attr{ .kind = 511, .n = 2 }, // muted silver }, }, Rule{ .kind = 582, // dark black .attrs = &[_]Attr{ Attr{ .kind = 58, .n = 1 }, // wavy crimson Attr{ .kind = 150, .n = 3 }, // plaid tan Attr{ .kind = 333, .n = 1 }, // dark white Attr{ .kind = 356, .n = 5 }, // striped red }, }, Rule{ .kind = 583, // faded plum .attrs = &[_]Attr{ Attr{ .kind = 151, .n = 5 }, // mirrored olive Attr{ .kind = 214, .n = 4 }, // light silver }, }, Rule{ .kind = 584, // dotted black .attrs = &[_]Attr{ Attr{ .kind = 29, .n = 1 }, // muted olive }, }, Rule{ .kind = 585, // mirrored coral .attrs = &[_]Attr{ Attr{ .kind = 239, .n = 4 }, // bright violet Attr{ .kind = 253, .n = 2 }, // posh aqua Attr{ .kind = 514, .n = 2 }, // dark salmon }, }, Rule{ .kind = 586, // muted chartreuse .attrs = &[_]Attr{ Attr{ .kind = 134, .n = 4 }, // posh gray Attr{ .kind = 339, .n = 5 }, // drab purple }, }, Rule{ .kind = 587, // clear plum .attrs = &[_]Attr{ Attr{ .kind = 115, .n = 3 }, // dim gold Attr{ .kind = 127, .n = 3 }, // dark red Attr{ .kind = 129, .n = 2 }, // posh black Attr{ .kind = 285, .n = 5 }, // plaid beige }, }, Rule{ .kind = 588, // faded bronze .attrs = &[_]Attr{ Attr{ .kind = 161, .n = 2 }, // light salmon }, }, Rule{ .kind = 589, // bright lime .attrs = &[_]Attr{ Attr{ .kind = 236, .n = 3 }, // faded teal Attr{ .kind = 396, .n = 1 }, // faded crimson Attr{ .kind = 505, .n = 5 }, // dotted coral }, }, Rule{ .kind = 590, // dull olive .attrs = &[_]Attr{ Attr{ .kind = 337, .n = 5 }, // muted lime Attr{ .kind = 377, .n = 3 }, // dark yellow }, }, Rule{ .kind = 591, // posh indigo .attrs = &[_]Attr{ Attr{ .kind = 473, .n = 5 }, // drab salmon }, }, Rule{ .kind = 592, // striped plum .attrs = &[_]Attr{ Attr{ .kind = 360, .n = 4 }, // dark teal Attr{ .kind = 440, .n = 5 }, // dim white }, }, Rule{ .kind = 593, // dim lavender .attrs = &[_]Attr{ Attr{ .kind = 246, .n = 3 }, // wavy maroon Attr{ .kind = 251, .n = 5 }, // striped bronze }, }, }, .names = &[_][]const u8{ "drab tan", "clear gold", "vibrant lime", "faded gold", "plaid aqua", "clear black", "pale lime", "dim salmon", "faded salmon", "dim turquoise", "dull gray", "striped gold", "vibrant yellow", "light fuchsia", "light lavender", "faded olive", "plaid cyan", "striped tomato", "drab gold", "clear teal", "dim red", "dull teal", "striped orange", "bright fuchsia", "plaid chartreuse", "dark silver", "dim maroon", "shiny violet", "clear orange", "muted olive", "dark chartreuse", "shiny indigo", "dotted silver", "clear gray", "dotted lime", "dark turquoise", "shiny teal", "vibrant cyan", "drab magenta", "bright yellow", "dull orange", "plaid tomato", "dull black", "light olive", "posh turquoise", "muted salmon", "muted black", "shiny turquoise", "muted purple", "dotted red", "striped black", "striped fuchsia", "drab indigo", "drab brown", "light gray", "dull coral", "pale purple", "mirrored black", "wavy crimson", "dotted violet", "clear lavender", "wavy yellow", "plaid red", "bright coral", "bright brown", "posh coral", "bright aqua", "drab lime", "striped tan", "muted violet", "striped brown", "dark lime", "wavy bronze", "mirrored silver", "dim black", "dark maroon", "muted lavender", "bright cyan", "dark plum", "posh yellow", "dull plum", "shiny blue", "pale violet", "posh fuchsia", "mirrored bronze", "striped lavender", "vibrant silver", "posh brown", "clear indigo", "drab lavender", "dark brown", "mirrored plum", "muted tomato", "wavy green", "posh bronze", "dull purple", "wavy red", "light beige", "light maroon", "vibrant orange", "clear blue", "mirrored fuchsia", "muted beige", "dark olive", "clear tan", "posh lime", "wavy beige", "pale blue", "dull aqua", "pale crimson", "dull lime", "wavy silver", "pale cyan", "striped beige", "dim plum", "dim gold", "dull cyan", "drab black", "dark green", "vibrant teal", "clear green", "light violet", "bright beige", "light tan", "pale red", "light turquoise", "mirrored chartreuse", "dark red", "shiny lime", "posh black", "posh salmon", "plaid salmon", "shiny orange", "mirrored yellow", "posh gray", "shiny silver", "dark fuchsia", "plaid plum", "bright bronze", "posh silver", "muted gold", "striped chartreuse", "dotted salmon", "vibrant bronze", "striped blue", "dark orange", "faded magenta", "bright silver", "drab silver", "posh orange", "plaid tan", "mirrored olive", "drab beige", "bright maroon", "muted bronze", "wavy brown", "shiny chartreuse", "dull white", "muted crimson", "shiny gray", "dotted orange", "light salmon", "shiny brown", "clear olive", "mirrored tan", "pale tan", "drab bronze", "drab teal", "drab chartreuse", "dim beige", "faded cyan", "plaid fuchsia", "pale yellow", "light gold", "posh olive", "pale tomato", "pale bronze", "posh white", "shiny coral", "plaid crimson", "clear turquoise", "vibrant green", "shiny gold", "dim orange", "dark tomato", "vibrant violet", "clear purple", "muted fuchsia", "bright olive", "bright gold", "mirrored indigo", "mirrored maroon", "dull chartreuse", "pale salmon", "bright red", "faded brown", "dark lavender", "drab plum", "vibrant gray", "plaid coral", "striped turquoise", "vibrant black", "shiny black", "shiny olive", "dull violet", "vibrant plum", "muted plum", "shiny lavender", "mirrored lavender", "mirrored blue", "faded violet", "plaid olive", "dotted aqua", "shiny yellow", "light silver", "bright orange", "dim indigo", "pale olive", "light indigo", "faded turquoise", "pale chartreuse", "wavy teal", "clear brown", "dark beige", "dotted bronze", "posh purple", "clear silver", "mirrored crimson", "plaid bronze", "wavy fuchsia", "plaid magenta", "drab aqua", "striped yellow", "dark coral", "dim silver", "striped white", "faded teal", "faded yellow", "faded blue", "bright violet", "dark purple", "dim aqua", "clear bronze", "dull magenta", "shiny magenta", "mirrored teal", "wavy maroon", "plaid teal", "plaid yellow", "bright tomato", "posh lavender", "striped bronze", "vibrant purple", "posh aqua", "muted teal", "faded fuchsia", "plaid green", "clear tomato", "dim olive", "clear violet", "plaid gold", "plaid lime", "striped teal", "bright lavender", "faded beige", "clear beige", "dotted turquoise", "posh plum", "dotted beige", "striped indigo", "clear cyan", "drab blue", "dim coral", "plaid purple", "vibrant red", "pale gray", "wavy tomato", "dull green", "wavy lime", "faded aqua", "vibrant olive", "mirrored violet", "wavy chartreuse", "light brown", "plaid blue", "plaid beige", "dotted teal", "dim green", "bright green", "plaid black", "dull salmon", "faded lime", "striped gray", "dull gold", "wavy plum", "shiny green", "dull crimson", "bright blue", "dull lavender", "posh tomato", "dim chartreuse", "dotted lavender", "posh magenta", "pale green", "plaid indigo", "dull fuchsia", "light plum", "dotted olive", "vibrant maroon", "dim yellow", "bright indigo", "wavy lavender", "dark bronze", "striped aqua", "dull tomato", "pale gold", "dull maroon", "pale teal", "light coral", "light magenta", "muted tan", "clear yellow", "dotted crimson", "dull beige", "posh cyan", "drab red", "drab gray", "plaid turquoise", "muted red", "pale coral", "drab green", "dim gray", "light tomato", "dark white", "pale maroon", "striped crimson", "vibrant gold", "muted lime", "drab cyan", "drab purple", "dotted gold", "dotted green", "wavy blue", "bright black", "bright chartreuse", "dim purple", "faded lavender", "bright purple", "pale fuchsia", "dark magenta", "bright salmon", "vibrant coral", "bright gray", "faded green", "bright magenta", "vibrant crimson", "striped red", "vibrant indigo", "shiny purple", "muted gray", "dark teal", "faded indigo", "mirrored orange", "clear red", "dark violet", "striped purple", "plaid violet", "mirrored gold", "shiny crimson", "wavy purple", "dark crimson", "posh gold", "dull yellow", "dim crimson", "drab white", "posh red", "drab turquoise", "dark yellow", "light bronze", "vibrant blue", "dotted cyan", "faded purple", "drab crimson", "drab fuchsia", "clear maroon", "dotted white", "dull red", "light green", "wavy aqua", "dull tan", "pale beige", "light teal", "light aqua", "dim tan", "light orange", "vibrant brown", "faded crimson", "mirrored turquoise", "faded tomato", "wavy black", "dark cyan", "dim brown", "muted indigo", "mirrored cyan", "vibrant tan", "clear white", "shiny white", "drab orange", "striped green", "muted brown", "plaid brown", "drab yellow", "faded black", "muted yellow", "dark aqua", "dull blue", "mirrored white", "muted blue", "muted coral", "pale plum", "muted green", "dim violet", "faded tan", "light yellow", "clear fuchsia", "posh violet", "dotted fuchsia", "dotted plum", "posh green", "vibrant magenta", "drab maroon", "drab coral", "dotted tan", "striped cyan", "pale silver", "striped silver", "vibrant chartreuse", "bright turquoise", "bright tan", "mirrored green", "dim white", "muted white", "posh maroon", "posh chartreuse", "pale lavender", "light blue", "dark gold", "shiny fuchsia", "muted orange", "shiny plum", "posh blue", "wavy magenta", "striped salmon", "plaid silver", "dim bronze", "dim tomato", "wavy indigo", "wavy gold", "vibrant white", "dim magenta", "dark blue", "plaid gray", "faded gray", "faded maroon", "clear crimson", "muted aqua", "mirrored brown", "dotted purple", "dotted indigo", "wavy orange", "muted maroon", "clear salmon", "wavy turquoise", "drab salmon", "dotted yellow", "mirrored aqua", "shiny bronze", "wavy tan", "mirrored magenta", "mirrored lime", "clear magenta", "light red", "light white", "vibrant salmon", "dotted magenta", "striped violet", "muted magenta", "muted turquoise", "dim lime", "dotted maroon", "light purple", "mirrored beige", "vibrant lavender", "pale brown", "vibrant fuchsia", "dull silver", "faded red", "faded coral", "shiny cyan", "dim cyan", "dotted tomato", "muted cyan", "pale white", "shiny beige", "plaid maroon", "dotted coral", "light cyan", "shiny tomato", "faded silver", "posh tan", "pale turquoise", "muted silver", "clear coral", "shiny tan", "dark salmon", "plaid orange", "dark indigo", "dotted brown", "wavy gray", "posh crimson", "drab tomato", "bright crimson", "vibrant beige", "dim teal", "striped olive", "light black", "dull brown", "shiny salmon", "clear aqua", "clear lime", "dull indigo", "shiny aqua", "wavy cyan", "dull bronze", "striped coral", "vibrant tomato", "dotted chartreuse", "dull turquoise", "plaid lavender", "wavy white", "dim blue", "shiny red", "pale aqua", "clear chartreuse", "plaid white", "dotted blue", "bright plum", "pale black", "striped magenta", "light crimson", "dark tan", "drab olive", "wavy violet", "faded white", "mirrored purple", "mirrored gray", "dark gray", "pale indigo", "bright white", "striped lime", "mirrored tomato", "wavy coral", "dim fuchsia", "light lime", "mirrored red", "light chartreuse", "wavy salmon", "faded chartreuse", "posh beige", "vibrant aqua", "wavy olive", "dotted gray", "mirrored salmon", "faded orange", "pale orange", "posh teal", "bright teal", "striped maroon", "drab violet", "pale magenta", "shiny maroon", "vibrant turquoise", "dark black", "faded plum", "dotted black", "mirrored coral", "muted chartreuse", "clear plum", "faded bronze", "bright lime", "dull olive", "posh indigo", "striped plum", "dim lavender", }, };
day7/src/input_rules.zig
const std = @import("std"); usingnamespace std.os.windows; const DynLib = std.DynLib; pub const ERROR_DEVICE_NOT_CONNECTED = 1167; pub const XUSER_MAX_COUNT = 4; pub const XINPUT_GAMEPAD = extern struct { wButtons: WORD, bLeftTrigger: BYTE, bRightTrigger: BYTE, sThumbLX: SHORT, sThumbLY: SHORT, sThumbRX: SHORT, sThumbRY: SHORT, // TODO: we could use this to check the buttons state here // const Self = @This(); // pub fn APressed(self: Self) bool { // return self.wButtons & GAMEPAD_A != 0; // } }; pub const XINPUT_STATE = extern struct { dwPacketNumber: DWORD, Gamepad: XINPUT_GAMEPAD, }; pub const XINPUT_VIBRATION = extern struct { wLeftMotorSpeed: WORD, wRightMotorSpeed: WORD, }; pub const GAMEPAD_DPAD_UP = 0x0001; pub const GAMEPAD_DPAD_DOWN = 0x0002; pub const GAMEPAD_DPAD_LEFT = 0x0004; pub const GAMEPAD_DPAD_RIGHT = 0x0008; pub const GAMEPAD_START = 0x0010; pub const GAMEPAD_BACK = 0x0020; pub const GAMEPAD_LEFT_THUMB = 0x0040; pub const GAMEPAD_RIGHT_THUMB = 0x0080; pub const GAMEPAD_LEFT_SHOULDER = 0x0100; pub const GAMEPAD_RIGHT_SHOULDER = 0x0200; pub const GAMEPAD_A = 0x1000; pub const GAMEPAD_B = 0x2000; pub const GAMEPAD_X = 0x4000; pub const GAMEPAD_Y = 0x8000; pub const GAMEPAD_LEFT_THUMB_DEADZONE = 7849; pub const GAMEPAD_RIGHT_THUMB_DEADZONE = 8689; pub const GAMEPAD_TRIGGER_THRESHOLD = 30; fn dummy_x_input_get_state(dwUserIndex: DWORD, pState: [*c]XINPUT_STATE) DWORD { _ = dwUserIndex; _ = pState; return ERROR_DEVICE_NOT_CONNECTED; } fn dummy_x_input_set_state(dwUserIndex: DWORD, pVibration: [*c]const XINPUT_VIBRATION) DWORD { _ = dwUserIndex; _ = pVibration; return ERROR_DEVICE_NOT_CONNECTED; } const x_input_get_state = fn (dwUserIndex: DWORD, pState: [*c]XINPUT_STATE) DWORD; const x_input_set_state = fn (dwUserIndex: DWORD, pVibration: [*c]const XINPUT_VIBRATION) DWORD; pub var xInputGetState = dummy_x_input_get_state; pub var xInputSetState = dummy_x_input_set_state; pub fn win32LoadXinput() void { var xinput_lib = DynLib.open("xinput1_4.dll") catch DynLib.open("xinput9_1_0.dll") catch DynLib.open("xinput1_3.dll") catch return; if (xinput_lib.lookup(x_input_get_state, "XInputGetState")) |func| { xInputGetState = func; } if (xinput_lib.lookup(x_input_set_state, "XInputSetState")) |func| { xInputSetState = func; } } const ERROR_SUCCESS = 0; // TODO: should we return the controllerState instead of asking for one? pub fn getState(controllerIndex: u32, controllerState: *XINPUT_STATE) !void { const r = xInputGetState(controllerIndex, controllerState); if (r == ERROR_SUCCESS) return; return switch (r) { ERROR_DEVICE_NOT_CONNECTED => error.DeviceNotConnected, else => unexpectedError(@intToEnum(Win32Error, @truncate(u16, r))), }; } pub fn setState(controllerIndex: u32, vibration: *const XINPUT_VIBRATION) !void { const r = xInputSetState(controllerIndex, vibration); if (r == ERROR_SUCCESS) return; return switch (r) { ERROR_DEVICE_NOT_CONNECTED => error.DeviceNotConnected, else => unexpectedError(@intToEnum(Win32Error, @truncate(u16, r))), }; }
src/xinput.zig
const std = @import("std"); const mem = std.mem; const json = std.json; const testing = std.testing; const assert = std.debug.assert; const testUtil = @import("util.zig"); const log = @import("../src/md/log.zig"); const Token = @import("../src/md/token.zig").Token; const TokenId = @import("../src/md/token.zig").TokenId; const Lexer = @import("../src/md/lexer.zig").Lexer; const Parser = @import("../src/md/parse.zig").Parser; var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const allocator = &arena.allocator; // "markdown": "\tfoo\tbaz\t\tbim\n", // "html": "<pre><code>foo\tbaz\t\tbim\n</code></pre>\n", test "Test Example 001" { const testNumber: u8 = 1; const parserInput = try testUtil.getTest(allocator, testNumber, testUtil.TestKey.markdown); testUtil.dumpTest(parserInput); var p = Parser.init(allocator); defer p.deinit(); _ = try p.parse(parserInput); log.Debug("Testing lexer"); const expectLexerJson = @embedFile("expect/01-section-tabs/testl_001.json"); if (try testUtil.compareJsonExpect(allocator, expectLexerJson, p.lex.tokens.items)) |ajson| { // log.Errorf("LEXER TEST FAILED! lexer tokens (in json):\n{}\n", .{ajson}); std.os.exit(1); } log.Debug("Testing parser"); const expectParserJson = @embedFile("expect/01-section-tabs/testp_001.json"); if (try testUtil.compareJsonExpect(allocator, expectParserJson, p.root.items)) |ajson| { // log.Errorf("PARSER TEST FAILED! parser tree (in json):\n{}\n", .{ajson}); std.os.exit(1); } log.Debug("Testing html translator"); const expectHtml = try testUtil.getTest(allocator, testNumber, testUtil.TestKey.html); defer allocator.free(expectHtml); if (try testUtil.compareHtmlExpect(allocator, expectHtml, &p.root)) |ahtml| { // log.Errorf("HTML TRANSLATE TEST FAILED! html:\n{}\n", .{ahtml}); std.os.exit(1); } } // "markdown": " \tfoo\tbaz\t\tbim\n", // "html": "<pre><code>foo\tbaz\t\tbim\n</code></pre>\n", test "Test Example 002" { const testNumber: u8 = 2; const parserInput = try testUtil.getTest(allocator, testNumber, testUtil.TestKey.markdown); testUtil.dumpTest(parserInput); var p = Parser.init(allocator); defer p.deinit(); _ = try p.parse(parserInput); log.Debug("Testing lexer"); const expectLexerJson = @embedFile("expect/01-section-tabs/testl_002.json"); if (try testUtil.compareJsonExpect(allocator, expectLexerJson, p.lex.tokens.items)) |ajson| { log.Errorf("LEXER TEST FAILED! lexer tokens (in json):\n{}\n", .{ajson}); std.os.exit(1); } log.Debug("Testing parser"); const expectParserJson = @embedFile("expect/01-section-tabs/testp_002.json"); if (try testUtil.compareJsonExpect(allocator, expectParserJson, p.root.items)) |ajson| { // log.Errorf("PARSER TEST FAILED! parser tree (in json):\n{}\n", .{ajson}); std.os.exit(1); } log.Debug("Testing html translator"); const expectHtml = try testUtil.getTest(allocator, testNumber, testUtil.TestKey.html); defer allocator.free(expectHtml); if (try testUtil.compareHtmlExpect(allocator, expectHtml, &p.root)) |ahtml| { // log.Errorf("HTML TRANSLATE TEST FAILED! html:\n{}\n", .{ahtml}); std.os.exit(1); } } // "markdown": " a\ta\n ὐ\ta\n", // "html": "<pre><code>a\ta\nὐ\ta\n</code></pre>\n", test "Test Example 003" { const testNumber: u8 = 3; const parserInput = try testUtil.getTest(allocator, testNumber, testUtil.TestKey.markdown); testUtil.dumpTest(parserInput); var p = Parser.init(allocator); defer p.deinit(); _ = try p.parse(parserInput); log.Debug("Testing lexer"); const expectLexerJson = @embedFile("expect/01-section-tabs/testl_003.json"); if (try testUtil.compareJsonExpect(allocator, expectLexerJson, p.lex.tokens.items)) |ajson| { // log.Errorf("LEXER TEST FAILED! lexer tokens (in json):\n{}\n", .{ajson}); std.os.exit(1); } log.Debug("Testing parser"); const expectParserJson = @embedFile("expect/01-section-tabs/testp_003.json"); if (try testUtil.compareJsonExpect(allocator, expectParserJson, p.root.items)) |ajson| { // log.Errorf("PARSER TEST FAILED! parser tree (in json):\n{}\n", .{ajson}); std.os.exit(1); } log.Debug("Testing html translator"); const expectHtml = try testUtil.getTest(allocator, testNumber, testUtil.TestKey.html); defer allocator.free(expectHtml); if (try testUtil.compareHtmlExpect(allocator, expectHtml, &p.root)) |ahtml| { // log.Errorf("HTML TRANSLATE TEST FAILED! html:\n{}\n", .{ahtml}); std.os.exit(1); } }
test/section_tabs.zig
const xcb = @import("../xcb.zig"); pub const id = xcb.Extension{ .name = "XKEYBOARD", .global_id = 0 }; pub const Const = extern enum(c_uint) { @"MaxLegalKeyCode" = 255, @"PerKeyBitArraySize" = 32, @"KeyNameLength" = 4, }; pub const EventType = extern enum(c_uint) { @"NewKeyboardNotify" = 1, @"MapNotify" = 2, @"StateNotify" = 4, @"ControlsNotify" = 8, @"IndicatorStateNotify" = 16, @"IndicatorMapNotify" = 32, @"NamesNotify" = 64, @"CompatMapNotify" = 128, @"BellNotify" = 256, @"ActionMessage" = 512, @"AccessXNotify" = 1024, @"ExtensionDeviceNotify" = 2048, }; pub const NKNDetail = extern enum(c_uint) { @"Keycodes" = 1, @"Geometry" = 2, @"DeviceID" = 4, }; pub const AXNDetail = extern enum(c_uint) { @"SKPress" = 1, @"SKAccept" = 2, @"SKReject" = 4, @"SKRelease" = 8, @"BKAccept" = 16, @"BKReject" = 32, @"AXKWarning" = 64, }; pub const MapPart = extern enum(c_uint) { @"KeyTypes" = 1, @"KeySyms" = 2, @"ModifierMap" = 4, @"ExplicitComponents" = 8, @"KeyActions" = 16, @"KeyBehaviors" = 32, @"VirtualMods" = 64, @"VirtualModMap" = 128, }; pub const SetMapFlags = extern enum(c_uint) { @"ResizeTypes" = 1, @"RecomputeActions" = 2, }; pub const StatePart = extern enum(c_uint) { @"ModifierState" = 1, @"ModifierBase" = 2, @"ModifierLatch" = 4, @"ModifierLock" = 8, @"GroupState" = 16, @"GroupBase" = 32, @"GroupLatch" = 64, @"GroupLock" = 128, @"CompatState" = 256, @"GrabMods" = 512, @"CompatGrabMods" = 1024, @"LookupMods" = 2048, @"CompatLookupMods" = 4096, @"PointerButtons" = 8192, }; pub const BoolCtrl = extern enum(c_uint) { @"RepeatKeys" = 1, @"SlowKeys" = 2, @"BounceKeys" = 4, @"StickyKeys" = 8, @"MouseKeys" = 16, @"MouseKeysAccel" = 32, @"AccessXKeys" = 64, @"AccessXTimeoutMask" = 128, @"AccessXFeedbackMask" = 256, @"AudibleBellMask" = 512, @"Overlay1Mask" = 1024, @"Overlay2Mask" = 2048, @"IgnoreGroupLockMask" = 4096, }; pub const Control = extern enum(c_uint) { @"GroupsWrap" = 134217728, @"InternalMods" = 268435456, @"IgnoreLockMods" = 536870912, @"PerKeyRepeat" = 1073741824, @"ControlsEnabled" = 2147483648, }; pub const AXOption = extern enum(c_uint) { @"SKPressFB" = 1, @"SKAcceptFB" = 2, @"FeatureFB" = 4, @"SlowWarnFB" = 8, @"IndicatorFB" = 16, @"StickyKeysFB" = 32, @"TwoKeys" = 64, @"LatchToLock" = 128, @"SKReleaseFB" = 256, @"SKRejectFB" = 512, @"BKRejectFB" = 1024, @"DumbBell" = 2048, }; pub const DeviceSpec = u16; pub const LedClassResult = extern enum(c_uint) { @"KbdFeedbackClass" = 0, @"LedFeedbackClass" = 4, }; pub const LedClass = extern enum(c_uint) { @"KbdFeedbackClass" = 0, @"LedFeedbackClass" = 4, @"DfltXIClass" = 768, @"AllXIClasses" = 1280, }; pub const LedClassSpec = u16; pub const BellClassResult = extern enum(c_uint) { @"KbdFeedbackClass" = 0, @"BellFeedbackClass" = 5, }; pub const BellClass = extern enum(c_uint) { @"KbdFeedbackClass" = 0, @"BellFeedbackClass" = 5, @"DfltXIClass" = 768, }; pub const BellClassSpec = u16; pub const ID = extern enum(c_uint) { @"UseCoreKbd" = 256, @"UseCorePtr" = 512, @"DfltXIClass" = 768, @"DfltXIId" = 1024, @"AllXIClass" = 1280, @"AllXIId" = 1536, @"XINone" = 65280, }; pub const IDSpec = u16; pub const Group = extern enum(c_uint) { @"1" = 0, @"2" = 1, @"3" = 2, @"4" = 3, }; pub const Groups = extern enum(c_uint) { @"Any" = 254, @"All" = 255, }; pub const SetOfGroup = extern enum(c_uint) { @"Group1" = 1, @"Group2" = 2, @"Group3" = 4, @"Group4" = 8, }; pub const SetOfGroups = extern enum(c_uint) { @"Any" = 128, }; pub const GroupsWrap = extern enum(c_uint) { @"WrapIntoRange" = 0, @"ClampIntoRange" = 64, @"RedirectIntoRange" = 128, }; pub const VModsHigh = extern enum(c_uint) { @"15" = 128, @"14" = 64, @"13" = 32, @"12" = 16, @"11" = 8, @"10" = 4, @"9" = 2, @"8" = 1, }; pub const VModsLow = extern enum(c_uint) { @"7" = 128, @"6" = 64, @"5" = 32, @"4" = 16, @"3" = 8, @"2" = 4, @"1" = 2, @"0" = 1, }; pub const VMod = extern enum(c_uint) { @"15" = 32768, @"14" = 16384, @"13" = 8192, @"12" = 4096, @"11" = 2048, @"10" = 1024, @"9" = 512, @"8" = 256, @"7" = 128, @"6" = 64, @"5" = 32, @"4" = 16, @"3" = 8, @"2" = 4, @"1" = 2, @"0" = 1, }; pub const Explicit = extern enum(c_uint) { @"VModMap" = 128, @"Behavior" = 64, @"AutoRepeat" = 32, @"Interpret" = 16, @"KeyType4" = 8, @"KeyType3" = 4, @"KeyType2" = 2, @"KeyType1" = 1, }; pub const SymInterpretMatch = extern enum(c_uint) { @"NoneOf" = 0, @"AnyOfOrNone" = 1, @"AnyOf" = 2, @"AllOf" = 3, @"Exactly" = 4, }; pub const SymInterpMatch = extern enum(c_uint) { @"LevelOneOnly" = 128, @"OpMask" = 127, }; pub const IMFlag = extern enum(c_uint) { @"NoExplicit" = 128, @"NoAutomatic" = 64, @"LEDDrivesKB" = 32, }; pub const IMModsWhich = extern enum(c_uint) { @"UseCompat" = 16, @"UseEffective" = 8, @"UseLocked" = 4, @"UseLatched" = 2, @"UseBase" = 1, }; pub const IMGroupsWhich = extern enum(c_uint) { @"UseCompat" = 16, @"UseEffective" = 8, @"UseLocked" = 4, @"UseLatched" = 2, @"UseBase" = 1, }; /// @brief IndicatorMap pub const IndicatorMap = struct { @"flags": u8, @"whichGroups": u8, @"groups": u8, @"whichMods": u8, @"mods": u8, @"realMods": u8, @"vmods": u16, @"ctrls": u32, }; pub const CMDetail = extern enum(c_uint) { @"SymInterp" = 1, @"GroupCompat" = 2, }; pub const NameDetail = extern enum(c_uint) { @"Keycodes" = 1, @"Geometry" = 2, @"Symbols" = 4, @"PhysSymbols" = 8, @"Types" = 16, @"Compat" = 32, @"KeyTypeNames" = 64, @"KTLevelNames" = 128, @"IndicatorNames" = 256, @"KeyNames" = 512, @"KeyAliases" = 1024, @"VirtualModNames" = 2048, @"GroupNames" = 4096, @"RGNames" = 8192, }; pub const GBNDetail = extern enum(c_uint) { @"Types" = 1, @"CompatMap" = 2, @"ClientSymbols" = 4, @"ServerSymbols" = 8, @"IndicatorMaps" = 16, @"KeyNames" = 32, @"Geometry" = 64, @"OtherNames" = 128, }; pub const XIFeature = extern enum(c_uint) { @"Keyboards" = 1, @"ButtonActions" = 2, @"IndicatorNames" = 4, @"IndicatorMaps" = 8, @"IndicatorState" = 16, }; pub const PerClientFlag = extern enum(c_uint) { @"DetectableAutoRepeat" = 1, @"GrabsUseXKBState" = 2, @"AutoResetControls" = 4, @"LookupStateWhenGrabbed" = 8, @"SendEventUsesXKBState" = 16, }; /// @brief ModDef pub const ModDef = struct { @"mask": u8, @"realMods": u8, @"vmods": u16, }; /// @brief KeyName pub const KeyName = struct { @"name": [4]u8, }; /// @brief KeyAlias pub const KeyAlias = struct { @"real": [4]u8, @"alias": [4]u8, }; /// @brief CountedString16 pub const CountedString16 = struct { @"length": u16, @"string": []u8, @"alignment_pad": []u8, }; /// @brief KTMapEntry pub const KTMapEntry = struct { @"active": u8, @"mods_mask": u8, @"level": u8, @"mods_mods": u8, @"mods_vmods": u16, @"pad0": [2]u8, }; /// @brief KeyType pub const KeyType = struct { @"mods_mask": u8, @"mods_mods": u8, @"mods_vmods": u16, @"numLevels": u8, @"nMapEntries": u8, @"hasPreserve": u8, @"pad0": u8, @"map": []xcb.xkb.KTMapEntry, @"preserve": []xcb.xkb.ModDef, }; /// @brief KeySymMap pub const KeySymMap = struct { @"kt_index": [4]u8, @"groupInfo": u8, @"width": u8, @"nSyms": u16, @"syms": []xcb.KEYSYM, }; /// @brief CommonBehavior pub const CommonBehavior = struct { @"type": u8, @"data": u8, }; /// @brief DefaultBehavior pub const DefaultBehavior = struct { @"type": u8, @"pad0": u8, }; /// @brief LockBehavior pub const LockBehavior = struct { @"type": u8, @"pad0": u8, }; /// @brief RadioGroupBehavior pub const RadioGroupBehavior = struct { @"type": u8, @"group": u8, }; /// @brief OverlayBehavior pub const OverlayBehavior = struct { @"type": u8, @"key": xcb.KEYCODE, }; /// @brief PermamentLockBehavior pub const PermamentLockBehavior = struct { @"type": u8, @"pad0": u8, }; /// @brief PermamentRadioGroupBehavior pub const PermamentRadioGroupBehavior = struct { @"type": u8, @"group": u8, }; /// @brief PermamentOverlayBehavior pub const PermamentOverlayBehavior = struct { @"type": u8, @"key": xcb.KEYCODE, }; /// @brief Behavior pub const Behavior = union { @"common": xcb.xkb.CommonBehavior, @"default": xcb.xkb.DefaultBehavior, @"lock": xcb.xkb.LockBehavior, @"radioGroup": xcb.xkb.RadioGroupBehavior, @"overlay1": xcb.xkb.OverlayBehavior, @"overlay2": xcb.xkb.OverlayBehavior, @"permamentLock": xcb.xkb.PermamentLockBehavior, @"permamentRadioGroup": xcb.xkb.PermamentRadioGroupBehavior, @"permamentOverlay1": xcb.xkb.PermamentOverlayBehavior, @"permamentOverlay2": xcb.xkb.PermamentOverlayBehavior, @"type": u8, }; pub const BehaviorType = extern enum(c_uint) { @"Default" = 0, @"Lock" = 1, @"RadioGroup" = 2, @"Overlay1" = 3, @"Overlay2" = 4, @"PermamentLock" = 129, @"PermamentRadioGroup" = 130, @"PermamentOverlay1" = 131, @"PermamentOverlay2" = 132, }; /// @brief SetBehavior pub const SetBehavior = struct { @"keycode": xcb.KEYCODE, @"behavior": xcb.xkb.Behavior, @"pad0": u8, }; /// @brief SetExplicit pub const SetExplicit = struct { @"keycode": xcb.KEYCODE, @"explicit": u8, }; /// @brief KeyModMap pub const KeyModMap = struct { @"keycode": xcb.KEYCODE, @"mods": u8, }; /// @brief KeyVModMap pub const KeyVModMap = struct { @"keycode": xcb.KEYCODE, @"pad0": u8, @"vmods": u16, }; /// @brief KTSetMapEntry pub const KTSetMapEntry = struct { @"level": u8, @"realMods": u8, @"virtualMods": u16, }; /// @brief SetKeyType pub const SetKeyType = struct { @"mask": u8, @"realMods": u8, @"virtualMods": u16, @"numLevels": u8, @"nMapEntries": u8, @"preserve": u8, @"pad0": u8, @"entries": []xcb.xkb.KTSetMapEntry, @"preserve_entries": []xcb.xkb.KTSetMapEntry, }; pub const STRING8 = u8; /// @brief Outline pub const Outline = struct { @"nPoints": u8, @"cornerRadius": u8, @"pad0": [2]u8, @"points": []xcb.POINT, }; /// @brief Shape pub const Shape = struct { @"name": xcb.ATOM, @"nOutlines": u8, @"primaryNdx": u8, @"approxNdx": u8, @"pad0": u8, @"outlines": []xcb.xkb.Outline, }; /// @brief Key pub const Key = struct { @"name": [4]xcb.xkb.STRING8, @"gap": i16, @"shapeNdx": u8, @"colorNdx": u8, }; /// @brief OverlayKey pub const OverlayKey = struct { @"over": [4]xcb.xkb.STRING8, @"under": [4]xcb.xkb.STRING8, }; /// @brief OverlayRow pub const OverlayRow = struct { @"rowUnder": u8, @"nKeys": u8, @"pad0": [2]u8, @"keys": []xcb.xkb.OverlayKey, }; /// @brief Overlay pub const Overlay = struct { @"name": xcb.ATOM, @"nRows": u8, @"pad0": [3]u8, @"rows": []xcb.xkb.OverlayRow, }; /// @brief Row pub const Row = struct { @"top": i16, @"left": i16, @"nKeys": u8, @"vertical": u8, @"pad0": [2]u8, @"keys": []xcb.xkb.Key, }; pub const DoodadType = extern enum(c_uint) { @"Outline" = 1, @"Solid" = 2, @"Text" = 3, @"Indicator" = 4, @"Logo" = 5, }; /// @brief Listing pub const Listing = struct { @"flags": u16, @"length": u16, @"string": []xcb.xkb.STRING8, }; /// @brief DeviceLedInfo pub const DeviceLedInfo = struct { @"ledClass": xcb.xkb.LedClassSpec, @"ledID": xcb.xkb.IDSpec, @"namesPresent": u32, @"mapsPresent": u32, @"physIndicators": u32, @"state": u32, @"names": []xcb.ATOM, @"maps": []xcb.xkb.IndicatorMap, }; pub const Error = extern enum(c_uint) { @"BadDevice" = 255, @"BadClass" = 254, @"BadId" = 253, }; /// Opcode for Keyboard. pub const KeyboardOpcode = 0; /// @brief KeyboardError pub const KeyboardError = struct { @"response_type": u8, @"error_code": u8, @"sequence": u16, @"value": u32, @"minorOpcode": u16, @"majorOpcode": u8, @"pad0": [21]u8, }; pub const SA = extern enum(c_uint) { @"ClearLocks" = 1, @"LatchToLock" = 2, @"UseModMapMods" = 4, @"GroupAbsolute" = 4, }; pub const SAType = extern enum(c_uint) { @"NoAction" = 0, @"SetMods" = 1, @"LatchMods" = 2, @"LockMods" = 3, @"SetGroup" = 4, @"LatchGroup" = 5, @"LockGroup" = 6, @"MovePtr" = 7, @"PtrBtn" = 8, @"LockPtrBtn" = 9, @"SetPtrDflt" = 10, @"ISOLock" = 11, @"Terminate" = 12, @"SwitchScreen" = 13, @"SetControls" = 14, @"LockControls" = 15, @"ActionMessage" = 16, @"RedirectKey" = 17, @"DeviceBtn" = 18, @"LockDeviceBtn" = 19, @"DeviceValuator" = 20, }; /// @brief SANoAction pub const SANoAction = struct { @"type": u8, @"pad0": [7]u8, }; /// @brief SASetMods pub const SASetMods = struct { @"type": u8, @"flags": u8, @"mask": u8, @"realMods": u8, @"vmodsHigh": u8, @"vmodsLow": u8, @"pad0": [2]u8, }; /// @brief SALatchMods pub const SALatchMods = struct { @"type": u8, @"flags": u8, @"mask": u8, @"realMods": u8, @"vmodsHigh": u8, @"vmodsLow": u8, @"pad0": [2]u8, }; /// @brief SALockMods pub const SALockMods = struct { @"type": u8, @"flags": u8, @"mask": u8, @"realMods": u8, @"vmodsHigh": u8, @"vmodsLow": u8, @"pad0": [2]u8, }; /// @brief SASetGroup pub const SASetGroup = struct { @"type": u8, @"flags": u8, @"group": i8, @"pad0": [5]u8, }; /// @brief SALatchGroup pub const SALatchGroup = struct { @"type": u8, @"flags": u8, @"group": i8, @"pad0": [5]u8, }; /// @brief SALockGroup pub const SALockGroup = struct { @"type": u8, @"flags": u8, @"group": i8, @"pad0": [5]u8, }; pub const SAMovePtrFlag = extern enum(c_uint) { @"NoAcceleration" = 1, @"MoveAbsoluteX" = 2, @"MoveAbsoluteY" = 4, }; /// @brief SAMovePtr pub const SAMovePtr = struct { @"type": u8, @"flags": u8, @"xHigh": i8, @"xLow": u8, @"yHigh": i8, @"yLow": u8, @"pad0": [2]u8, }; /// @brief SAPtrBtn pub const SAPtrBtn = struct { @"type": u8, @"flags": u8, @"count": u8, @"button": u8, @"pad0": [4]u8, }; /// @brief SALockPtrBtn pub const SALockPtrBtn = struct { @"type": u8, @"flags": u8, @"pad0": u8, @"button": u8, @"pad1": [4]u8, }; pub const SASetPtrDfltFlag = extern enum(c_uint) { @"DfltBtnAbsolute" = 4, @"AffectDfltButton" = 1, }; /// @brief SASetPtrDflt pub const SASetPtrDflt = struct { @"type": u8, @"flags": u8, @"affect": u8, @"value": i8, @"pad0": [4]u8, }; pub const SAIsoLockFlag = extern enum(c_uint) { @"NoLock" = 1, @"NoUnlock" = 2, @"UseModMapMods" = 4, @"GroupAbsolute" = 4, @"ISODfltIsGroup" = 8, }; pub const SAIsoLockNoAffect = extern enum(c_uint) { @"Ctrls" = 8, @"Ptr" = 16, @"Group" = 32, @"Mods" = 64, }; /// @brief SAIsoLock pub const SAIsoLock = struct { @"type": u8, @"flags": u8, @"mask": u8, @"realMods": u8, @"group": i8, @"affect": u8, @"vmodsHigh": u8, @"vmodsLow": u8, }; /// @brief SATerminate pub const SATerminate = struct { @"type": u8, @"pad0": [7]u8, }; pub const SwitchScreenFlag = extern enum(c_uint) { @"Application" = 1, @"Absolute" = 4, }; /// @brief SASwitchScreen pub const SASwitchScreen = struct { @"type": u8, @"flags": u8, @"newScreen": i8, @"pad0": [5]u8, }; pub const BoolCtrlsHigh = extern enum(c_uint) { @"AccessXFeedback" = 1, @"AudibleBell" = 2, @"Overlay1" = 4, @"Overlay2" = 8, @"IgnoreGroupLock" = 16, }; pub const BoolCtrlsLow = extern enum(c_uint) { @"RepeatKeys" = 1, @"SlowKeys" = 2, @"BounceKeys" = 4, @"StickyKeys" = 8, @"MouseKeys" = 16, @"MouseKeysAccel" = 32, @"AccessXKeys" = 64, @"AccessXTimeout" = 128, }; /// @brief SASetControls pub const SASetControls = struct { @"type": u8, @"pad0": [3]u8, @"boolCtrlsHigh": u8, @"boolCtrlsLow": u8, @"pad1": [2]u8, }; /// @brief SALockControls pub const SALockControls = struct { @"type": u8, @"pad0": [3]u8, @"boolCtrlsHigh": u8, @"boolCtrlsLow": u8, @"pad1": [2]u8, }; pub const ActionMessageFlag = extern enum(c_uint) { @"OnPress" = 1, @"OnRelease" = 2, @"GenKeyEvent" = 4, }; /// @brief SAActionMessage pub const SAActionMessage = struct { @"type": u8, @"flags": u8, @"message": [6]u8, }; /// @brief SARedirectKey pub const SARedirectKey = struct { @"type": u8, @"newkey": xcb.KEYCODE, @"mask": u8, @"realModifiers": u8, @"vmodsMaskHigh": u8, @"vmodsMaskLow": u8, @"vmodsHigh": u8, @"vmodsLow": u8, }; /// @brief SADeviceBtn pub const SADeviceBtn = struct { @"type": u8, @"flags": u8, @"count": u8, @"button": u8, @"device": u8, @"pad0": [3]u8, }; pub const LockDeviceFlags = extern enum(c_uint) { @"NoLock" = 1, @"NoUnlock" = 2, }; /// @brief SALockDeviceBtn pub const SALockDeviceBtn = struct { @"type": u8, @"flags": u8, @"pad0": u8, @"button": u8, @"device": u8, @"pad1": [3]u8, }; pub const SAValWhat = extern enum(c_uint) { @"IgnoreVal" = 0, @"SetValMin" = 1, @"SetValCenter" = 2, @"SetValMax" = 3, @"SetValRelative" = 4, @"SetValAbsolute" = 5, }; /// @brief SADeviceValuator pub const SADeviceValuator = struct { @"type": u8, @"device": u8, @"val1what": u8, @"val1index": u8, @"val1value": u8, @"val2what": u8, @"val2index": u8, @"val2value": u8, }; /// @brief SIAction pub const SIAction = struct { @"type": u8, @"data": [7]u8, }; /// @brief SymInterpret pub const SymInterpret = struct { @"sym": xcb.KEYSYM, @"mods": u8, @"match": u8, @"virtualMod": u8, @"flags": u8, @"action": xcb.xkb.SIAction, }; /// @brief Action pub const Action = union { @"noaction": xcb.xkb.SANoAction, @"setmods": xcb.xkb.SASetMods, @"latchmods": xcb.xkb.SALatchMods, @"lockmods": xcb.xkb.SALockMods, @"setgroup": xcb.xkb.SASetGroup, @"latchgroup": xcb.xkb.SALatchGroup, @"lockgroup": xcb.xkb.SALockGroup, @"moveptr": xcb.xkb.SAMovePtr, @"ptrbtn": xcb.xkb.SAPtrBtn, @"lockptrbtn": xcb.xkb.SALockPtrBtn, @"setptrdflt": xcb.xkb.SASetPtrDflt, @"isolock": xcb.xkb.SAIsoLock, @"terminate": xcb.xkb.SATerminate, @"switchscreen": xcb.xkb.SASwitchScreen, @"setcontrols": xcb.xkb.SASetControls, @"lockcontrols": xcb.xkb.SALockControls, @"message": xcb.xkb.SAActionMessage, @"redirect": xcb.xkb.SARedirectKey, @"devbtn": xcb.xkb.SADeviceBtn, @"lockdevbtn": xcb.xkb.SALockDeviceBtn, @"devval": xcb.xkb.SADeviceValuator, @"type": u8, }; /// @brief UseExtensioncookie pub const UseExtensioncookie = struct { sequence: c_uint, }; /// @brief UseExtensionRequest pub const UseExtensionRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 0, @"length": u16, @"wantedMajor": u16, @"wantedMinor": u16, }; /// @brief UseExtensionReply pub const UseExtensionReply = struct { @"response_type": u8, @"supported": u8, @"sequence": u16, @"length": u32, @"serverMajor": u16, @"serverMinor": u16, @"pad0": [20]u8, }; /// @brief SelectEventsRequest pub const SelectEventsRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 1, @"length": u16, @"deviceSpec": xcb.xkb.DeviceSpec, @"affectWhich": u16, @"clear": u16, @"selectAll": u16, @"affectMap": u16, @"map": u16, }; /// @brief BellRequest pub const BellRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 3, @"length": u16, @"deviceSpec": xcb.xkb.DeviceSpec, @"bellClass": xcb.xkb.BellClassSpec, @"bellID": xcb.xkb.IDSpec, @"percent": i8, @"forceSound": u8, @"eventOnly": u8, @"pad0": u8, @"pitch": i16, @"duration": i16, @"pad1": [2]u8, @"name": xcb.ATOM, @"window": xcb.WINDOW, }; /// @brief GetStatecookie pub const GetStatecookie = struct { sequence: c_uint, }; /// @brief GetStateRequest pub const GetStateRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 4, @"length": u16, @"deviceSpec": xcb.xkb.DeviceSpec, @"pad0": [2]u8, }; /// @brief GetStateReply pub const GetStateReply = struct { @"response_type": u8, @"deviceID": u8, @"sequence": u16, @"length": u32, @"mods": u8, @"baseMods": u8, @"latchedMods": u8, @"lockedMods": u8, @"group": u8, @"lockedGroup": u8, @"baseGroup": i16, @"latchedGroup": i16, @"compatState": u8, @"grabMods": u8, @"compatGrabMods": u8, @"lookupMods": u8, @"compatLookupMods": u8, @"pad0": u8, @"ptrBtnState": u16, @"pad1": [6]u8, }; /// @brief LatchLockStateRequest pub const LatchLockStateRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 5, @"length": u16, @"deviceSpec": xcb.xkb.DeviceSpec, @"affectModLocks": u8, @"modLocks": u8, @"lockGroup": u8, @"groupLock": u8, @"affectModLatches": u8, @"pad0": u8, @"pad1": u8, @"latchGroup": u8, @"groupLatch": u16, }; /// @brief GetControlscookie pub const GetControlscookie = struct { sequence: c_uint, }; /// @brief GetControlsRequest pub const GetControlsRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 6, @"length": u16, @"deviceSpec": xcb.xkb.DeviceSpec, @"pad0": [2]u8, }; /// @brief GetControlsReply pub const GetControlsReply = struct { @"response_type": u8, @"deviceID": u8, @"sequence": u16, @"length": u32, @"mouseKeysDfltBtn": u8, @"numGroups": u8, @"groupsWrap": u8, @"internalModsMask": u8, @"ignoreLockModsMask": u8, @"internalModsRealMods": u8, @"ignoreLockModsRealMods": u8, @"pad0": u8, @"internalModsVmods": u16, @"ignoreLockModsVmods": u16, @"repeatDelay": u16, @"repeatInterval": u16, @"slowKeysDelay": u16, @"debounceDelay": u16, @"mouseKeysDelay": u16, @"mouseKeysInterval": u16, @"mouseKeysTimeToMax": u16, @"mouseKeysMaxSpeed": u16, @"mouseKeysCurve": i16, @"accessXOption": u16, @"accessXTimeout": u16, @"accessXTimeoutOptionsMask": u16, @"accessXTimeoutOptionsValues": u16, @"pad1": [2]u8, @"accessXTimeoutMask": u32, @"accessXTimeoutValues": u32, @"enabledControls": u32, @"perKeyRepeat": [32]u8, }; /// @brief SetControlsRequest pub const SetControlsRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 7, @"length": u16, @"deviceSpec": xcb.xkb.DeviceSpec, @"affectInternalRealMods": u8, @"internalRealMods": u8, @"affectIgnoreLockRealMods": u8, @"ignoreLockRealMods": u8, @"affectInternalVirtualMods": u16, @"internalVirtualMods": u16, @"affectIgnoreLockVirtualMods": u16, @"ignoreLockVirtualMods": u16, @"mouseKeysDfltBtn": u8, @"groupsWrap": u8, @"accessXOptions": u16, @"pad0": [2]u8, @"affectEnabledControls": u32, @"enabledControls": u32, @"changeControls": u32, @"repeatDelay": u16, @"repeatInterval": u16, @"slowKeysDelay": u16, @"debounceDelay": u16, @"mouseKeysDelay": u16, @"mouseKeysInterval": u16, @"mouseKeysTimeToMax": u16, @"mouseKeysMaxSpeed": u16, @"mouseKeysCurve": i16, @"accessXTimeout": u16, @"accessXTimeoutMask": u32, @"accessXTimeoutValues": u32, @"accessXTimeoutOptionsMask": u16, @"accessXTimeoutOptionsValues": u16, @"perKeyRepeat": [32]u8, }; /// @brief GetMapcookie pub const GetMapcookie = struct { sequence: c_uint, }; /// @brief GetMapRequest pub const GetMapRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 8, @"length": u16, @"deviceSpec": xcb.xkb.DeviceSpec, @"full": u16, @"partial": u16, @"firstType": u8, @"nTypes": u8, @"firstKeySym": xcb.KEYCODE, @"nKeySyms": u8, @"firstKeyAction": xcb.KEYCODE, @"nKeyActions": u8, @"firstKeyBehavior": xcb.KEYCODE, @"nKeyBehaviors": u8, @"virtualMods": u16, @"firstKeyExplicit": xcb.KEYCODE, @"nKeyExplicit": u8, @"firstModMapKey": xcb.KEYCODE, @"nModMapKeys": u8, @"firstVModMapKey": xcb.KEYCODE, @"nVModMapKeys": u8, @"pad0": [2]u8, }; /// @brief GetMapReply pub const GetMapReply = struct { @"response_type": u8, @"deviceID": u8, @"sequence": u16, @"length": u32, @"pad0": [2]u8, @"minKeyCode": xcb.KEYCODE, @"maxKeyCode": xcb.KEYCODE, @"present": u16, @"firstType": u8, @"nTypes": u8, @"totalTypes": u8, @"firstKeySym": xcb.KEYCODE, @"totalSyms": u16, @"nKeySyms": u8, @"firstKeyAction": xcb.KEYCODE, @"totalActions": u16, @"nKeyActions": u8, @"firstKeyBehavior": xcb.KEYCODE, @"nKeyBehaviors": u8, @"totalKeyBehaviors": u8, @"firstKeyExplicit": xcb.KEYCODE, @"nKeyExplicit": u8, @"totalKeyExplicit": u8, @"firstModMapKey": xcb.KEYCODE, @"nModMapKeys": u8, @"totalModMapKeys": u8, @"firstVModMapKey": xcb.KEYCODE, @"nVModMapKeys": u8, @"totalVModMapKeys": u8, @"pad1": u8, @"virtualMods": u16, }; /// @brief SetMapRequest pub const SetMapRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 9, @"length": u16, @"deviceSpec": xcb.xkb.DeviceSpec, @"present": u16, @"flags": u16, @"minKeyCode": xcb.KEYCODE, @"maxKeyCode": xcb.KEYCODE, @"firstType": u8, @"nTypes": u8, @"firstKeySym": xcb.KEYCODE, @"nKeySyms": u8, @"totalSyms": u16, @"firstKeyAction": xcb.KEYCODE, @"nKeyActions": u8, @"totalActions": u16, @"firstKeyBehavior": xcb.KEYCODE, @"nKeyBehaviors": u8, @"totalKeyBehaviors": u8, @"firstKeyExplicit": xcb.KEYCODE, @"nKeyExplicit": u8, @"totalKeyExplicit": u8, @"firstModMapKey": xcb.KEYCODE, @"nModMapKeys": u8, @"totalModMapKeys": u8, @"firstVModMapKey": xcb.KEYCODE, @"nVModMapKeys": u8, @"totalVModMapKeys": u8, @"virtualMods": u16, }; /// @brief GetCompatMapcookie pub const GetCompatMapcookie = struct { sequence: c_uint, }; /// @brief GetCompatMapRequest pub const GetCompatMapRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 10, @"length": u16, @"deviceSpec": xcb.xkb.DeviceSpec, @"groups": u8, @"getAllSI": u8, @"firstSI": u16, @"nSI": u16, }; /// @brief GetCompatMapReply pub const GetCompatMapReply = struct { @"response_type": u8, @"deviceID": u8, @"sequence": u16, @"length": u32, @"groupsRtrn": u8, @"pad0": u8, @"firstSIRtrn": u16, @"nSIRtrn": u16, @"nTotalSI": u16, @"pad1": [16]u8, @"si_rtrn": []xcb.xkb.SymInterpret, @"group_rtrn": []xcb.xkb.ModDef, }; /// @brief SetCompatMapRequest pub const SetCompatMapRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 11, @"length": u16, @"deviceSpec": xcb.xkb.DeviceSpec, @"pad0": u8, @"recomputeActions": u8, @"truncateSI": u8, @"groups": u8, @"firstSI": u16, @"nSI": u16, @"pad1": [2]u8, @"si": []const xcb.xkb.SymInterpret, @"groupMaps": []const xcb.xkb.ModDef, }; /// @brief GetIndicatorStatecookie pub const GetIndicatorStatecookie = struct { sequence: c_uint, }; /// @brief GetIndicatorStateRequest pub const GetIndicatorStateRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 12, @"length": u16, @"deviceSpec": xcb.xkb.DeviceSpec, @"pad0": [2]u8, }; /// @brief GetIndicatorStateReply pub const GetIndicatorStateReply = struct { @"response_type": u8, @"deviceID": u8, @"sequence": u16, @"length": u32, @"state": u32, @"pad0": [20]u8, }; /// @brief GetIndicatorMapcookie pub const GetIndicatorMapcookie = struct { sequence: c_uint, }; /// @brief GetIndicatorMapRequest pub const GetIndicatorMapRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 13, @"length": u16, @"deviceSpec": xcb.xkb.DeviceSpec, @"pad0": [2]u8, @"which": u32, }; /// @brief GetIndicatorMapReply pub const GetIndicatorMapReply = struct { @"response_type": u8, @"deviceID": u8, @"sequence": u16, @"length": u32, @"which": u32, @"realIndicators": u32, @"nIndicators": u8, @"pad0": [15]u8, @"maps": []xcb.xkb.IndicatorMap, }; /// @brief SetIndicatorMapRequest pub const SetIndicatorMapRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 14, @"length": u16, @"deviceSpec": xcb.xkb.DeviceSpec, @"pad0": [2]u8, @"which": u32, @"maps": []const xcb.xkb.IndicatorMap, }; /// @brief GetNamedIndicatorcookie pub const GetNamedIndicatorcookie = struct { sequence: c_uint, }; /// @brief GetNamedIndicatorRequest pub const GetNamedIndicatorRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 15, @"length": u16, @"deviceSpec": xcb.xkb.DeviceSpec, @"ledClass": xcb.xkb.LedClassSpec, @"ledID": xcb.xkb.IDSpec, @"pad0": [2]u8, @"indicator": xcb.ATOM, }; /// @brief GetNamedIndicatorReply pub const GetNamedIndicatorReply = struct { @"response_type": u8, @"deviceID": u8, @"sequence": u16, @"length": u32, @"indicator": xcb.ATOM, @"found": u8, @"on": u8, @"realIndicator": u8, @"ndx": u8, @"map_flags": u8, @"map_whichGroups": u8, @"map_groups": u8, @"map_whichMods": u8, @"map_mods": u8, @"map_realMods": u8, @"map_vmod": u16, @"map_ctrls": u32, @"supported": u8, @"pad0": [3]u8, }; /// @brief SetNamedIndicatorRequest pub const SetNamedIndicatorRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 16, @"length": u16, @"deviceSpec": xcb.xkb.DeviceSpec, @"ledClass": xcb.xkb.LedClassSpec, @"ledID": xcb.xkb.IDSpec, @"pad0": [2]u8, @"indicator": xcb.ATOM, @"setState": u8, @"on": u8, @"setMap": u8, @"createMap": u8, @"pad1": u8, @"map_flags": u8, @"map_whichGroups": u8, @"map_groups": u8, @"map_whichMods": u8, @"map_realMods": u8, @"map_vmods": u16, @"map_ctrls": u32, }; /// @brief GetNamescookie pub const GetNamescookie = struct { sequence: c_uint, }; /// @brief GetNamesRequest pub const GetNamesRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 17, @"length": u16, @"deviceSpec": xcb.xkb.DeviceSpec, @"pad0": [2]u8, @"which": u32, }; /// @brief GetNamesReply pub const GetNamesReply = struct { @"response_type": u8, @"deviceID": u8, @"sequence": u16, @"length": u32, @"which": u32, @"minKeyCode": xcb.KEYCODE, @"maxKeyCode": xcb.KEYCODE, @"nTypes": u8, @"groupNames": u8, @"virtualMods": u16, @"firstKey": xcb.KEYCODE, @"nKeys": u8, @"indicators": u32, @"nRadioGroups": u8, @"nKeyAliases": u8, @"nKTLevels": u16, @"pad0": [4]u8, }; /// @brief SetNamesRequest pub const SetNamesRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 18, @"length": u16, @"deviceSpec": xcb.xkb.DeviceSpec, @"virtualMods": u16, @"which": u32, @"firstType": u8, @"nTypes": u8, @"firstKTLevelt": u8, @"nKTLevels": u8, @"indicators": u32, @"groupNames": u8, @"nRadioGroups": u8, @"firstKey": xcb.KEYCODE, @"nKeys": u8, @"nKeyAliases": u8, @"pad0": u8, @"totalKTLevelNames": u16, }; /// @brief PerClientFlagscookie pub const PerClientFlagscookie = struct { sequence: c_uint, }; /// @brief PerClientFlagsRequest pub const PerClientFlagsRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 21, @"length": u16, @"deviceSpec": xcb.xkb.DeviceSpec, @"pad0": [2]u8, @"change": u32, @"value": u32, @"ctrlsToChange": u32, @"autoCtrls": u32, @"autoCtrlsValues": u32, }; /// @brief PerClientFlagsReply pub const PerClientFlagsReply = struct { @"response_type": u8, @"deviceID": u8, @"sequence": u16, @"length": u32, @"supported": u32, @"value": u32, @"autoCtrls": u32, @"autoCtrlsValues": u32, @"pad0": [8]u8, }; /// @brief ListComponentscookie pub const ListComponentscookie = struct { sequence: c_uint, }; /// @brief ListComponentsRequest pub const ListComponentsRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 22, @"length": u16, @"deviceSpec": xcb.xkb.DeviceSpec, @"maxNames": u16, }; /// @brief ListComponentsReply pub const ListComponentsReply = struct { @"response_type": u8, @"deviceID": u8, @"sequence": u16, @"length": u32, @"nKeymaps": u16, @"nKeycodes": u16, @"nTypes": u16, @"nCompatMaps": u16, @"nSymbols": u16, @"nGeometries": u16, @"extra": u16, @"pad0": [10]u8, @"keymaps": []xcb.xkb.Listing, @"keycodes": []xcb.xkb.Listing, @"types": []xcb.xkb.Listing, @"compatMaps": []xcb.xkb.Listing, @"symbols": []xcb.xkb.Listing, @"geometries": []xcb.xkb.Listing, }; /// @brief GetKbdByNamecookie pub const GetKbdByNamecookie = struct { sequence: c_uint, }; /// @brief GetKbdByNameRequest pub const GetKbdByNameRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 23, @"length": u16, @"deviceSpec": xcb.xkb.DeviceSpec, @"need": u16, @"want": u16, @"load": u8, @"pad0": u8, }; /// @brief GetKbdByNameReply pub const GetKbdByNameReply = struct { @"response_type": u8, @"deviceID": u8, @"sequence": u16, @"length": u32, @"minKeyCode": xcb.KEYCODE, @"maxKeyCode": xcb.KEYCODE, @"loaded": u8, @"newKeyboard": u8, @"found": u16, @"reported": u16, @"pad0": [16]u8, }; /// @brief GetDeviceInfocookie pub const GetDeviceInfocookie = struct { sequence: c_uint, }; /// @brief GetDeviceInfoRequest pub const GetDeviceInfoRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 24, @"length": u16, @"deviceSpec": xcb.xkb.DeviceSpec, @"wanted": u16, @"allButtons": u8, @"firstButton": u8, @"nButtons": u8, @"pad0": u8, @"ledClass": xcb.xkb.LedClassSpec, @"ledID": xcb.xkb.IDSpec, }; /// @brief GetDeviceInfoReply pub const GetDeviceInfoReply = struct { @"response_type": u8, @"deviceID": u8, @"sequence": u16, @"length": u32, @"present": u16, @"supported": u16, @"unsupported": u16, @"nDeviceLedFBs": u16, @"firstBtnWanted": u8, @"nBtnsWanted": u8, @"firstBtnRtrn": u8, @"nBtnsRtrn": u8, @"totalBtns": u8, @"hasOwnState": u8, @"dfltKbdFB": u16, @"dfltLedFB": u16, @"pad0": [2]u8, @"devType": xcb.ATOM, @"nameLen": u16, @"name": []xcb.xkb.STRING8, @"btnActions": []xcb.xkb.Action, @"leds": []xcb.xkb.DeviceLedInfo, }; /// @brief SetDeviceInfoRequest pub const SetDeviceInfoRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 25, @"length": u16, @"deviceSpec": xcb.xkb.DeviceSpec, @"firstBtn": u8, @"nBtns": u8, @"change": u16, @"nDeviceLedFBs": u16, @"btnActions": []const xcb.xkb.Action, @"leds": []const xcb.xkb.DeviceLedInfo, }; /// @brief SetDebuggingFlagscookie pub const SetDebuggingFlagscookie = struct { sequence: c_uint, }; /// @brief SetDebuggingFlagsRequest pub const SetDebuggingFlagsRequest = struct { @"major_opcode": u8, @"minor_opcode": u8 = 101, @"length": u16, @"msgLength": u16, @"pad0": [2]u8, @"affectFlags": u32, @"flags": u32, @"affectCtrls": u32, @"ctrls": u32, @"message": []const xcb.xkb.STRING8, }; /// @brief SetDebuggingFlagsReply pub const SetDebuggingFlagsReply = struct { @"response_type": u8, @"pad0": u8, @"sequence": u16, @"length": u32, @"currentFlags": u32, @"currentCtrls": u32, @"supportedFlags": u32, @"supportedCtrls": u32, @"pad1": [8]u8, }; /// Opcode for NewKeyboardNotify. pub const NewKeyboardNotifyOpcode = 0; /// @brief NewKeyboardNotifyEvent pub const NewKeyboardNotifyEvent = struct { @"response_type": u8, @"xkbType": u8, @"sequence": u16, @"time": xcb.TIMESTAMP, @"deviceID": u8, @"oldDeviceID": u8, @"minKeyCode": xcb.KEYCODE, @"maxKeyCode": xcb.KEYCODE, @"oldMinKeyCode": xcb.KEYCODE, @"oldMaxKeyCode": xcb.KEYCODE, @"requestMajor": u8, @"requestMinor": u8, @"changed": u16, @"pad0": [14]u8, }; /// Opcode for MapNotify. pub const MapNotifyOpcode = 1; /// @brief MapNotifyEvent pub const MapNotifyEvent = struct { @"response_type": u8, @"xkbType": u8, @"sequence": u16, @"time": xcb.TIMESTAMP, @"deviceID": u8, @"ptrBtnActions": u8, @"changed": u16, @"minKeyCode": xcb.KEYCODE, @"maxKeyCode": xcb.KEYCODE, @"firstType": u8, @"nTypes": u8, @"firstKeySym": xcb.KEYCODE, @"nKeySyms": u8, @"firstKeyAct": xcb.KEYCODE, @"nKeyActs": u8, @"firstKeyBehavior": xcb.KEYCODE, @"nKeyBehavior": u8, @"firstKeyExplicit": xcb.KEYCODE, @"nKeyExplicit": u8, @"firstModMapKey": xcb.KEYCODE, @"nModMapKeys": u8, @"firstVModMapKey": xcb.KEYCODE, @"nVModMapKeys": u8, @"virtualMods": u16, @"pad0": [2]u8, }; /// Opcode for StateNotify. pub const StateNotifyOpcode = 2; /// @brief StateNotifyEvent pub const StateNotifyEvent = struct { @"response_type": u8, @"xkbType": u8, @"sequence": u16, @"time": xcb.TIMESTAMP, @"deviceID": u8, @"mods": u8, @"baseMods": u8, @"latchedMods": u8, @"lockedMods": u8, @"group": u8, @"baseGroup": i16, @"latchedGroup": i16, @"lockedGroup": u8, @"compatState": u8, @"grabMods": u8, @"compatGrabMods": u8, @"lookupMods": u8, @"compatLoockupMods": u8, @"ptrBtnState": u16, @"changed": u16, @"keycode": xcb.KEYCODE, @"eventType": u8, @"requestMajor": u8, @"requestMinor": u8, }; /// Opcode for ControlsNotify. pub const ControlsNotifyOpcode = 3; /// @brief ControlsNotifyEvent pub const ControlsNotifyEvent = struct { @"response_type": u8, @"xkbType": u8, @"sequence": u16, @"time": xcb.TIMESTAMP, @"deviceID": u8, @"numGroups": u8, @"pad0": [2]u8, @"changedControls": u32, @"enabledControls": u32, @"enabledControlChanges": u32, @"keycode": xcb.KEYCODE, @"eventType": u8, @"requestMajor": u8, @"requestMinor": u8, @"pad1": [4]u8, }; /// Opcode for IndicatorStateNotify. pub const IndicatorStateNotifyOpcode = 4; /// @brief IndicatorStateNotifyEvent pub const IndicatorStateNotifyEvent = struct { @"response_type": u8, @"xkbType": u8, @"sequence": u16, @"time": xcb.TIMESTAMP, @"deviceID": u8, @"pad0": [3]u8, @"state": u32, @"stateChanged": u32, @"pad1": [12]u8, }; /// Opcode for IndicatorMapNotify. pub const IndicatorMapNotifyOpcode = 5; /// @brief IndicatorMapNotifyEvent pub const IndicatorMapNotifyEvent = struct { @"response_type": u8, @"xkbType": u8, @"sequence": u16, @"time": xcb.TIMESTAMP, @"deviceID": u8, @"pad0": [3]u8, @"state": u32, @"mapChanged": u32, @"pad1": [12]u8, }; /// Opcode for NamesNotify. pub const NamesNotifyOpcode = 6; /// @brief NamesNotifyEvent pub const NamesNotifyEvent = struct { @"response_type": u8, @"xkbType": u8, @"sequence": u16, @"time": xcb.TIMESTAMP, @"deviceID": u8, @"pad0": u8, @"changed": u16, @"firstType": u8, @"nTypes": u8, @"firstLevelName": u8, @"nLevelNames": u8, @"pad1": u8, @"nRadioGroups": u8, @"nKeyAliases": u8, @"changedGroupNames": u8, @"changedVirtualMods": u16, @"firstKey": xcb.KEYCODE, @"nKeys": u8, @"changedIndicators": u32, @"pad2": [4]u8, }; /// Opcode for CompatMapNotify. pub const CompatMapNotifyOpcode = 7; /// @brief CompatMapNotifyEvent pub const CompatMapNotifyEvent = struct { @"response_type": u8, @"xkbType": u8, @"sequence": u16, @"time": xcb.TIMESTAMP, @"deviceID": u8, @"changedGroups": u8, @"firstSI": u16, @"nSI": u16, @"nTotalSI": u16, @"pad0": [16]u8, }; /// Opcode for BellNotify. pub const BellNotifyOpcode = 8; /// @brief BellNotifyEvent pub const BellNotifyEvent = struct { @"response_type": u8, @"xkbType": u8, @"sequence": u16, @"time": xcb.TIMESTAMP, @"deviceID": u8, @"bellClass": u8, @"bellID": u8, @"percent": u8, @"pitch": u16, @"duration": u16, @"name": xcb.ATOM, @"window": xcb.WINDOW, @"eventOnly": u8, @"pad0": [7]u8, }; /// Opcode for ActionMessage. pub const ActionMessageOpcode = 9; /// @brief ActionMessageEvent pub const ActionMessageEvent = struct { @"response_type": u8, @"xkbType": u8, @"sequence": u16, @"time": xcb.TIMESTAMP, @"deviceID": u8, @"keycode": xcb.KEYCODE, @"press": u8, @"keyEventFollows": u8, @"mods": u8, @"group": u8, @"message": [8]xcb.xkb.STRING8, @"pad0": [10]u8, }; /// Opcode for AccessXNotify. pub const AccessXNotifyOpcode = 10; /// @brief AccessXNotifyEvent pub const AccessXNotifyEvent = struct { @"response_type": u8, @"xkbType": u8, @"sequence": u16, @"time": xcb.TIMESTAMP, @"deviceID": u8, @"keycode": xcb.KEYCODE, @"detailt": u16, @"slowKeysDelay": u16, @"debounceDelay": u16, @"pad0": [16]u8, }; /// Opcode for ExtensionDeviceNotify. pub const ExtensionDeviceNotifyOpcode = 11; /// @brief ExtensionDeviceNotifyEvent pub const ExtensionDeviceNotifyEvent = struct { @"response_type": u8, @"xkbType": u8, @"sequence": u16, @"time": xcb.TIMESTAMP, @"deviceID": u8, @"pad0": u8, @"reason": u16, @"ledClass": u16, @"ledID": u16, @"ledsDefined": u32, @"ledState": u32, @"firstButton": u8, @"nButtons": u8, @"supported": u16, @"unsupported": u16, @"pad1": [2]u8, }; test "" { @import("std").testing.refAllDecls(@This()); }
src/auto/xkb.zig
const uefi = @import("std").os.uefi; const fmt = @import("std").fmt; const console = @import("./console.zig"); const runtime = @import("./uefi_runtime.zig"); const load_kernel_image = @import("./loader.zig").load_kernel_image; pub var boot_services: *uefi.tables.BootServices = undefined; pub var runtime_services: *runtime.RuntimeServices = undefined; export fn efi_main(handle: u64, system_table: uefi.tables.SystemTable) callconv(.C) uefi.Status { console.out = system_table.con_out.?; boot_services = system_table.boot_services.?; runtime_services = @ptrCast(*runtime.RuntimeServices, system_table.runtime_services); console.puts("bootloader started\r\n"); // Clear screen. reset() returns usize(0) on success var result = console.out.clearScreen(); if (uefi.Status.Success != result) { return result; } console.puts("configuring graphics mode...\r\n"); // Graphics output? var graphics_output_protocol: ?*uefi.protocols.GraphicsOutputProtocol = undefined; if (boot_services.locateProtocol(&uefi.protocols.GraphicsOutputProtocol.guid, null, @ptrCast(*?*c_void, &graphics_output_protocol)) == uefi.Status.Success) { // Check supported resolutions: var i: u32 = 0; while (i < graphics_output_protocol.?.mode.max_mode) : (i += 1) { var info: *uefi.protocols.GraphicsOutputModeInformation = undefined; var info_size: usize = undefined; _ = graphics_output_protocol.?.queryMode(i, &info_size, &info); console.printf(" mode {}: {}x{} {}\r\n", .{ i, info.horizontal_resolution, info.vertical_resolution, info.pixel_format }); } console.printf(" current mode = {}\r\n", .{graphics_output_protocol.?.mode.mode}); // TODO:: search for compatible mode and set 1024x768? or make triangles resolution independent //_ = graphics_output_protocol.?.setMode(2); } else { console.puts("[error] unable to configure graphics mode\r\n"); } // obtain access to the file system console.puts("initialising File System service..."); var simple_file_system: ?*uefi.protocols.SimpleFileSystemProtocol = undefined; result = boot_services.locateProtocol(&uefi.protocols.SimpleFileSystemProtocol.guid, null, @ptrCast(*?*c_void, &simple_file_system)); if (result != uefi.Status.Success) { console.puts(" [failed]\r\n"); console.printf("ERROR {}: initialising file system\r\n", .{result}); return result; } // Grab a handle to the FS volume var root_file_system: *uefi.protocols.FileProtocol = undefined; result = simple_file_system.?.openVolume(&root_file_system); if (result != uefi.Status.Success) { console.puts(" [failed]\r\n"); console.printf("ERROR {}: opening file system volume\r\n", .{result}); return result; } console.puts(" [done]\r\n"); // Locate where there is some free memory console.puts("locating free memory...\r\n"); var memory_map: [*]uefi.tables.MemoryDescriptor = undefined; var memory_map_size: usize = 0; var memory_map_key: usize = undefined; var descriptor_size: usize = undefined; var descriptor_version: u32 = undefined; // get the current memory map while (uefi.Status.BufferTooSmall == boot_services.getMemoryMap(&memory_map_size, memory_map, &memory_map_key, &descriptor_size, &descriptor_version)) { result = boot_services.allocatePool(uefi.tables.MemoryType.BootServicesData, memory_map_size, @ptrCast(*[*]align(8) u8, &memory_map)); if (uefi.Status.Success != result) { return result; } } console.printf(" -> memory map size: {}, descriptor size {}\r\n", .{memory_map_size, descriptor_size}); var mem_index: usize = 0; var mem_count: usize = undefined; var mem_point: *uefi.tables.MemoryDescriptor = undefined; var base_address: u64 = 0x100000; var num_pages: usize = 0; mem_count = memory_map_size / descriptor_size; while (mem_index < mem_count) { mem_point = @intToPtr(*uefi.tables.MemoryDescriptor, @ptrToInt(memory_map) + (mem_index * descriptor_size)); if (mem_point.type == uefi.tables.MemoryType.ConventionalMemory and mem_point.physical_start >= base_address) { base_address = mem_point.physical_start; num_pages = mem_point.number_of_pages; break; } mem_index += 1; } console.printf(" -> found {} pages at address {}\r\n", .{num_pages, base_address}); console.puts(" -> [done]\r\n"); // Start moving the kernel image into memory (\kernelx64.elf or \kernelaa64.elf) console.puts("loading kernel...\r\n"); var entry_point: u64 = 0; var kernel_start: u64 = 0; // different images for different architectures result = switch (@import("builtin").target.cpu.arch) { .x86_64 => load_kernel_image( root_file_system, &[_:0]u16{ '\\', 'k', 'e', 'r', 'n', 'e', 'l', 'x', '6', '4', '.', 'e', 'l', 'f' }, base_address, &entry_point, &kernel_start ), .aarch64 => load_kernel_image( root_file_system, &[_:0]u16{ '\\', 'k', 'e', 'r', 'n', 'e', 'l', 'a', 'a', '6', '4', '.', 'e', 'l', 'f' }, base_address, &entry_point, &kernel_start ), else => @compileError("unsupported architecture"), }; if (result != uefi.Status.Success) { console.puts(" [failed]\r\n"); console.printf("ERROR {}: loading kernel\r\n", .{result}); return result; } console.puts(" -> [done]\r\n"); // prevent system reboot if we don't check-in console.puts("disabling watchdog timer..."); result = boot_services.setWatchdogTimer(0, 0, 0, null); if (result != uefi.Status.Success) { console.puts(" [failed]\r\n"); console.printf("ERROR {}: disabling watchdog timer\r\n", .{result}); return result; } console.puts(" [done]\r\n"); console.printf("graphics buffer@{}\r\n", .{graphics_output_protocol.?.mode.frame_buffer_base}); console.printf("jumping to kernel... @{}\r\n", .{entry_point}); // Attempt to exit boot services! result = uefi.Status.NoResponse; while(result != uefi.Status.Success) { // Get the memory map while (uefi.Status.BufferTooSmall == boot_services.getMemoryMap(&memory_map_size, memory_map, &memory_map_key, &descriptor_size, &descriptor_version)) { result = boot_services.allocatePool(uefi.tables.MemoryType.BootServicesData, memory_map_size, @ptrCast(*[*]align(8) u8, &memory_map)); if (uefi.Status.Success != result) { return result; } } // Pass the current image's handle and the memory map key to exitBootServices // to gain full control over the hardware. // // exitBootServices may fail. If exitBootServices failed, only getMemoryMap and // exitBootservices may be called afterwards. The application may not return // anymore after the first call to exitBootServices, even if it was unsuccessful. // // Most protocols may not be used any more (except for runtime protocols // which nobody seems to implement). // // After exiting boot services, the following fields in the system table should // be set to null: ConsoleInHandle, ConIn, ConsoleOutHandle, ConOut, // StandardErrorHandle, StdErr, and BootServicesTable. Because the fields are // being modified, the table's CRC32 must be recomputed. // // All events of type event_signal_exit_boot_services will be signaled. result = boot_services.exitBootServices(uefi.handle, memory_map_key); } // Set kernel boot info. var boot_info = BootInfo{ .video_buff = graphics_output_protocol.?.mode, .memory_map = memory_map, .memory_map_size = memory_map_size, .memory_map_descriptor_size = descriptor_size, }; // Put the boot information at the start of the kernel var boot_info_ptr: *u64 = @intToPtr(*u64, base_address); boot_info_ptr.* = @ptrToInt(&boot_info); // Prepare the memory map to be configured with virtual memory mem_index = 0; mem_count = memory_map_size / descriptor_size; while (mem_index < mem_count) { mem_point = @intToPtr(*uefi.tables.MemoryDescriptor, @ptrToInt(memory_map) + (mem_index * descriptor_size)); // We want to change the virtual address of the loader data to match the ELF file // all other entries need their virtual addresses configured too if (mem_point.type == uefi.tables.MemoryType.LoaderData) { mem_point.virtual_start = kernel_start; } else { mem_point.virtual_start = mem_point.physical_start; } mem_index += 1; } // Configure the virtual memory result = runtime_services.setVirtualAddressMap(memory_map_size, descriptor_size, descriptor_version, memory_map); if (result != uefi.Status.Success) { console.draw_triangle(boot_info.video_buff.frame_buffer_base, 1024 / 2, 768 / 3 - 25, 100, 0x00119911); return uefi.Status.LoadError; } // Cast pointer to kernel entry. // Jump to kernel entry. @intToPtr(fn() callconv(.C) void, entry_point)(); // Should never make it here return uefi.Status.LoadError; } const BootInfo = extern struct { video_buff: *uefi.protocols.GraphicsOutputProtocolMode, memory_map: [*]uefi.tables.MemoryDescriptor, memory_map_size: u64, memory_map_descriptor_size: u64, };
bootstrap/uefi_bootstrap.zig
const std = @import("std"); const assert = std.debug.assert; const Allocator = std.mem.Allocator; const wren = @import("./wren.zig"); const wrappers = @import("./c_wrappers.zig"); const WrenError = @import("./error.zig").WrenError; const Handle = @import("./handle.zig").Handle; const Receiver = @import("./call.zig").Receiver; const allocatorWrapper = @import("./allocator_wrapper.zig").allocatorWrapper; pub const ErrorType = enum { Compile, Runtime, StackTrace }; pub const SlotType = enum { Bool, Foreign, List, Map, Null, Number, String, Unknown, }; pub fn AllocatedMemory(comptime T: type) type { return struct { const Self = @This(); allocator: *Allocator, data: []T, pub fn init(allocator: *Allocator, len: usize) Self { // In the future, not panicking might be nice. But failing // allocations here put the VM in an irrecoverable state. const data = allocator.alloc(T, len) catch |e| std.debug.panic("could not allocate memory but really need it", .{}); return Self{ .allocator = allocator, .data = data }; } }; } const AllocatedBytes = AllocatedMemory(u8); pub const WriteFn = fn (*Vm, []const u8) void; pub const ErrorFn = fn (*Vm, ErrorType, ?[]const u8, ?u32, []const u8) void; pub const ResolveModuleFn = fn (*Vm, []const u8, []const u8) AllocatedBytes; pub const LoadModuleFn = fn (*Vm, []const u8) AllocatedBytes; pub const Configuration = struct { const Self = @This(); allocator: ?*Allocator = null, resolveModuleFn: ?ResolveModuleFn = null, loadModuleFn: ?LoadModuleFn = null, bindForeignClassFn: ?wren.BindForeignClassFn = null, bindForeignMethodFn: ?wren.BindForeignMethodFn = null, writeFn: ?WriteFn = null, errorFn: ?ErrorFn = null, initialHeapSize: ?usize = null, minHeapSize: ?usize = null, heapGrowthPercent: ?u8 = null, const registerForeignClasses = @import("./foreign.zig").registerForeignClasses; // This will be much nicer when https://github.com/ziglang/zig/issues/2765 is done. pub fn newVmInPlace(self: Self, comptime UserData: type, result: *Vm, user_data: ?*UserData) WrenError!void { var cfg: wren.Configuration = undefined; wren.initConfiguration(&cfg); if (self.allocator) |a| { cfg.reallocateFn = allocatorWrapper; } if (self.resolveModuleFn) |f| { cfg.resolveModuleFn = wrappers.resolveModuleWrapper; } if (self.loadModuleFn) |f| { cfg.loadModuleFn = wrappers.loadModuleWrapper; } if (self.bindForeignClassFn) |f| { cfg.bindForeignClassFn = f; } if (self.bindForeignMethodFn) |f| { cfg.bindForeignMethodFn = f; } if (self.writeFn) |f| { cfg.writeFn = wrappers.writeWrapper; } if (self.errorFn) |f| { cfg.errorFn = wrappers.errorWrapper; } if (self.initialHeapSize) |i| { cfg.initialHeapSize = i; } if (self.minHeapSize) |i| { cfg.minHeapSize = i; } if (self.heapGrowthPercent) |i| { cfg.heapGrowthPercent = i; } // This is slightly hacky, but even the VM creation needs the // allocator. Create a temporary pseudo-userdata with only the // allocator set, it will be replaced after being used once. var pseudo_vm: Vm = undefined; std.mem.set(u8, std.mem.asBytes(&pseudo_vm), 0); pseudo_vm.allocator = self.allocator; cfg.userData = &pseudo_vm; const ptr = wren.newVm(&cfg) orelse return WrenError.VmCreationFailed; Vm.initInPlace(UserData, result, ptr, self, user_data); } }; pub const Vm = struct { const Self = @This(); vm: *wren.Vm, allocator: ?*Allocator, resolveModuleFn: ?ResolveModuleFn, loadModuleFn: ?LoadModuleFn, writeFn: ?WriteFn, errorFn: ?ErrorFn, user_data_ptr: ?usize, // This will be much nicer when https://github.com/ziglang/zig/issues/2765 is done. pub fn initInPlace(comptime UserData: type, result: *Self, vm: *wren.Vm, conf: Configuration, user_data: ?*UserData) void { result.vm = vm; result.allocator = conf.allocator; result.resolveModuleFn = conf.resolveModuleFn; result.loadModuleFn = conf.loadModuleFn; result.writeFn = conf.writeFn; result.errorFn = conf.errorFn; result.user_data_ptr = if (@sizeOf(UserData) > 0 and user_data != null) @ptrToInt(user_data) else null; result.registerWithWren(); } pub fn deinit(self: *Self) void { wren.freeVm(self.vm); } pub fn fromC(vm: ?*wren.Vm) *Vm { const udptr = wren.getUserData(vm); assert(udptr != null); return @ptrCast(*Vm, @alignCast(@alignOf(*Vm), udptr)); } fn registerWithWren(self: *Self) void { wren.setUserData(self.vm, self); } pub fn getUserData(self: *Self, comptime UserData: type) *UserData { const udp = self.user_data_ptr orelse std.debug.panic("user data pointer is null", .{}); return @intToPtr(*UserData, udp); } pub fn interpret(self: *Self, module: []const u8, code: []const u8) WrenError!void { const res = wren.interpret(self.vm, @ptrCast([*c]const u8, module), @ptrCast([*c]const u8, code)); if (res == .WREN_RESULT_COMPILE_ERROR) { return WrenError.CompileError; } if (res == .WREN_RESULT_RUNTIME_ERROR) { return WrenError.RuntimeError; } } pub fn getSlotCount(self: *Self) u32 { const slot_count = wren.getSlotCount(self.vm); assert(slot_count >= 0); return @intCast(u32, slot_count); } pub fn ensureSlots(self: *Self, slot_count: u32) void { wren.ensureSlots(self.vm, @intCast(c_int, slot_count)); } pub fn getSlotType(self: *Self, slot_index: u32) SlotType { return switch (wren.getSlotType(self.vm, @intCast(c_int, slot_index))) { .WREN_TYPE_BOOL => .Bool, .WREN_TYPE_FOREIGN => .Foreign, .WREN_TYPE_LIST => .Map, .WREN_TYPE_MAP => .Map, .WREN_TYPE_NULL => .Null, .WREN_TYPE_NUM => .Number, .WREN_TYPE_STRING => .String, .WREN_TYPE_UNKNOWN => .Unknown, else => std.debug.panic("invalid slot type returned: {}", .{wren.getSlotType(self.vm, @intCast(c_int, slot_index))}), }; } pub fn setSlot(self: *Self, slot_index: u32, value: anytype) void { comptime const ti = @typeInfo(@TypeOf(value)); switch (ti) { .Bool => wren.setSlotBool(self.vm, @intCast(c_int, slot_index), value), .Int => wren.setSlotDouble(self.vm, @intCast(c_int, slot_index), @intToFloat(f64, value)), .Float => wren.setSlotDouble(self.vm, @intCast(c_int, slot_index), value), .ComptimeInt => wren.setSlotDouble(self.vm, @intCast(c_int, slot_index), value), .ComptimeFloat => wren.setSlotDouble(self.vm, @intCast(c_int, slot_index), value), .Array => if (ti.Array.child == u8) wren.setSlotBytes(@intCast(c_int, slot_index), value.ptr, value.len) else @compileError("only u8 arrays are allowed"), .Pointer => { comptime const cti = @typeInfo(ti.Pointer.child); if (cti == .Array and cti.Array.child == u8) { wren.setSlotBytes(self.vm, @intCast(c_int, slot_index), @ptrCast([*c]const u8, value), value.*.len); } else if (cti == .Int and !cti.Int.is_signed and cti.Int.bits == 8) { wren.setSlotBytes(self.vm, @intCast(c_int, slot_index), @ptrCast([*c]const u8, value), value.len); } else { @compileError("only pointers to u8 arrays are allowed, found " ++ @typeName(@TypeOf(value))); } }, .Null => wren.setSlotNull(self.vm, @intCast(c_int, slot_index)), else => @compileError("not a valid wren datatype: " ++ @typeName(@TypeOf(value))), } } pub fn getSlot(self: *Self, comptime T: type, slot_index: u32) T { const slot = @intCast(c_int, slot_index); comptime const ti = @typeInfo(T); return switch (ti) { .Int, .Float => { assert(self.getSlotType(slot_index) == .Number); switch (T) { i32, u32 => return @floatToInt(T, wren.getSlotDouble(self.vm, slot)), f32, f64 => return @floatCast(T, wren.getSlotDouble(self.vm, slot)), else => @compileError("only i32, u32, f32 or f64 are allowed, got " ++ @typeName(T)), } }, .Bool => { assert(self.getSlotType(slot_index) == .Bool); return wren.getSlotBool(self.vm, slot); }, .Pointer => { const slot_type = self.getSlotType(slot_index); if (ti.Pointer.child == wren.Handle) { assert(slot_type == .Unknown or slot_type == .Foreign); const handle = wren.getSlotHandle(self.vm, slot); assert(handle != null); return @ptrCast(T, handle); } if (ti.Pointer.child != u8) { assert(slot_type == .Foreign); const ptr = wren.getSlotForeign(self.vm, slot); return @ptrCast(*ti.Pointer.child, @alignCast(@alignOf(ti.Pointer.child), ptr)); } assert(slot_type == .String); if (ti.Pointer.child != u8 or !ti.Pointer.is_const) { @compileError("strings can only be retrieved as []u8 const, got " ++ @typeName(T)); } var slice: []const u8 = undefined; var len: c_int = undefined; slice.ptr = wren.getSlotBytes(self.vm, @intCast(c_int, slot_index), @ptrCast([*c]c_int, &len)); slice.len = @intCast(usize, len); return slice; }, else => @compileError("not a valid wren datatype: " ++ @typeName(T)), }; } pub fn isSlotNull(self: *Self, slot_index: u32) bool { return self.getSlotType(slot_index) == .Null; } pub fn getVariable(self: *Self, module: []const u8, variable: []const u8, slot_index: u32) void { wren.getVariable(self.vm, @ptrCast([*c]const u8, module), @ptrCast([*c]const u8, variable), @intCast(c_int, slot_index)); } pub fn setSlotHandle(self: *Self, slot_index: u32, handle: *wren.Handle) void { wren.setSlotHandle(self.vm, @intCast(c_int, slot_index), handle); } pub const makeReceiver = @import("./call.zig").Receiver.init; pub const makeCallHandle = @import("./call.zig").CallHandle.init; pub fn abortFiber(self: *Self, slot_index: u32, value: anytype) void { self.setSlot(slot_index, value); wren.abortFiber(self.vm, @intCast(c_int, slot_index)); } }; fn printError(vm: *Vm, error_type: ErrorType, module: ?[]const u8, line: ?u32, message: []const u8) void { std.debug.print("error_type={}, module={}, line={}, message={}\n", .{ error_type, module, line, message }); } const testing = std.testing; const EmptyUserData = struct {}; const TestUserData = struct { i: i32, }; test "init vm" { var user_data = TestUserData{ .i = 23 }; var config = Configuration{}; var vm: Vm = undefined; try config.newVmInPlace(TestUserData, &vm, &user_data); defer vm.deinit(); const ud = vm.getUserData(TestUserData); testing.expectEqual(@as(i32, 23), ud.i); } var testPrintSuccess = false; fn testPrint(vm: *Vm, text: []const u8) void { testPrintSuccess = true; } test "writeFn" { var config = Configuration{}; config.writeFn = testPrint; var vm: Vm = undefined; try config.newVmInPlace(EmptyUserData, &vm, null); testing.expect(!testPrintSuccess); try vm.interpret("main", "System.print(\"I am running in a VM!\")"); testing.expect(testPrintSuccess); } var testResolveModuleSuccess = false; fn testResolveModule(vm: *Vm, importer: []const u8, name: []const u8) AllocatedBytes { testing.expectEqualStrings("test_main", importer); testing.expectEqualStrings("my_module", name); const res = "it worked!"; var mem = AllocatedBytes.init(std.heap.c_allocator, res.len + 1); std.mem.copy(u8, mem.data, res); mem.data[res.len] = 0; testResolveModuleSuccess = true; return mem; } fn testResolveLoadModule(vm: *Vm, name: []const u8) AllocatedBytes { testing.expectEqualStrings("it worked!", name); const src = ""; var mem = AllocatedBytes.init(std.heap.c_allocator, src.len + 1); std.mem.copy(u8, mem.data, src); mem.data[src.len] = 0; return mem; } test "resolveModuleFn" { var config = Configuration{}; config.resolveModuleFn = testResolveModule; config.loadModuleFn = testResolveLoadModule; var vm: Vm = undefined; try config.newVmInPlace(EmptyUserData, &vm, null); defer vm.deinit(); try vm.interpret("test_main", "import \"my_module\""); testing.expect(testResolveModuleSuccess == true); } var testLoadModuleSuccess = false; fn testLoadModule(vm: *Vm, name: []const u8) AllocatedBytes { testing.expectEqualStrings(name, "my_module"); testLoadModuleSuccess = true; const source = "System.print(\"I am running in a VM!\")"; var mem = AllocatedMemory(u8).init(std.heap.c_allocator, source.len + 1); std.mem.copy(u8, mem.data, source); mem.data[source.len] = 0; return mem; } test "loadModuleFn" { var config = Configuration{}; config.loadModuleFn = testLoadModule; var vm: Vm = undefined; try config.newVmInPlace(EmptyUserData, &vm, null); defer vm.deinit(); try vm.interpret("main", "import \"my_module\""); testing.expect(testLoadModuleSuccess == true); } var testCompileErrorCount: i32 = 0; var testRuntimeErrorCount: i32 = 0; var testStackTraceErrorCount: i32 = 0; fn testError(vm: *Vm, error_type: ErrorType, module: ?[]const u8, line: ?u32, message: []const u8) void { if (error_type == .Compile) { testCompileErrorCount += 1; } if (error_type == .Runtime) { testRuntimeErrorCount += 1; } if (error_type == .StackTrace) { testStackTraceErrorCount += 1; } } test "errorFn" { var config = Configuration{}; config.errorFn = testError; var vm: Vm = undefined; try config.newVmInPlace(EmptyUserData, &vm, null); vm.interpret("main", "zimport \"my_module\"") catch |e| {}; testing.expectEqual(testCompileErrorCount, 2); vm.interpret("main", "import \"blob\"") catch |e| {}; testing.expectEqual(@intCast(i32, 1), testRuntimeErrorCount); testing.expectEqual(@intCast(i32, 1), testStackTraceErrorCount); } test "allocators" { const alloc = std.testing.allocator; // const alloc = std.heap.c_allocator; var config = Configuration{}; config.allocator = alloc; var vm: Vm = undefined; try config.newVmInPlace(EmptyUserData, &vm, null); defer vm.deinit(); try vm.interpret("main", "System.print(\"I am running in a VM!\")"); } test "slot count" { var config = Configuration{}; var vm: Vm = undefined; try config.newVmInPlace(EmptyUserData, &vm, null); defer vm.deinit(); vm.ensureSlots(10); testing.expect(vm.getSlotCount() >= 10); } test "primitive slot types" { var config = Configuration{}; var vm: Vm = undefined; try config.newVmInPlace(EmptyUserData, &vm, null); defer vm.deinit(); vm.ensureSlots(100); var i: u32 = 0; vm.setSlot(i, true); testing.expectEqual(SlotType.Bool, vm.getSlotType(i)); testing.expectEqual(true, vm.getSlot(bool, i)); i += 1; var runtimeInt: i32 = 42; vm.setSlot(i, runtimeInt); testing.expectEqual(SlotType.Number, vm.getSlotType(i)); testing.expectEqual(runtimeInt, vm.getSlot(i32, i)); i += 1; var runtimeFloat: f32 = 23.5; vm.setSlot(i, runtimeFloat); testing.expectEqual(SlotType.Number, vm.getSlotType(i)); testing.expectEqual(runtimeFloat, vm.getSlot(f32, i)); i += 1; vm.setSlot(i, 42); testing.expectEqual(SlotType.Number, vm.getSlotType(i)); testing.expectEqual(@as(i32, 42), vm.getSlot(i32, i)); i += 1; vm.setSlot(i, 23.5); testing.expectEqual(SlotType.Number, vm.getSlotType(i)); testing.expectEqual(@as(f32, 23.5), vm.getSlot(f32, i)); i += 1; vm.setSlot(i, "All your base"); testing.expectEqual(SlotType.String, vm.getSlotType(i)); testing.expectEqualStrings("All your base", vm.getSlot([]const u8, i)); i += 1; vm.setSlot(i, null); testing.expectEqual(SlotType.Null, vm.getSlotType(i)); testing.expect(vm.isSlotNull(i)); i += 1; } test "read variable" { var config = Configuration{}; var vm: Vm = undefined; try config.newVmInPlace(EmptyUserData, &vm, null); defer vm.deinit(); try vm.interpret("test", "var my_var = \"Move all zig!\""); vm.ensureSlots(1); vm.getVariable("test", "my_var", 0); testing.expectEqual(SlotType.String, vm.getSlotType(0)); testing.expectEqualStrings("Move all zig!", vm.getSlot([]const u8, 0)); }
src/zapata/vm.zig
const Buffer = @import("Buffer.zig"); const Sampler = @import("Sampler.zig"); const Texture = @import("Texture.zig"); const TextureView = @import("TextureView.zig"); const StorageTextureBindingLayout = @import("structs.zig").StorageTextureBindingLayout; const StorageTextureAccess = @import("enums.zig").StorageTextureAccess; const ShaderStage = @import("enums.zig").ShaderStage; const BindGroupLayout = @This(); /// The type erased pointer to the BindGroupLayout implementation /// Equal to c.WGPUBindGroupLayout for NativeInstance. ptr: *anyopaque, vtable: *const VTable, pub const VTable = struct { reference: fn (ptr: *anyopaque) void, release: fn (ptr: *anyopaque) void, setLabel: fn (ptr: *anyopaque, label: [:0]const u8) void, }; pub inline fn reference(layout: BindGroupLayout) void { layout.vtable.reference(layout.ptr); } pub inline fn release(layout: BindGroupLayout) void { layout.vtable.release(layout.ptr); } pub inline fn setLabel(group: BindGroupLayout, label: [:0]const u8) void { group.vtable.setLabel(group.ptr, label); } pub const Descriptor = struct { label: ?[*:0]const u8 = null, entries: []const Entry, }; pub const Entry = extern struct { reserved: ?*anyopaque = null, binding: u32, visibility: ShaderStage, buffer: Buffer.BindingLayout = .{ .type = .none }, sampler: Sampler.BindingLayout = .{ .type = .none }, texture: Texture.BindingLayout = .{ .sample_type = .none }, storage_texture: StorageTextureBindingLayout = .{ .access = .none, .format = .none }, /// Helper to create a buffer BindGroupLayout.Entry. pub fn buffer( binding: u32, visibility: ShaderStage, binding_type: Buffer.BindingType, has_dynamic_offset: bool, min_binding_size: u64, ) Entry { return .{ .binding = binding, .visibility = visibility, .buffer = .{ .type = binding_type, .has_dynamic_offset = has_dynamic_offset, .min_binding_size = min_binding_size, }, }; } /// Helper to create a sampler BindGroupLayout.Entry. pub fn sampler(binding: u32, visibility: ShaderStage, binding_type: Sampler.BindingType) Entry { return .{ .binding = binding, .visibility = visibility, .sampler = .{ .type = binding_type }, }; } /// Helper to create a texture BindGroupLayout.Entry. pub fn texture( binding: u32, visibility: ShaderStage, sample_type: Texture.SampleType, view_dimension: TextureView.Dimension, multisampled: bool, ) Entry { return .{ .binding = binding, .visibility = visibility, .texture = .{ .sample_type = sample_type, .view_dimension = view_dimension, .multisampled = multisampled, }, }; } /// Helper to create a storage texture BindGroupLayout.Entry. pub fn storageTexture( binding: u32, visibility: ShaderStage, access: StorageTextureAccess, format: Texture.Format, view_dimension: TextureView.Dimension, ) Entry { return .{ .binding = binding, .visibility = visibility, .storage_texture = .{ .access = access, .format = format, .view_dimension = view_dimension, }, }; } }; test { _ = VTable; _ = reference; _ = release; _ = setLabel; _ = Descriptor; _ = Entry; const desc = BindGroupLayout.Descriptor{ .entries = &.{ BindGroupLayout.Entry.buffer(0, .{ .vertex = true }, .uniform, true, 0), BindGroupLayout.Entry.sampler(1, .{ .vertex = true }, .filtering), BindGroupLayout.Entry.texture(2, .{ .fragment = true }, .float, .dimension_2d, false), BindGroupLayout.Entry.storageTexture(3, .{ .fragment = true }, .none, .rgba32_float, .dimension_2d), }, }; _ = desc; }
gpu/src/BindGroupLayout.zig
const std = @import("std"); const builtin = @import("builtin"); fn add_module(comptime module: []const u8, b: *std.build.Builder, target: std.zig.CrossTarget) !*std.build.Step { // Standard release options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. const mode = b.standardReleaseOptions(); const all = b.step(module, "All " ++ module ++ " examples"); const dir = try std.fs.cwd().openDir( module, .{ .iterate = true }, ); var iter = dir.iterate(); while (try iter.next()) |entry| { if (entry.kind != .File) continue; const extension_idx = std.mem.lastIndexOf(u8, entry.name, ".c") orelse continue; const name = entry.name[0..extension_idx]; const path = try std.fs.path.join(b.allocator, &.{ module, entry.name }); // zig's mingw headers do not include pthread.h if (std.mem.eql(u8, "core_loading_thread", name) and target.getOsTag() == .windows) continue; const exe = b.addExecutable(name, null); exe.addCSourceFile(path, switch (target.getOsTag()) { .windows => &[_][]const u8{}, .linux => &[_][]const u8{}, .macos => &[_][]const u8{"-DPLATFORM_DESKTOP"}, else => @panic("Unsupported OS"), }); exe.setTarget(target); exe.setBuildMode(mode); exe.linkLibC(); exe.addObjectFile(switch (target.getOsTag()) { .windows => "../src/raylib.lib", .linux => "../src/libraylib.a", .macos => "../src/libraylib.a", else => @panic("Unsupported OS"), }); exe.addIncludeDir("../src"); exe.addIncludeDir("../src/external"); exe.addIncludeDir("../src/external/glfw/include"); switch (exe.target.toTarget().os.tag) { .windows => { exe.linkSystemLibrary("winmm"); exe.linkSystemLibrary("gdi32"); exe.linkSystemLibrary("opengl32"); exe.addIncludeDir("external/glfw/deps/mingw"); }, .linux => { exe.linkSystemLibrary("GL"); exe.linkSystemLibrary("rt"); exe.linkSystemLibrary("dl"); exe.linkSystemLibrary("m"); exe.linkSystemLibrary("X11"); }, .macos => { exe.linkFramework("Foundation"); exe.linkFramework("Cocoa"); exe.linkFramework("OpenGL"); exe.linkFramework("CoreAudio"); exe.linkFramework("CoreVideo"); exe.linkFramework("IOKit"); }, else => { @panic("Unsupported OS"); }, } exe.setOutputDir(module); var run = exe.run(); run.step.dependOn(&b.addInstallArtifact(exe).step); run.cwd = module; b.step(name, name).dependOn(&run.step); all.dependOn(&exe.step); } return all; } pub fn build(b: *std.build.Builder) !void { // Standard target options allows the person running `zig build` to choose // what target to build for. Here we do not override the defaults, which // means any target is allowed, and the default is native. Other options // for restricting supported target set are available. const target = b.standardTargetOptions(.{}); const all = b.getInstallStep(); all.dependOn(try add_module("audio", b, target)); all.dependOn(try add_module("core", b, target)); all.dependOn(try add_module("models", b, target)); all.dependOn(try add_module("others", b, target)); all.dependOn(try add_module("shaders", b, target)); all.dependOn(try add_module("shapes", b, target)); all.dependOn(try add_module("text", b, target)); all.dependOn(try add_module("textures", b, target)); }
examples/build.zig
const aoc = @import("../aoc.zig"); const std = @import("std"); const TileMap = struct { range: aoc.CoordRange = aoc.CoordRange.init(), unprocessed_tiles: std.ArrayList(Tile), queue: std.ArrayList(aoc.Coord), tile_map: std.AutoHashMap(aoc.Coord, Tile), fn init(allocator: std.mem.Allocator) TileMap { return TileMap { .unprocessed_tiles = std.ArrayList(Tile).init(allocator), .queue = std.ArrayList(aoc.Coord).init(allocator), .tile_map = std.AutoHashMap(aoc.Coord, Tile).init(allocator), }; } fn deinit(self: *TileMap) void { self.unprocessed_tiles.deinit(); self.queue.deinit(); var tile_map_iter = self.tile_map.valueIterator(); while (tile_map_iter.next()) |tile| { tile.deinit(); } self.tile_map.deinit(); } fn process(self: *TileMap) !void { try self.tile_map.put(aoc.PredefinedCoord.ORIGIN, self.unprocessed_tiles.pop()); try self.queue.append(aoc.PredefinedCoord.ORIGIN); while (self.queue.popOrNull()) |coord| { const tile = self.tile_map.get(coord).?; var idx: usize = 0; outer: while (idx < self.unprocessed_tiles.items.len) { var unprocessed_tile = self.unprocessed_tiles.items[idx]; var iterator = unprocessed_tile.transformation_iterator(); while (iterator.next()) { if (unprocessed_tile.offsetMatchingWithTile(&tile)) |offset| { const next = coord.add(offset); self.range.amend(next); try self.tile_map.putNoClobber(next, unprocessed_tile); try self.queue.append(next); _ = self.unprocessed_tiles.swapRemove(idx); continue :outer; } } idx += 1; } } } }; const Tile = struct { const VECTOR_SIZE: usize = 10; id: u16, matrix: aoc.SquareMatrix, fn fromGroup(group: []const u8) !Tile { var tile = Tile { .id = try std.fmt.parseInt(u16, group[5..9], 10), .matrix = aoc.SquareMatrix.init(VECTOR_SIZE), }; var coord = aoc.PredefinedCoord.ORIGIN; for (group[11..]) |c| { switch (c) { '#' => { tile.matrix.set(coord, 1); coord.col += 1; }, '.' => { tile.matrix.set(coord, 0); coord.col += 1; }, '\n' => { coord.row += 1; coord.col = 0; }, else => unreachable } } return tile; } fn deinit(self: *Tile) void { self.matrix.deinit(); } fn transformation_iterator(self: *Tile) MatrixTransformationIterator { return .{ .matrix = &self.matrix }; } fn offsetMatchingWithTile(self: *const Tile, other: *const Tile) ?aoc.Coord { if (self.topMatches(other)) { return aoc.PredefinedCoord.DOWN; } if (other.topMatches(self)) { return aoc.PredefinedCoord.UP; } if (self.leftMatches(other)) { return aoc.PredefinedCoord.RIGHT; } if (other.leftMatches(self)) { return aoc.PredefinedCoord.LEFT; } return null; } fn topMatches(self: *const Tile, other: *const Tile) bool { const other_bottom = other.matrix.submatrix(aoc.Coord.init(.{VECTOR_SIZE - 1, 0}), aoc.Coord.init(.{1, VECTOR_SIZE})); return self.matrix.submatrix(aoc.PredefinedCoord.ORIGIN, aoc.Coord.init(.{1, VECTOR_SIZE})).equals(&other_bottom); } fn leftMatches(self: *const Tile, other: *const Tile) bool { const other_right = other.matrix.submatrix(aoc.Coord.init(.{0, VECTOR_SIZE - 1}), aoc.Coord.init(.{VECTOR_SIZE, 1})); return self.matrix.submatrix(aoc.PredefinedCoord.ORIGIN, aoc.Coord.init(.{VECTOR_SIZE, 1})).equals(&other_right); } }; const Image = struct { const TILES_SIZE: usize = 12; const BORDERLESS_TILE_SIZE: usize = Tile.VECTOR_SIZE - 2; const ROW_BITS = TILES_SIZE * BORDERLESS_TILE_SIZE; const MONSTER_COORDS = [_]aoc.Coord { aoc.Coord.init(.{0, 18}), aoc.Coord.init(.{1, 0}), aoc.Coord.init(.{1, 5}), aoc.Coord.init(.{1, 6}), aoc.Coord.init(.{1, 11}), aoc.Coord.init(.{1, 12}), aoc.Coord.init(.{1, 17}), aoc.Coord.init(.{1, 18}), aoc.Coord.init(.{1, 19}), aoc.Coord.init(.{2, 1}), aoc.Coord.init(.{2, 4}), aoc.Coord.init(.{2, 7}), aoc.Coord.init(.{2, 10}), aoc.Coord.init(.{2, 13}), aoc.Coord.init(.{2, 16}), }; const MONSTER_LIMIT = aoc.Coord.init(.{3, 20}); matrix: aoc.SquareMatrix, roughness: usize, fn fromTileMap(tilemap: *const TileMap) Image { var matrix = aoc.SquareMatrix.init(ROW_BITS); var roughness: usize = 0; var tilemap_iter = tilemap.range.iterator(); while (tilemap_iter.next()) |tilemap_coord| { const image_superoffset = tilemap_coord.subtract(tilemap.range.first); const tile = tilemap.tile_map.get(tilemap_coord).?; var pixel_iter = aoc.CoordRangeIterator.init( aoc.PredefinedCoord.ORIGIN, aoc.Coord.init(.{BORDERLESS_TILE_SIZE - 1, BORDERLESS_TILE_SIZE - 1}) ); while (pixel_iter.next()) |pixel_coord| { if (tile.matrix.get(pixel_coord.add(aoc.Coord.init(.{1, 1}))) == 1) { roughness += 1; matrix.set(pixel_coord.add(image_superoffset.multiply(BORDERLESS_TILE_SIZE)), 1); } } } return .{ .matrix = matrix, .roughness = roughness }; } fn deinit(self: *Image) void { self.matrix.deinit(); } fn transformation_iterator(self: *Image) MatrixTransformationIterator { return .{ .matrix = &self.matrix }; } fn findMonsters(self: *Image) usize { var iter = self.transformation_iterator(); while (iter.next()) { var monsters: usize = 0; var range_iter = aoc.CoordRangeIterator.init( aoc.PredefinedCoord.ORIGIN, aoc.Coord.init(.{ROW_BITS - MONSTER_LIMIT.row - 1, ROW_BITS - MONSTER_LIMIT.col - 1}) ); outer: while (range_iter.next()) |coord| { for (MONSTER_COORDS) |monster_coord| { if (self.matrix.get(coord.add(monster_coord)) != 1) { continue :outer; } } monsters += 1; } if (monsters > 0) { return self.roughness - (MONSTER_COORDS.len * monsters); } } unreachable; } }; const MatrixTransformationIterator = struct { matrix: *aoc.SquareMatrix, counter: u4 = 0, fn next(self: *MatrixTransformationIterator) bool { if (self.counter == 8) { return false; } if (self.counter % 4 == 0) { self.matrix.flipHorizontally(); } self.matrix.rotate90DegreesClockwise(); self.counter += 1; return true; } }; pub fn run(problem: *aoc.Problem) !aoc.Solution { var tile_map = TileMap.init(problem.allocator); defer tile_map.deinit(); while (problem.group()) |group| { if (group.len != 0) { try tile_map.unprocessed_tiles.append(try Tile.fromGroup(group)); } } try tile_map.process(); const res1 = @intCast(usize, tile_map.tile_map.get(tile_map.range.first).?.id) * tile_map.tile_map.get(aoc.Coord.init(.{tile_map.range.first.row, tile_map.range.last.col})).?.id * tile_map.tile_map.get(aoc.Coord.init(.{tile_map.range.last.row, tile_map.range.first.col})).?.id * tile_map.tile_map.get(tile_map.range.last).?.id; var image = Image.fromTileMap(&tile_map); defer image.deinit(); const res2 = image.findMonsters(); return problem.solution(res1, res2); }
src/main/zig/2020/day20.zig
const builtin = @import("builtin"); const assertOrPanic = @import("std").debug.assertOrPanic; test "@sizeOf and @typeOf" { const y: @typeOf(x) = 120; assertOrPanic(@sizeOf(@typeOf(y)) == 2); } const x: u16 = 13; const z: @typeOf(x) = 19; const A = struct { a: u8, b: u32, c: u8, d: u3, e: u5, f: u16, g: u16, }; const P = packed struct { a: u8, b: u32, c: u8, d: u3, e: u5, f: u16, g: u16, }; test "@byteOffsetOf" { // Packed structs have fixed memory layout assertOrPanic(@byteOffsetOf(P, "a") == 0); assertOrPanic(@byteOffsetOf(P, "b") == 1); assertOrPanic(@byteOffsetOf(P, "c") == 5); assertOrPanic(@byteOffsetOf(P, "d") == 6); assertOrPanic(@byteOffsetOf(P, "e") == 6); assertOrPanic(@byteOffsetOf(P, "f") == 7); assertOrPanic(@byteOffsetOf(P, "g") == 9); // Normal struct fields can be moved/padded var a: A = undefined; assertOrPanic(@ptrToInt(&a.a) - @ptrToInt(&a) == @byteOffsetOf(A, "a")); assertOrPanic(@ptrToInt(&a.b) - @ptrToInt(&a) == @byteOffsetOf(A, "b")); assertOrPanic(@ptrToInt(&a.c) - @ptrToInt(&a) == @byteOffsetOf(A, "c")); assertOrPanic(@ptrToInt(&a.d) - @ptrToInt(&a) == @byteOffsetOf(A, "d")); assertOrPanic(@ptrToInt(&a.e) - @ptrToInt(&a) == @byteOffsetOf(A, "e")); assertOrPanic(@ptrToInt(&a.f) - @ptrToInt(&a) == @byteOffsetOf(A, "f")); assertOrPanic(@ptrToInt(&a.g) - @ptrToInt(&a) == @byteOffsetOf(A, "g")); } test "@bitOffsetOf" { // Packed structs have fixed memory layout assertOrPanic(@bitOffsetOf(P, "a") == 0); assertOrPanic(@bitOffsetOf(P, "b") == 8); assertOrPanic(@bitOffsetOf(P, "c") == 40); assertOrPanic(@bitOffsetOf(P, "d") == 48); assertOrPanic(@bitOffsetOf(P, "e") == 51); assertOrPanic(@bitOffsetOf(P, "f") == 56); assertOrPanic(@bitOffsetOf(P, "g") == 72); assertOrPanic(@byteOffsetOf(A, "a") * 8 == @bitOffsetOf(A, "a")); assertOrPanic(@byteOffsetOf(A, "b") * 8 == @bitOffsetOf(A, "b")); assertOrPanic(@byteOffsetOf(A, "c") * 8 == @bitOffsetOf(A, "c")); assertOrPanic(@byteOffsetOf(A, "d") * 8 == @bitOffsetOf(A, "d")); assertOrPanic(@byteOffsetOf(A, "e") * 8 == @bitOffsetOf(A, "e")); assertOrPanic(@byteOffsetOf(A, "f") * 8 == @bitOffsetOf(A, "f")); assertOrPanic(@byteOffsetOf(A, "g") * 8 == @bitOffsetOf(A, "g")); }
test/stage1/behavior/sizeof_and_typeof.zig
const std = @import("std"); const testing = std.testing; const fmt = std.fmt; const rand = std.rand; const mem = std.mem; const Allocator = std.mem.Allocator; pub fn concat(allocator: *Allocator, bufs: []const []const u8) []const u8 { if (std.mem.concat(allocator, u8, bufs)) |concated| { return concated; } else |err| { std.debug.print("error while concatnating, {}\n", .{err}); @panic("failed to concatnate"); } } pub fn intToString(buf: []u8, value: anytype) []u8 { return buf[0..fmt.formatIntBuf(buf, value, 10, false, fmt.FormatOptions{})]; } pub fn randRepeatString(output: []u8, comptime base: comptime_int, comptime max: comptime_int, comptime T: type, seed: u64) T { const repeated = [1]u8{base} ** max; var r = rand.DefaultPrng.init(seed); var len = r.random.int(T); mem.copy(u8, output, repeated[0..len]); return len; } test "concat" { const key: []const u8 = "key"; const val: []const u8 = "value"; var concated = concat(testing.allocator, &[2][]const u8{ key, val }); defer testing.allocator.free(concated); testing.expectEqualSlices(u8, "keyvalue", concated); } test "intToString" { var buffer: [100]u8 = undefined; testing.expectEqualSlices(u8, "1", intToString(&buffer, @as(u8, 1))); var i: usize = 1000; testing.expectEqualSlices(u8, "1000", intToString(&buffer, @as(u64, i))); } test "randRepeatString" { const base: comptime_int = 97; const max: comptime_int = 1024; var buf: [1024]u8 = undefined; var len = randRepeatString(&buf, base, max, u10, 0); testing.expectEqualSlices(u8, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", buf[0..len]); }
src/util.zig
pub const DIRECTDRAW_VERSION = @as(u32, 1792); pub const _FACDD = @as(u32, 2166); pub const CLSID_DirectDraw = Guid.initString("d7b70ee0-4340-11cf-b063-0020afc2cd35"); pub const CLSID_DirectDraw7 = Guid.initString("3c305196-50db-11d3-9cfe-00c04fd930c5"); pub const CLSID_DirectDrawClipper = Guid.initString("593817a0-7db3-11cf-a2de-00aa00b93356"); pub const DDENUM_ATTACHEDSECONDARYDEVICES = @as(i32, 1); pub const DDENUM_DETACHEDSECONDARYDEVICES = @as(i32, 2); pub const DDENUM_NONDISPLAYDEVICES = @as(i32, 4); pub const DDCREATE_HARDWAREONLY = @as(i32, 1); pub const DDCREATE_EMULATIONONLY = @as(i32, 2); pub const MAX_DDDEVICEID_STRING = @as(u32, 512); pub const DDGDI_GETHOSTIDENTIFIER = @as(i32, 1); pub const DDSD_CAPS = @as(i32, 1); pub const DDSD_HEIGHT = @as(i32, 2); pub const DDSD_WIDTH = @as(i32, 4); pub const DDSD_PITCH = @as(i32, 8); pub const DDSD_BACKBUFFERCOUNT = @as(i32, 32); pub const DDSD_ZBUFFERBITDEPTH = @as(i32, 64); pub const DDSD_ALPHABITDEPTH = @as(i32, 128); pub const DDSD_LPSURFACE = @as(i32, 2048); pub const DDSD_PIXELFORMAT = @as(i32, 4096); pub const DDSD_CKDESTOVERLAY = @as(i32, 8192); pub const DDSD_CKDESTBLT = @as(i32, 16384); pub const DDSD_CKSRCOVERLAY = @as(i32, 32768); pub const DDSD_CKSRCBLT = @as(i32, 65536); pub const DDSD_MIPMAPCOUNT = @as(i32, 131072); pub const DDSD_REFRESHRATE = @as(i32, 262144); pub const DDSD_LINEARSIZE = @as(i32, 524288); pub const DDSD_TEXTURESTAGE = @as(i32, 1048576); pub const DDSD_FVF = @as(i32, 2097152); pub const DDSD_SRCVBHANDLE = @as(i32, 4194304); pub const DDSD_DEPTH = @as(i32, 8388608); pub const DDSD_ALL = @as(i32, 16775662); pub const DDOSD_GUID = @as(i32, 1); pub const DDOSD_COMPRESSION_RATIO = @as(i32, 2); pub const DDOSD_SCAPS = @as(i32, 4); pub const DDOSD_OSCAPS = @as(i32, 8); pub const DDOSD_ALL = @as(i32, 15); pub const DDOSDCAPS_OPTCOMPRESSED = @as(i32, 1); pub const DDOSDCAPS_OPTREORDERED = @as(i32, 2); pub const DDOSDCAPS_MONOLITHICMIPMAP = @as(i32, 4); pub const DDOSDCAPS_VALIDSCAPS = @as(i32, 805324800); pub const DDOSDCAPS_VALIDOSCAPS = @as(i32, 7); pub const DDCOLOR_BRIGHTNESS = @as(i32, 1); pub const DDCOLOR_CONTRAST = @as(i32, 2); pub const DDCOLOR_HUE = @as(i32, 4); pub const DDCOLOR_SATURATION = @as(i32, 8); pub const DDCOLOR_SHARPNESS = @as(i32, 16); pub const DDCOLOR_GAMMA = @as(i32, 32); pub const DDCOLOR_COLORENABLE = @as(i32, 64); pub const DDSCAPS_RESERVED1 = @as(i32, 1); pub const DDSCAPS_ALPHA = @as(i32, 2); pub const DDSCAPS_BACKBUFFER = @as(i32, 4); pub const DDSCAPS_COMPLEX = @as(i32, 8); pub const DDSCAPS_FLIP = @as(i32, 16); pub const DDSCAPS_FRONTBUFFER = @as(i32, 32); pub const DDSCAPS_OFFSCREENPLAIN = @as(i32, 64); pub const DDSCAPS_OVERLAY = @as(i32, 128); pub const DDSCAPS_PALETTE = @as(i32, 256); pub const DDSCAPS_PRIMARYSURFACE = @as(i32, 512); pub const DDSCAPS_RESERVED3 = @as(i32, 1024); pub const DDSCAPS_PRIMARYSURFACELEFT = @as(i32, 0); pub const DDSCAPS_SYSTEMMEMORY = @as(i32, 2048); pub const DDSCAPS_TEXTURE = @as(i32, 4096); pub const DDSCAPS_3DDEVICE = @as(i32, 8192); pub const DDSCAPS_VIDEOMEMORY = @as(i32, 16384); pub const DDSCAPS_VISIBLE = @as(i32, 32768); pub const DDSCAPS_WRITEONLY = @as(i32, 65536); pub const DDSCAPS_ZBUFFER = @as(i32, 131072); pub const DDSCAPS_OWNDC = @as(i32, 262144); pub const DDSCAPS_LIVEVIDEO = @as(i32, 524288); pub const DDSCAPS_HWCODEC = @as(i32, 1048576); pub const DDSCAPS_MODEX = @as(i32, 2097152); pub const DDSCAPS_MIPMAP = @as(i32, 4194304); pub const DDSCAPS_RESERVED2 = @as(i32, 8388608); pub const DDSCAPS_ALLOCONLOAD = @as(i32, 67108864); pub const DDSCAPS_VIDEOPORT = @as(i32, 134217728); pub const DDSCAPS_LOCALVIDMEM = @as(i32, 268435456); pub const DDSCAPS_NONLOCALVIDMEM = @as(i32, 536870912); pub const DDSCAPS_STANDARDVGAMODE = @as(i32, 1073741824); pub const DDSCAPS_OPTIMIZED = @as(i32, -2147483648); pub const DDSCAPS2_RESERVED4 = @as(i32, 2); pub const DDSCAPS2_HARDWAREDEINTERLACE = @as(i32, 0); pub const DDSCAPS2_HINTDYNAMIC = @as(i32, 4); pub const DDSCAPS2_HINTSTATIC = @as(i32, 8); pub const DDSCAPS2_TEXTUREMANAGE = @as(i32, 16); pub const DDSCAPS2_RESERVED1 = @as(i32, 32); pub const DDSCAPS2_RESERVED2 = @as(i32, 64); pub const DDSCAPS2_OPAQUE = @as(i32, 128); pub const DDSCAPS2_HINTANTIALIASING = @as(i32, 256); pub const DDSCAPS2_CUBEMAP = @as(i32, 512); pub const DDSCAPS2_CUBEMAP_POSITIVEX = @as(i32, 1024); pub const DDSCAPS2_CUBEMAP_NEGATIVEX = @as(i32, 2048); pub const DDSCAPS2_CUBEMAP_POSITIVEY = @as(i32, 4096); pub const DDSCAPS2_CUBEMAP_NEGATIVEY = @as(i32, 8192); pub const DDSCAPS2_CUBEMAP_POSITIVEZ = @as(i32, 16384); pub const DDSCAPS2_CUBEMAP_NEGATIVEZ = @as(i32, 32768); pub const DDSCAPS2_MIPMAPSUBLEVEL = @as(i32, 65536); pub const DDSCAPS2_D3DTEXTUREMANAGE = @as(i32, 131072); pub const DDSCAPS2_DONOTPERSIST = @as(i32, 262144); pub const DDSCAPS2_STEREOSURFACELEFT = @as(i32, 524288); pub const DDSCAPS2_VOLUME = @as(i32, 2097152); pub const DDSCAPS2_NOTUSERLOCKABLE = @as(i32, 4194304); pub const DDSCAPS2_POINTS = @as(i32, 8388608); pub const DDSCAPS2_RTPATCHES = @as(i32, 16777216); pub const DDSCAPS2_NPATCHES = @as(i32, 33554432); pub const DDSCAPS2_RESERVED3 = @as(i32, 67108864); pub const DDSCAPS2_DISCARDBACKBUFFER = @as(i32, 268435456); pub const DDSCAPS2_ENABLEALPHACHANNEL = @as(i32, 536870912); pub const DDSCAPS2_EXTENDEDFORMATPRIMARY = @as(i32, 1073741824); pub const DDSCAPS2_ADDITIONALPRIMARY = @as(i32, -2147483648); pub const DDSCAPS3_MULTISAMPLE_MASK = @as(i32, 31); pub const DDSCAPS3_MULTISAMPLE_QUALITY_MASK = @as(i32, 224); pub const DDSCAPS3_MULTISAMPLE_QUALITY_SHIFT = @as(u32, 5); pub const DDSCAPS3_RESERVED1 = @as(i32, 256); pub const DDSCAPS3_RESERVED2 = @as(i32, 512); pub const DDSCAPS3_LIGHTWEIGHTMIPMAP = @as(i32, 1024); pub const DDSCAPS3_AUTOGENMIPMAP = @as(i32, 2048); pub const DDSCAPS3_DMAP = @as(i32, 4096); pub const DDSCAPS3_CREATESHAREDRESOURCE = @as(i32, 8192); pub const DDSCAPS3_READONLYRESOURCE = @as(i32, 16384); pub const DDSCAPS3_OPENSHAREDRESOURCE = @as(i32, 32768); pub const DDCAPS_3D = @as(i32, 1); pub const DDCAPS_ALIGNBOUNDARYDEST = @as(i32, 2); pub const DDCAPS_ALIGNSIZEDEST = @as(i32, 4); pub const DDCAPS_ALIGNBOUNDARYSRC = @as(i32, 8); pub const DDCAPS_ALIGNSIZESRC = @as(i32, 16); pub const DDCAPS_ALIGNSTRIDE = @as(i32, 32); pub const DDCAPS_BLT = @as(i32, 64); pub const DDCAPS_BLTQUEUE = @as(i32, 128); pub const DDCAPS_BLTFOURCC = @as(i32, 256); pub const DDCAPS_BLTSTRETCH = @as(i32, 512); pub const DDCAPS_GDI = @as(i32, 1024); pub const DDCAPS_OVERLAY = @as(i32, 2048); pub const DDCAPS_OVERLAYCANTCLIP = @as(i32, 4096); pub const DDCAPS_OVERLAYFOURCC = @as(i32, 8192); pub const DDCAPS_OVERLAYSTRETCH = @as(i32, 16384); pub const DDCAPS_PALETTE = @as(i32, 32768); pub const DDCAPS_PALETTEVSYNC = @as(i32, 65536); pub const DDCAPS_READSCANLINE = @as(i32, 131072); pub const DDCAPS_RESERVED1 = @as(i32, 262144); pub const DDCAPS_VBI = @as(i32, 524288); pub const DDCAPS_ZBLTS = @as(i32, 1048576); pub const DDCAPS_ZOVERLAYS = @as(i32, 2097152); pub const DDCAPS_COLORKEY = @as(i32, 4194304); pub const DDCAPS_ALPHA = @as(i32, 8388608); pub const DDCAPS_COLORKEYHWASSIST = @as(i32, 16777216); pub const DDCAPS_NOHARDWARE = @as(i32, 33554432); pub const DDCAPS_BLTCOLORFILL = @as(i32, 67108864); pub const DDCAPS_BANKSWITCHED = @as(i32, 134217728); pub const DDCAPS_BLTDEPTHFILL = @as(i32, 268435456); pub const DDCAPS_CANCLIP = @as(i32, 536870912); pub const DDCAPS_CANCLIPSTRETCHED = @as(i32, 1073741824); pub const DDCAPS_CANBLTSYSMEM = @as(i32, -2147483648); pub const DDCAPS2_CERTIFIED = @as(i32, 1); pub const DDCAPS2_NO2DDURING3DSCENE = @as(i32, 2); pub const DDCAPS2_VIDEOPORT = @as(i32, 4); pub const DDCAPS2_AUTOFLIPOVERLAY = @as(i32, 8); pub const DDCAPS2_CANBOBINTERLEAVED = @as(i32, 16); pub const DDCAPS2_CANBOBNONINTERLEAVED = @as(i32, 32); pub const DDCAPS2_COLORCONTROLOVERLAY = @as(i32, 64); pub const DDCAPS2_COLORCONTROLPRIMARY = @as(i32, 128); pub const DDCAPS2_CANDROPZ16BIT = @as(i32, 256); pub const DDCAPS2_NONLOCALVIDMEM = @as(i32, 512); pub const DDCAPS2_NONLOCALVIDMEMCAPS = @as(i32, 1024); pub const DDCAPS2_NOPAGELOCKREQUIRED = @as(i32, 2048); pub const DDCAPS2_WIDESURFACES = @as(i32, 4096); pub const DDCAPS2_CANFLIPODDEVEN = @as(i32, 8192); pub const DDCAPS2_CANBOBHARDWARE = @as(i32, 16384); pub const DDCAPS2_COPYFOURCC = @as(i32, 32768); pub const DDCAPS2_PRIMARYGAMMA = @as(i32, 131072); pub const DDCAPS2_CANRENDERWINDOWED = @as(i32, 524288); pub const DDCAPS2_CANCALIBRATEGAMMA = @as(i32, 1048576); pub const DDCAPS2_FLIPINTERVAL = @as(i32, 2097152); pub const DDCAPS2_FLIPNOVSYNC = @as(i32, 4194304); pub const DDCAPS2_CANMANAGETEXTURE = @as(i32, 8388608); pub const DDCAPS2_TEXMANINNONLOCALVIDMEM = @as(i32, 16777216); pub const DDCAPS2_STEREO = @as(i32, 33554432); pub const DDCAPS2_SYSTONONLOCAL_AS_SYSTOLOCAL = @as(i32, 67108864); pub const DDCAPS2_RESERVED1 = @as(i32, 134217728); pub const DDCAPS2_CANMANAGERESOURCE = @as(i32, 268435456); pub const DDCAPS2_DYNAMICTEXTURES = @as(i32, 536870912); pub const DDCAPS2_CANAUTOGENMIPMAP = @as(i32, 1073741824); pub const DDCAPS2_CANSHARERESOURCE = @as(i32, -2147483648); pub const DDFXALPHACAPS_BLTALPHAEDGEBLEND = @as(i32, 1); pub const DDFXALPHACAPS_BLTALPHAPIXELS = @as(i32, 2); pub const DDFXALPHACAPS_BLTALPHAPIXELSNEG = @as(i32, 4); pub const DDFXALPHACAPS_BLTALPHASURFACES = @as(i32, 8); pub const DDFXALPHACAPS_BLTALPHASURFACESNEG = @as(i32, 16); pub const DDFXALPHACAPS_OVERLAYALPHAEDGEBLEND = @as(i32, 32); pub const DDFXALPHACAPS_OVERLAYALPHAPIXELS = @as(i32, 64); pub const DDFXALPHACAPS_OVERLAYALPHAPIXELSNEG = @as(i32, 128); pub const DDFXALPHACAPS_OVERLAYALPHASURFACES = @as(i32, 256); pub const DDFXALPHACAPS_OVERLAYALPHASURFACESNEG = @as(i32, 512); pub const DDFXCAPS_BLTARITHSTRETCHY = @as(i32, 32); pub const DDFXCAPS_BLTARITHSTRETCHYN = @as(i32, 16); pub const DDFXCAPS_BLTMIRRORLEFTRIGHT = @as(i32, 64); pub const DDFXCAPS_BLTMIRRORUPDOWN = @as(i32, 128); pub const DDFXCAPS_BLTROTATION = @as(i32, 256); pub const DDFXCAPS_BLTROTATION90 = @as(i32, 512); pub const DDFXCAPS_BLTSHRINKX = @as(i32, 1024); pub const DDFXCAPS_BLTSHRINKXN = @as(i32, 2048); pub const DDFXCAPS_BLTSHRINKY = @as(i32, 4096); pub const DDFXCAPS_BLTSHRINKYN = @as(i32, 8192); pub const DDFXCAPS_BLTSTRETCHX = @as(i32, 16384); pub const DDFXCAPS_BLTSTRETCHXN = @as(i32, 32768); pub const DDFXCAPS_BLTSTRETCHY = @as(i32, 65536); pub const DDFXCAPS_BLTSTRETCHYN = @as(i32, 131072); pub const DDFXCAPS_OVERLAYARITHSTRETCHY = @as(i32, 262144); pub const DDFXCAPS_OVERLAYARITHSTRETCHYN = @as(i32, 8); pub const DDFXCAPS_OVERLAYSHRINKX = @as(i32, 524288); pub const DDFXCAPS_OVERLAYSHRINKXN = @as(i32, 1048576); pub const DDFXCAPS_OVERLAYSHRINKY = @as(i32, 2097152); pub const DDFXCAPS_OVERLAYSHRINKYN = @as(i32, 4194304); pub const DDFXCAPS_OVERLAYSTRETCHX = @as(i32, 8388608); pub const DDFXCAPS_OVERLAYSTRETCHXN = @as(i32, 16777216); pub const DDFXCAPS_OVERLAYSTRETCHY = @as(i32, 33554432); pub const DDFXCAPS_OVERLAYSTRETCHYN = @as(i32, 67108864); pub const DDFXCAPS_OVERLAYMIRRORLEFTRIGHT = @as(i32, 134217728); pub const DDFXCAPS_OVERLAYMIRRORUPDOWN = @as(i32, 268435456); pub const DDFXCAPS_OVERLAYDEINTERLACE = @as(i32, 536870912); pub const DDFXCAPS_BLTALPHA = @as(i32, 1); pub const DDFXCAPS_BLTFILTER = @as(i32, 32); pub const DDFXCAPS_OVERLAYALPHA = @as(i32, 4); pub const DDFXCAPS_OVERLAYFILTER = @as(i32, 262144); pub const DDSVCAPS_RESERVED1 = @as(i32, 1); pub const DDSVCAPS_RESERVED2 = @as(i32, 2); pub const DDSVCAPS_RESERVED3 = @as(i32, 4); pub const DDSVCAPS_RESERVED4 = @as(i32, 8); pub const DDSVCAPS_STEREOSEQUENTIAL = @as(i32, 16); pub const DDPCAPS_4BIT = @as(i32, 1); pub const DDPCAPS_8BITENTRIES = @as(i32, 2); pub const DDPCAPS_8BIT = @as(i32, 4); pub const DDPCAPS_INITIALIZE = @as(i32, 0); pub const DDPCAPS_PRIMARYSURFACE = @as(i32, 16); pub const DDPCAPS_PRIMARYSURFACELEFT = @as(i32, 32); pub const DDPCAPS_ALLOW256 = @as(i32, 64); pub const DDPCAPS_VSYNC = @as(i32, 128); pub const DDPCAPS_1BIT = @as(i32, 256); pub const DDPCAPS_2BIT = @as(i32, 512); pub const DDPCAPS_ALPHA = @as(i32, 1024); pub const DDSPD_IUNKNOWNPOINTER = @as(i32, 1); pub const DDSPD_VOLATILE = @as(i32, 2); pub const DDBD_1 = @as(i32, 16384); pub const DDBD_2 = @as(i32, 8192); pub const DDBD_4 = @as(i32, 4096); pub const DDBD_8 = @as(i32, 2048); pub const DDBD_16 = @as(i32, 1024); pub const DDBD_24 = @as(i32, 512); pub const DDBD_32 = @as(i32, 256); pub const DDCKEY_COLORSPACE = @as(i32, 1); pub const DDCKEY_DESTBLT = @as(i32, 2); pub const DDCKEY_DESTOVERLAY = @as(i32, 4); pub const DDCKEY_SRCBLT = @as(i32, 8); pub const DDCKEY_SRCOVERLAY = @as(i32, 16); pub const DDCKEYCAPS_DESTBLT = @as(i32, 1); pub const DDCKEYCAPS_DESTBLTCLRSPACE = @as(i32, 2); pub const DDCKEYCAPS_DESTBLTCLRSPACEYUV = @as(i32, 4); pub const DDCKEYCAPS_DESTBLTYUV = @as(i32, 8); pub const DDCKEYCAPS_DESTOVERLAY = @as(i32, 16); pub const DDCKEYCAPS_DESTOVERLAYCLRSPACE = @as(i32, 32); pub const DDCKEYCAPS_DESTOVERLAYCLRSPACEYUV = @as(i32, 64); pub const DDCKEYCAPS_DESTOVERLAYONEACTIVE = @as(i32, 128); pub const DDCKEYCAPS_DESTOVERLAYYUV = @as(i32, 256); pub const DDCKEYCAPS_SRCBLT = @as(i32, 512); pub const DDCKEYCAPS_SRCBLTCLRSPACE = @as(i32, 1024); pub const DDCKEYCAPS_SRCBLTCLRSPACEYUV = @as(i32, 2048); pub const DDCKEYCAPS_SRCBLTYUV = @as(i32, 4096); pub const DDCKEYCAPS_SRCOVERLAY = @as(i32, 8192); pub const DDCKEYCAPS_SRCOVERLAYCLRSPACE = @as(i32, 16384); pub const DDCKEYCAPS_SRCOVERLAYCLRSPACEYUV = @as(i32, 32768); pub const DDCKEYCAPS_SRCOVERLAYONEACTIVE = @as(i32, 65536); pub const DDCKEYCAPS_SRCOVERLAYYUV = @as(i32, 131072); pub const DDCKEYCAPS_NOCOSTOVERLAY = @as(i32, 262144); pub const DDPF_ALPHAPIXELS = @as(i32, 1); pub const DDPF_ALPHA = @as(i32, 2); pub const DDPF_FOURCC = @as(i32, 4); pub const DDPF_PALETTEINDEXED4 = @as(i32, 8); pub const DDPF_PALETTEINDEXEDTO8 = @as(i32, 16); pub const DDPF_PALETTEINDEXED8 = @as(i32, 32); pub const DDPF_RGB = @as(i32, 64); pub const DDPF_COMPRESSED = @as(i32, 128); pub const DDPF_RGBTOYUV = @as(i32, 256); pub const DDPF_YUV = @as(i32, 512); pub const DDPF_ZBUFFER = @as(i32, 1024); pub const DDPF_PALETTEINDEXED1 = @as(i32, 2048); pub const DDPF_PALETTEINDEXED2 = @as(i32, 4096); pub const DDPF_ZPIXELS = @as(i32, 8192); pub const DDPF_STENCILBUFFER = @as(i32, 16384); pub const DDPF_ALPHAPREMULT = @as(i32, 32768); pub const DDPF_LUMINANCE = @as(i32, 131072); pub const DDPF_BUMPLUMINANCE = @as(i32, 262144); pub const DDPF_BUMPDUDV = @as(i32, 524288); pub const DDENUMSURFACES_ALL = @as(i32, 1); pub const DDENUMSURFACES_MATCH = @as(i32, 2); pub const DDENUMSURFACES_NOMATCH = @as(i32, 4); pub const DDENUMSURFACES_CANBECREATED = @as(i32, 8); pub const DDENUMSURFACES_DOESEXIST = @as(i32, 16); pub const DDSDM_STANDARDVGAMODE = @as(i32, 1); pub const DDEDM_REFRESHRATES = @as(i32, 1); pub const DDEDM_STANDARDVGAMODES = @as(i32, 2); pub const DDSCL_FULLSCREEN = @as(i32, 1); pub const DDSCL_ALLOWREBOOT = @as(i32, 2); pub const DDSCL_NOWINDOWCHANGES = @as(i32, 4); pub const DDSCL_NORMAL = @as(i32, 8); pub const DDSCL_EXCLUSIVE = @as(i32, 16); pub const DDSCL_ALLOWMODEX = @as(i32, 64); pub const DDSCL_SETFOCUSWINDOW = @as(i32, 128); pub const DDSCL_SETDEVICEWINDOW = @as(i32, 256); pub const DDSCL_CREATEDEVICEWINDOW = @as(i32, 512); pub const DDSCL_MULTITHREADED = @as(i32, 1024); pub const DDSCL_FPUSETUP = @as(i32, 2048); pub const DDSCL_FPUPRESERVE = @as(i32, 4096); pub const DDBLT_ALPHADEST = @as(i32, 1); pub const DDBLT_ALPHADESTCONSTOVERRIDE = @as(i32, 2); pub const DDBLT_ALPHADESTNEG = @as(i32, 4); pub const DDBLT_ALPHADESTSURFACEOVERRIDE = @as(i32, 8); pub const DDBLT_ALPHAEDGEBLEND = @as(i32, 16); pub const DDBLT_ALPHASRC = @as(i32, 32); pub const DDBLT_ALPHASRCCONSTOVERRIDE = @as(i32, 64); pub const DDBLT_ALPHASRCNEG = @as(i32, 128); pub const DDBLT_ALPHASRCSURFACEOVERRIDE = @as(i32, 256); pub const DDBLT_ASYNC = @as(i32, 512); pub const DDBLT_COLORFILL = @as(i32, 1024); pub const DDBLT_DDFX = @as(i32, 2048); pub const DDBLT_DDROPS = @as(i32, 4096); pub const DDBLT_KEYDEST = @as(i32, 8192); pub const DDBLT_KEYDESTOVERRIDE = @as(i32, 16384); pub const DDBLT_KEYSRC = @as(i32, 32768); pub const DDBLT_KEYSRCOVERRIDE = @as(i32, 65536); pub const DDBLT_ROP = @as(i32, 131072); pub const DDBLT_ROTATIONANGLE = @as(i32, 262144); pub const DDBLT_ZBUFFER = @as(i32, 524288); pub const DDBLT_ZBUFFERDESTCONSTOVERRIDE = @as(i32, 1048576); pub const DDBLT_ZBUFFERDESTOVERRIDE = @as(i32, 2097152); pub const DDBLT_ZBUFFERSRCCONSTOVERRIDE = @as(i32, 4194304); pub const DDBLT_ZBUFFERSRCOVERRIDE = @as(i32, 8388608); pub const DDBLT_WAIT = @as(i32, 16777216); pub const DDBLT_DEPTHFILL = @as(i32, 33554432); pub const DDBLT_DONOTWAIT = @as(i32, 134217728); pub const DDBLT_PRESENTATION = @as(i32, 268435456); pub const DDBLT_LAST_PRESENTATION = @as(i32, 536870912); pub const DDBLT_EXTENDED_FLAGS = @as(i32, 1073741824); pub const DDBLT_EXTENDED_LINEAR_CONTENT = @as(i32, 4); pub const DDBLTFAST_NOCOLORKEY = @as(u32, 0); pub const DDBLTFAST_SRCCOLORKEY = @as(u32, 1); pub const DDBLTFAST_DESTCOLORKEY = @as(u32, 2); pub const DDBLTFAST_WAIT = @as(u32, 16); pub const DDBLTFAST_DONOTWAIT = @as(u32, 32); pub const DDFLIP_WAIT = @as(i32, 1); pub const DDFLIP_EVEN = @as(i32, 2); pub const DDFLIP_ODD = @as(i32, 4); pub const DDFLIP_NOVSYNC = @as(i32, 8); pub const DDFLIP_INTERVAL2 = @as(i32, 33554432); pub const DDFLIP_INTERVAL3 = @as(i32, 50331648); pub const DDFLIP_INTERVAL4 = @as(i32, 67108864); pub const DDFLIP_STEREO = @as(i32, 16); pub const DDFLIP_DONOTWAIT = @as(i32, 32); pub const DDOVER_ALPHADEST = @as(i32, 1); pub const DDOVER_ALPHADESTCONSTOVERRIDE = @as(i32, 2); pub const DDOVER_ALPHADESTNEG = @as(i32, 4); pub const DDOVER_ALPHADESTSURFACEOVERRIDE = @as(i32, 8); pub const DDOVER_ALPHAEDGEBLEND = @as(i32, 16); pub const DDOVER_ALPHASRC = @as(i32, 32); pub const DDOVER_ALPHASRCCONSTOVERRIDE = @as(i32, 64); pub const DDOVER_ALPHASRCNEG = @as(i32, 128); pub const DDOVER_ALPHASRCSURFACEOVERRIDE = @as(i32, 256); pub const DDOVER_HIDE = @as(i32, 512); pub const DDOVER_KEYDEST = @as(i32, 1024); pub const DDOVER_KEYDESTOVERRIDE = @as(i32, 2048); pub const DDOVER_KEYSRC = @as(i32, 4096); pub const DDOVER_KEYSRCOVERRIDE = @as(i32, 8192); pub const DDOVER_SHOW = @as(i32, 16384); pub const DDOVER_ADDDIRTYRECT = @as(i32, 32768); pub const DDOVER_REFRESHDIRTYRECTS = @as(i32, 65536); pub const DDOVER_REFRESHALL = @as(i32, 131072); pub const DDOVER_DDFX = @as(i32, 524288); pub const DDOVER_AUTOFLIP = @as(i32, 1048576); pub const DDOVER_BOB = @as(i32, 2097152); pub const DDOVER_OVERRIDEBOBWEAVE = @as(i32, 4194304); pub const DDOVER_INTERLEAVED = @as(i32, 8388608); pub const DDOVER_BOBHARDWARE = @as(i32, 16777216); pub const DDOVER_ARGBSCALEFACTORS = @as(i32, 33554432); pub const DDOVER_DEGRADEARGBSCALING = @as(i32, 67108864); pub const DDSETSURFACEDESC_RECREATEDC = @as(i32, 0); pub const DDSETSURFACEDESC_PRESERVEDC = @as(i32, 1); pub const DDLOCK_SURFACEMEMORYPTR = @as(i32, 0); pub const DDLOCK_WAIT = @as(i32, 1); pub const DDLOCK_EVENT = @as(i32, 2); pub const DDLOCK_READONLY = @as(i32, 16); pub const DDLOCK_WRITEONLY = @as(i32, 32); pub const DDLOCK_NOSYSLOCK = @as(i32, 2048); pub const DDLOCK_NOOVERWRITE = @as(i32, 4096); pub const DDLOCK_DISCARDCONTENTS = @as(i32, 8192); pub const DDLOCK_OKTOSWAP = @as(i32, 8192); pub const DDLOCK_DONOTWAIT = @as(i32, 16384); pub const DDLOCK_HASVOLUMETEXTUREBOXRECT = @as(i32, 32768); pub const DDLOCK_NODIRTYUPDATE = @as(i32, 65536); pub const DDBLTFX_ARITHSTRETCHY = @as(i32, 1); pub const DDBLTFX_MIRRORLEFTRIGHT = @as(i32, 2); pub const DDBLTFX_MIRRORUPDOWN = @as(i32, 4); pub const DDBLTFX_NOTEARING = @as(i32, 8); pub const DDBLTFX_ROTATE180 = @as(i32, 16); pub const DDBLTFX_ROTATE270 = @as(i32, 32); pub const DDBLTFX_ROTATE90 = @as(i32, 64); pub const DDBLTFX_ZBUFFERRANGE = @as(i32, 128); pub const DDBLTFX_ZBUFFERBASEDEST = @as(i32, 256); pub const DDOVERFX_ARITHSTRETCHY = @as(i32, 1); pub const DDOVERFX_MIRRORLEFTRIGHT = @as(i32, 2); pub const DDOVERFX_MIRRORUPDOWN = @as(i32, 4); pub const DDOVERFX_DEINTERLACE = @as(i32, 8); pub const DDWAITVB_BLOCKBEGIN = @as(i32, 1); pub const DDWAITVB_BLOCKBEGINEVENT = @as(i32, 2); pub const DDWAITVB_BLOCKEND = @as(i32, 4); pub const DDGFS_CANFLIP = @as(i32, 1); pub const DDGFS_ISFLIPDONE = @as(i32, 2); pub const DDGBS_CANBLT = @as(i32, 1); pub const DDGBS_ISBLTDONE = @as(i32, 2); pub const DDENUMOVERLAYZ_BACKTOFRONT = @as(i32, 0); pub const DDENUMOVERLAYZ_FRONTTOBACK = @as(i32, 1); pub const DDOVERZ_SENDTOFRONT = @as(i32, 0); pub const DDOVERZ_SENDTOBACK = @as(i32, 1); pub const DDOVERZ_MOVEFORWARD = @as(i32, 2); pub const DDOVERZ_MOVEBACKWARD = @as(i32, 3); pub const DDOVERZ_INSERTINFRONTOF = @as(i32, 4); pub const DDOVERZ_INSERTINBACKOF = @as(i32, 5); pub const DDSGR_CALIBRATE = @as(i32, 1); pub const DDSMT_ISTESTREQUIRED = @as(i32, 1); pub const DDEM_MODEPASSED = @as(i32, 1); pub const DDEM_MODEFAILED = @as(i32, 2); pub const DDENUMRET_CANCEL = @as(u32, 0); pub const DDENUMRET_OK = @as(u32, 1); pub const DDERR_NOTINITIALIZED = @as(i32, -2147221008); pub const OBJECT_ISROOT = @as(i32, -2147483648); pub const DDUNSUPPORTEDMODE = @as(u32, 4294967295); pub const GUID_MiscellaneousCallbacks = Guid.initString("efd60cc0-49e7-11d0-889d-00aa00bbb76a"); pub const GUID_VideoPortCallbacks = Guid.initString("efd60cc1-49e7-11d0-889d-00aa00bbb76a"); pub const GUID_ColorControlCallbacks = Guid.initString("efd60cc2-49e7-11d0-889d-00aa00bbb76a"); pub const GUID_VideoPortCaps = Guid.initString("efd60cc3-49e7-11d0-889d-00aa00bbb76a"); pub const GUID_D3DCallbacks2 = Guid.initString("0ba584e1-70b6-11d0-889d-00aa00bbb76a"); pub const GUID_D3DCallbacks3 = Guid.initString("ddf41230-ec0a-11d0-a9b6-00aa00c0993e"); pub const GUID_NonLocalVidMemCaps = Guid.initString("86c4fa80-8d84-11d0-94e8-00c04fc34137"); pub const GUID_KernelCallbacks = Guid.initString("80863800-6b06-11d0-9b06-00a0c903a3b8"); pub const GUID_KernelCaps = Guid.initString("ffaa7540-7aa8-11d0-9b06-00a0c903a3b8"); pub const GUID_D3DExtendedCaps = Guid.initString("7de41f80-9d93-11d0-89ab-00a0c9054129"); pub const GUID_ZPixelFormats = Guid.initString("93869880-36cf-11d1-9b1b-00aa00bbb8ae"); pub const GUID_DDMoreSurfaceCaps = Guid.initString("3b8a0466-f269-11d1-880b-00c04fd930c5"); pub const GUID_DDStereoMode = Guid.initString("f828169c-a8e8-11d2-a1f2-00a0c983eaf6"); pub const GUID_OptSurfaceKmodeInfo = Guid.initString("e05c8472-51d4-11d1-8cce-00a0c90629a8"); pub const GUID_OptSurfaceUmodeInfo = Guid.initString("9d792804-5fa8-11d1-8cd0-00a0c90629a8"); pub const GUID_UserModeDriverInfo = Guid.initString("f0b0e8e2-5f97-11d1-8cd0-00a0c906<PASSWORD>"); pub const GUID_UserModeDriverPassword = Guid.initString("<PASSWORD>"); pub const GUID_D3DParseUnknownCommandCallback = Guid.initString("2e04ffa0-98e4-11d1-8ce1-00a0c90629a8"); pub const GUID_MotionCompCallbacks = Guid.initString("b1122b40-5da5-11d1-8fcf-00c04fc29b4e"); pub const GUID_Miscellaneous2Callbacks = Guid.initString("406b2f00-3e5a-11d1-b640-00aa00a1f96a"); pub const DDPF_NOVEL_TEXTURE_FORMAT = @as(i32, 1048576); pub const DDPF_D3DFORMAT = @as(i32, 2097152); pub const D3DFORMAT_OP_TEXTURE = @as(i32, 1); pub const D3DFORMAT_OP_VOLUMETEXTURE = @as(i32, 2); pub const D3DFORMAT_OP_CUBETEXTURE = @as(i32, 4); pub const D3DFORMAT_OP_OFFSCREEN_RENDERTARGET = @as(i32, 8); pub const D3DFORMAT_OP_SAME_FORMAT_RENDERTARGET = @as(i32, 16); pub const D3DFORMAT_OP_ZSTENCIL = @as(i32, 64); pub const D3DFORMAT_OP_ZSTENCIL_WITH_ARBITRARY_COLOR_DEPTH = @as(i32, 128); pub const D3DFORMAT_OP_SAME_FORMAT_UP_TO_ALPHA_RENDERTARGET = @as(i32, 256); pub const D3DFORMAT_OP_DISPLAYMODE = @as(i32, 1024); pub const D3DFORMAT_OP_3DACCELERATION = @as(i32, 2048); pub const D3DFORMAT_OP_PIXELSIZE = @as(i32, 4096); pub const D3DFORMAT_OP_CONVERT_TO_ARGB = @as(i32, 8192); pub const D3DFORMAT_OP_OFFSCREENPLAIN = @as(i32, 16384); pub const D3DFORMAT_OP_SRGBREAD = @as(i32, 32768); pub const D3DFORMAT_OP_BUMPMAP = @as(i32, 65536); pub const D3DFORMAT_OP_DMAP = @as(i32, 131072); pub const D3DFORMAT_OP_NOFILTER = @as(i32, 262144); pub const D3DFORMAT_MEMBEROFGROUP_ARGB = @as(i32, 524288); pub const D3DFORMAT_OP_SRGBWRITE = @as(i32, 1048576); pub const D3DFORMAT_OP_NOALPHABLEND = @as(i32, 2097152); pub const D3DFORMAT_OP_AUTOGENMIPMAP = @as(i32, 4194304); pub const D3DFORMAT_OP_VERTEXTEXTURE = @as(i32, 8388608); pub const D3DFORMAT_OP_NOTEXCOORDWRAPNORMIP = @as(i32, 16777216); pub const DELETED_OK = @as(u32, 0); pub const DELETED_LASTONE = @as(u32, 1); pub const DELETED_NOTFOUND = @as(u32, 2); pub const DCICOMMAND = @as(u32, 3075); pub const DD_VERSION = @as(i32, 512); pub const DD_RUNTIME_VERSION = @as(i32, 2306); pub const DD_HAL_VERSION = @as(u32, 256); pub const DDCREATEDRIVEROBJECT = @as(u32, 10); pub const DDGET32BITDRIVERNAME = @as(u32, 11); pub const DDNEWCALLBACKFNS = @as(u32, 12); pub const DDVERSIONINFO = @as(u32, 13); pub const CCHDEVICENAME = @as(u32, 32); pub const MAX_DRIVER_NAME = @as(u32, 32); pub const MAX_PALETTE_SIZE = @as(u32, 256); pub const MAX_AUTOFLIP_BUFFERS = @as(u32, 10); pub const DDSCAPS_EXECUTEBUFFER = @as(i32, 8388608); pub const DDSCAPS2_VERTEXBUFFER = @as(i32, 32); pub const DDSCAPS2_COMMANDBUFFER = @as(i32, 64); pub const DDSCAPS2_INDEXBUFFER = @as(i32, 67108864); pub const DDSCAPS3_VIDEO = @as(i32, 512); pub const D3DFMT_INTERNAL_D32 = @as(u32, 71); pub const D3DFMT_INTERNAL_S1D15 = @as(u32, 72); pub const D3DFMT_INTERNAL_D15S1 = @as(u32, 73); pub const D3DFMT_INTERNAL_S8D24 = @as(u32, 74); pub const D3DFMT_INTERNAL_D24S8 = @as(u32, 75); pub const D3DFMT_INTERNAL_X8D24 = @as(u32, 76); pub const D3DFMT_INTERNAL_D24X8 = @as(u32, 77); pub const DDHAL_PLEASEALLOC_BLOCKSIZE = @as(i32, 2); pub const DDHAL_PLEASEALLOC_LINEARSIZE = @as(i32, 3); pub const VIDMEM_ISLINEAR = @as(i32, 1); pub const VIDMEM_ISRECTANGULAR = @as(i32, 2); pub const VIDMEM_ISHEAP = @as(i32, 4); pub const VIDMEM_ISNONLOCAL = @as(i32, 8); pub const VIDMEM_ISWC = @as(i32, 16); pub const VIDMEM_HEAPDISABLED = @as(i32, 32); pub const HEAPALIASINFO_MAPPEDREAL = @as(i32, 1); pub const HEAPALIASINFO_MAPPEDDUMMY = @as(i32, 2); pub const DDHAL_CB32_DESTROYDRIVER = @as(i32, 1); pub const DDHAL_CB32_CREATESURFACE = @as(i32, 2); pub const DDHAL_CB32_SETCOLORKEY = @as(i32, 4); pub const DDHAL_CB32_SETMODE = @as(i32, 8); pub const DDHAL_CB32_WAITFORVERTICALBLANK = @as(i32, 16); pub const DDHAL_CB32_CANCREATESURFACE = @as(i32, 32); pub const DDHAL_CB32_CREATEPALETTE = @as(i32, 64); pub const DDHAL_CB32_GETSCANLINE = @as(i32, 128); pub const DDHAL_CB32_SETEXCLUSIVEMODE = @as(i32, 256); pub const DDHAL_CB32_FLIPTOGDISURFACE = @as(i32, 512); pub const DDHAL_PALCB32_DESTROYPALETTE = @as(i32, 1); pub const DDHAL_PALCB32_SETENTRIES = @as(i32, 2); pub const DDHAL_SURFCB32_DESTROYSURFACE = @as(i32, 1); pub const DDHAL_SURFCB32_FLIP = @as(i32, 2); pub const DDHAL_SURFCB32_SETCLIPLIST = @as(i32, 4); pub const DDHAL_SURFCB32_LOCK = @as(i32, 8); pub const DDHAL_SURFCB32_UNLOCK = @as(i32, 16); pub const DDHAL_SURFCB32_BLT = @as(i32, 32); pub const DDHAL_SURFCB32_SETCOLORKEY = @as(i32, 64); pub const DDHAL_SURFCB32_ADDATTACHEDSURFACE = @as(i32, 128); pub const DDHAL_SURFCB32_GETBLTSTATUS = @as(i32, 256); pub const DDHAL_SURFCB32_GETFLIPSTATUS = @as(i32, 512); pub const DDHAL_SURFCB32_UPDATEOVERLAY = @as(i32, 1024); pub const DDHAL_SURFCB32_SETOVERLAYPOSITION = @as(i32, 2048); pub const DDHAL_SURFCB32_RESERVED4 = @as(i32, 4096); pub const DDHAL_SURFCB32_SETPALETTE = @as(i32, 8192); pub const DDHAL_MISCCB32_GETAVAILDRIVERMEMORY = @as(i32, 1); pub const DDHAL_MISCCB32_UPDATENONLOCALHEAP = @as(i32, 2); pub const DDHAL_MISCCB32_GETHEAPALIGNMENT = @as(i32, 4); pub const DDHAL_MISCCB32_GETSYSMEMBLTSTATUS = @as(i32, 8); pub const DDHAL_MISC2CB32_CREATESURFACEEX = @as(i32, 2); pub const DDHAL_MISC2CB32_GETDRIVERSTATE = @as(i32, 4); pub const DDHAL_MISC2CB32_DESTROYDDLOCAL = @as(i32, 8); pub const DDHAL_EXEBUFCB32_CANCREATEEXEBUF = @as(i32, 1); pub const DDHAL_EXEBUFCB32_CREATEEXEBUF = @as(i32, 2); pub const DDHAL_EXEBUFCB32_DESTROYEXEBUF = @as(i32, 4); pub const DDHAL_EXEBUFCB32_LOCKEXEBUF = @as(i32, 8); pub const DDHAL_EXEBUFCB32_UNLOCKEXEBUF = @as(i32, 16); pub const DDHAL_VPORT32_CANCREATEVIDEOPORT = @as(i32, 1); pub const DDHAL_VPORT32_CREATEVIDEOPORT = @as(i32, 2); pub const DDHAL_VPORT32_FLIP = @as(i32, 4); pub const DDHAL_VPORT32_GETBANDWIDTH = @as(i32, 8); pub const DDHAL_VPORT32_GETINPUTFORMATS = @as(i32, 16); pub const DDHAL_VPORT32_GETOUTPUTFORMATS = @as(i32, 32); pub const DDHAL_VPORT32_GETFIELD = @as(i32, 128); pub const DDHAL_VPORT32_GETLINE = @as(i32, 256); pub const DDHAL_VPORT32_GETCONNECT = @as(i32, 512); pub const DDHAL_VPORT32_DESTROY = @as(i32, 1024); pub const DDHAL_VPORT32_GETFLIPSTATUS = @as(i32, 2048); pub const DDHAL_VPORT32_UPDATE = @as(i32, 4096); pub const DDHAL_VPORT32_WAITFORSYNC = @as(i32, 8192); pub const DDHAL_VPORT32_GETSIGNALSTATUS = @as(i32, 16384); pub const DDHAL_VPORT32_COLORCONTROL = @as(i32, 32768); pub const DDHAL_COLOR_COLORCONTROL = @as(i32, 1); pub const DDHAL_KERNEL_SYNCSURFACEDATA = @as(i32, 1); pub const DDHAL_KERNEL_SYNCVIDEOPORTDATA = @as(i32, 2); pub const DDHAL_MOCOMP32_GETGUIDS = @as(u32, 1); pub const DDHAL_MOCOMP32_GETFORMATS = @as(u32, 2); pub const DDHAL_MOCOMP32_CREATE = @as(u32, 4); pub const DDHAL_MOCOMP32_GETCOMPBUFFINFO = @as(u32, 8); pub const DDHAL_MOCOMP32_GETINTERNALINFO = @as(u32, 16); pub const DDHAL_MOCOMP32_BEGINFRAME = @as(u32, 32); pub const DDHAL_MOCOMP32_ENDFRAME = @as(u32, 64); pub const DDHAL_MOCOMP32_RENDER = @as(u32, 128); pub const DDHAL_MOCOMP32_QUERYSTATUS = @as(u32, 256); pub const DDHAL_MOCOMP32_DESTROY = @as(u32, 512); pub const DDHAL_DRIVER_NOTHANDLED = @as(i32, 0); pub const DDHAL_DRIVER_HANDLED = @as(i32, 1); pub const DDHAL_DRIVER_NOCKEYHW = @as(i32, 2); pub const DDRAWIPAL_256 = @as(i32, 1); pub const DDRAWIPAL_16 = @as(i32, 2); pub const DDRAWIPAL_GDI = @as(i32, 4); pub const DDRAWIPAL_STORED_8 = @as(i32, 8); pub const DDRAWIPAL_STORED_16 = @as(i32, 16); pub const DDRAWIPAL_STORED_24 = @as(i32, 32); pub const DDRAWIPAL_EXCLUSIVE = @as(i32, 64); pub const DDRAWIPAL_INHEL = @as(i32, 128); pub const DDRAWIPAL_DIRTY = @as(i32, 256); pub const DDRAWIPAL_ALLOW256 = @as(i32, 512); pub const DDRAWIPAL_4 = @as(i32, 1024); pub const DDRAWIPAL_2 = @as(i32, 2048); pub const DDRAWIPAL_STORED_8INDEX = @as(i32, 4096); pub const DDRAWIPAL_ALPHA = @as(i32, 8192); pub const DDRAWICLIP_WATCHWINDOW = @as(i32, 1); pub const DDRAWICLIP_ISINITIALIZED = @as(i32, 2); pub const DDRAWICLIP_INMASTERSPRITELIST = @as(i32, 4); pub const DDAL_IMPLICIT = @as(i32, 1); pub const ACCESSRECT_VRAMSTYLE = @as(i32, 1); pub const ACCESSRECT_NOTHOLDINGWIN16LOCK = @as(i32, 2); pub const ACCESSRECT_BROKEN = @as(i32, 4); pub const PFINDEX_UNINITIALIZED = @as(u32, 0); pub const DDRAWISURFGBL_MEMFREE = @as(i32, 1); pub const DDRAWISURFGBL_SYSMEMREQUESTED = @as(i32, 2); pub const DDRAWISURFGBL_ISGDISURFACE = @as(i32, 4); pub const DDRAWISURFGBL_SOFTWAREAUTOFLIP = @as(i32, 8); pub const DDRAWISURFGBL_LOCKNOTHOLDINGWIN16LOCK = @as(i32, 16); pub const DDRAWISURFGBL_LOCKVRAMSTYLE = @as(i32, 32); pub const DDRAWISURFGBL_LOCKBROKEN = @as(i32, 64); pub const DDRAWISURFGBL_IMPLICITHANDLE = @as(i32, 128); pub const DDRAWISURFGBL_ISCLIENTMEM = @as(i32, 256); pub const DDRAWISURFGBL_HARDWAREOPSOURCE = @as(i32, 512); pub const DDRAWISURFGBL_HARDWAREOPDEST = @as(i32, 1024); pub const DDRAWISURFGBL_VPORTINTERLEAVED = @as(i32, 2048); pub const DDRAWISURFGBL_VPORTDATA = @as(i32, 4096); pub const DDRAWISURFGBL_LATEALLOCATELINEAR = @as(i32, 8192); pub const DDRAWISURFGBL_SYSMEMEXECUTEBUFFER = @as(i32, 16384); pub const DDRAWISURFGBL_FASTLOCKHELD = @as(i32, 32768); pub const DDRAWISURFGBL_READONLYLOCKHELD = @as(i32, 65536); pub const DDRAWISURFGBL_DX8SURFACE = @as(i32, 524288); pub const DDRAWISURFGBL_DDHELDONTFREE = @as(i32, 1048576); pub const DDRAWISURFGBL_NOTIFYWHENUNLOCKED = @as(i32, 2097152); pub const DDRAWISURFGBL_RESERVED0 = @as(i32, -2147483648); pub const DDRAWISURF_ATTACHED = @as(i32, 1); pub const DDRAWISURF_IMPLICITCREATE = @as(i32, 2); pub const DDRAWISURF_ISFREE = @as(i32, 4); pub const DDRAWISURF_ATTACHED_FROM = @as(i32, 8); pub const DDRAWISURF_IMPLICITROOT = @as(i32, 16); pub const DDRAWISURF_PARTOFPRIMARYCHAIN = @as(i32, 32); pub const DDRAWISURF_DATAISALIASED = @as(i32, 64); pub const DDRAWISURF_HASDC = @as(i32, 128); pub const DDRAWISURF_HASCKEYDESTOVERLAY = @as(i32, 256); pub const DDRAWISURF_HASCKEYDESTBLT = @as(i32, 512); pub const DDRAWISURF_HASCKEYSRCOVERLAY = @as(i32, 1024); pub const DDRAWISURF_HASCKEYSRCBLT = @as(i32, 2048); pub const DDRAWISURF_LOCKEXCLUDEDCURSOR = @as(i32, 4096); pub const DDRAWISURF_HASPIXELFORMAT = @as(i32, 8192); pub const DDRAWISURF_HASOVERLAYDATA = @as(i32, 16384); pub const DDRAWISURF_SETGAMMA = @as(i32, 32768); pub const DDRAWISURF_SW_CKEYDESTOVERLAY = @as(i32, 65536); pub const DDRAWISURF_SW_CKEYDESTBLT = @as(i32, 131072); pub const DDRAWISURF_SW_CKEYSRCOVERLAY = @as(i32, 262144); pub const DDRAWISURF_SW_CKEYSRCBLT = @as(i32, 524288); pub const DDRAWISURF_HW_CKEYDESTOVERLAY = @as(i32, 1048576); pub const DDRAWISURF_HW_CKEYDESTBLT = @as(i32, 2097152); pub const DDRAWISURF_HW_CKEYSRCOVERLAY = @as(i32, 4194304); pub const DDRAWISURF_HW_CKEYSRCBLT = @as(i32, 8388608); pub const DDRAWISURF_INMASTERSPRITELIST = @as(i32, 16777216); pub const DDRAWISURF_HELCB = @as(i32, 33554432); pub const DDRAWISURF_FRONTBUFFER = @as(i32, 67108864); pub const DDRAWISURF_BACKBUFFER = @as(i32, 134217728); pub const DDRAWISURF_INVALID = @as(i32, 268435456); pub const DDRAWISURF_DCIBUSY = @as(i32, 536870912); pub const DDRAWISURF_GETDCNULL = @as(i32, 1073741824); pub const DDRAWISURF_STEREOSURFACELEFT = @as(i32, 536870912); pub const DDRAWISURF_DRIVERMANAGED = @as(i32, 1073741824); pub const DDRAWISURF_DCILOCK = @as(i32, -2147483648); pub const ROP_HAS_SOURCE = @as(i32, 1); pub const ROP_HAS_PATTERN = @as(i32, 2); pub const DDMODEINFO_PALETTIZED = @as(u32, 1); pub const DDMODEINFO_MODEX = @as(u32, 2); pub const DDMODEINFO_UNSUPPORTED = @as(u32, 4); pub const DDMODEINFO_STANDARDVGA = @as(u32, 8); pub const DDMODEINFO_MAXREFRESH = @as(u32, 16); pub const DDMODEINFO_STEREO = @as(u32, 32); pub const DDRAWILCL_HASEXCLUSIVEMODE = @as(i32, 1); pub const DDRAWILCL_ISFULLSCREEN = @as(i32, 2); pub const DDRAWILCL_SETCOOPCALLED = @as(i32, 4); pub const DDRAWILCL_ACTIVEYES = @as(i32, 8); pub const DDRAWILCL_ACTIVENO = @as(i32, 16); pub const DDRAWILCL_HOOKEDHWND = @as(i32, 32); pub const DDRAWILCL_ALLOWMODEX = @as(i32, 64); pub const DDRAWILCL_V1SCLBEHAVIOUR = @as(i32, 128); pub const DDRAWILCL_MODEHASBEENCHANGED = @as(i32, 256); pub const DDRAWILCL_CREATEDWINDOW = @as(i32, 512); pub const DDRAWILCL_DIRTYDC = @as(i32, 1024); pub const DDRAWILCL_DISABLEINACTIVATE = @as(i32, 2048); pub const DDRAWILCL_CURSORCLIPPED = @as(i32, 4096); pub const DDRAWILCL_EXPLICITMONITOR = @as(i32, 8192); pub const DDRAWILCL_MULTITHREADED = @as(i32, 16384); pub const DDRAWILCL_FPUSETUP = @as(i32, 32768); pub const DDRAWILCL_POWEREDDOWN = @as(i32, 65536); pub const DDRAWILCL_DIRECTDRAW7 = @as(i32, 131072); pub const DDRAWILCL_ATTEMPTEDD3DCONTEXT = @as(i32, 262144); pub const DDRAWILCL_FPUPRESERVE = @as(i32, 524288); pub const DDRAWILCL_DX8DRIVER = @as(i32, 1048576); pub const DDRAWILCL_DIRECTDRAW8 = @as(i32, 2097152); pub const DDRAWI_xxxxxxxxx1 = @as(i32, 1); pub const DDRAWI_xxxxxxxxx2 = @as(i32, 2); pub const DDRAWI_VIRTUALDESKTOP = @as(i32, 8); pub const DDRAWI_MODEX = @as(i32, 16); pub const DDRAWI_DISPLAYDRV = @as(i32, 32); pub const DDRAWI_FULLSCREEN = @as(i32, 64); pub const DDRAWI_MODECHANGED = @as(i32, 128); pub const DDRAWI_NOHARDWARE = @as(i32, 256); pub const DDRAWI_PALETTEINIT = @as(i32, 512); pub const DDRAWI_NOEMULATION = @as(i32, 1024); pub const DDRAWI_HASCKEYDESTOVERLAY = @as(i32, 2048); pub const DDRAWI_HASCKEYSRCOVERLAY = @as(i32, 4096); pub const DDRAWI_HASGDIPALETTE = @as(i32, 8192); pub const DDRAWI_EMULATIONINITIALIZED = @as(i32, 16384); pub const DDRAWI_HASGDIPALETTE_EXCLUSIVE = @as(i32, 32768); pub const DDRAWI_MODEXILLEGAL = @as(i32, 65536); pub const DDRAWI_FLIPPEDTOGDI = @as(i32, 131072); pub const DDRAWI_NEEDSWIN16FORVRAMLOCK = @as(i32, 262144); pub const DDRAWI_PDEVICEVRAMBITCLEARED = @as(i32, 524288); pub const DDRAWI_STANDARDVGA = @as(i32, 1048576); pub const DDRAWI_EXTENDEDALIGNMENT = @as(i32, 2097152); pub const DDRAWI_CHANGINGMODE = @as(i32, 4194304); pub const DDRAWI_GDIDRV = @as(i32, 8388608); pub const DDRAWI_ATTACHEDTODESKTOP = @as(i32, 16777216); pub const DDRAWI_UMODELOADED = @as(i32, 33554432); pub const DDRAWI_DDRAWDATANOTFETCHED = @as(i32, 67108864); pub const DDRAWI_SECONDARYDRIVERLOADED = @as(i32, 134217728); pub const DDRAWI_TESTINGMODES = @as(i32, 268435456); pub const DDRAWI_DRIVERINFO2 = @as(i32, 536870912); pub const DDRAWI_BADPDEV = @as(i32, 1073741824); pub const DDRAWIVPORT_ON = @as(u32, 1); pub const DDRAWIVPORT_SOFTWARE_AUTOFLIP = @as(u32, 2); pub const DDRAWIVPORT_COLORKEYANDINTERP = @as(u32, 4); pub const DDRAWIVPORT_NOKERNELHANDLES = @as(u32, 8); pub const DDRAWIVPORT_SOFTWARE_BOB = @as(u32, 16); pub const DDRAWIVPORT_VBION = @as(u32, 32); pub const DDRAWIVPORT_VIDEOON = @as(u32, 64); pub const DDHALINFO_ISPRIMARYDISPLAY = @as(i32, 1); pub const DDHALINFO_MODEXILLEGAL = @as(i32, 2); pub const DDHALINFO_GETDRIVERINFOSET = @as(i32, 4); pub const DDHALINFO_GETDRIVERINFO2 = @as(i32, 8); pub const DDWAITVB_I_TESTVB = @as(i32, -2147483642); pub const DDRAWI_VPORTSTART = @as(u32, 1); pub const DDRAWI_VPORTSTOP = @as(u32, 2); pub const DDRAWI_VPORTUPDATE = @as(u32, 3); pub const DDRAWI_VPORTGETCOLOR = @as(u32, 1); pub const DDRAWI_VPORTSETCOLOR = @as(u32, 2); pub const DDRAWI_GETCOLOR = @as(u32, 1); pub const DDRAWI_SETCOLOR = @as(u32, 2); pub const DDMCQUERY_READ = @as(u32, 1); pub const GUID_D3DCaps = Guid.initString("7bf06991-8794-11d0-9139-080036d2ef02"); pub const GUID_D3DCallbacks = Guid.initString("7bf06990-8794-11d0-9139-080036d2ef02"); pub const GUID_DDMoreCaps = Guid.initString("880baf30-b030-11d0-8ea7-00609797ea5b"); pub const GUID_NTCallbacks = Guid.initString("6fe9ecde-df89-11d1-9db0-0060082771ba"); pub const GUID_GetHeapAlignment = Guid.initString("42e02f16-7b41-11d2-8bff-00a0c983eaf6"); pub const GUID_UpdateNonLocalHeap = Guid.initString("42e02f17-7b41-11d2-8bff-00a0c983eaf6"); pub const GUID_NTPrivateDriverCaps = Guid.initString("fad16a23-7b66-11d2-83d7-00c04f7ce58c"); pub const GUID_VPE2Callbacks = Guid.initString("52882147-2d47-469a-a0d1-03455890f6c8"); pub const DDSCAPS_COMMANDBUFFER = @as(i32, 1024); pub const DDHAL_PLEASEALLOC_USERMEM = @as(i32, 4); pub const DDHAL_CB32_MAPMEMORY = @as(i32, -2147483648); pub const DDHAL_MISC2CB32_ALPHABLT = @as(i32, 1); pub const DDHAL_CREATESURFACEEX_SWAPHANDLES = @as(i32, 1); pub const DDHAL_NTCB32_FREEDRIVERMEMORY = @as(i32, 1); pub const DDHAL_NTCB32_SETEXCLUSIVEMODE = @as(i32, 2); pub const DDHAL_NTCB32_FLIPTOGDISURFACE = @as(i32, 4); pub const DDHAL_VPORT32_GETAUTOFLIPSURF = @as(i32, 64); pub const DDHAL_D3DBUFCB32_CANCREATED3DBUF = @as(i32, 1); pub const DDHAL_D3DBUFCB32_CREATED3DBUF = @as(i32, 2); pub const DDHAL_D3DBUFCB32_DESTROYD3DBUF = @as(i32, 4); pub const DDHAL_D3DBUFCB32_LOCKD3DBUF = @as(i32, 8); pub const DDHAL_D3DBUFCB32_UNLOCKD3DBUF = @as(i32, 16); pub const DDHAL_PRIVATECAP_ATOMICSURFACECREATION = @as(i32, 1); pub const DDHAL_PRIVATECAP_NOTIFYPRIMARYCREATION = @as(i32, 2); pub const DDHAL_PRIVATECAP_RESERVED1 = @as(i32, 4); pub const DDBLT_AFLAGS = @as(i32, -2147483648); pub const DDABLT_SRCOVERDEST = @as(i32, 1); pub const DDKERNELCAPS_SKIPFIELDS = @as(i32, 1); pub const DDKERNELCAPS_AUTOFLIP = @as(i32, 2); pub const DDKERNELCAPS_SETSTATE = @as(i32, 4); pub const DDKERNELCAPS_LOCK = @as(i32, 8); pub const DDKERNELCAPS_FLIPVIDEOPORT = @as(i32, 16); pub const DDKERNELCAPS_FLIPOVERLAY = @as(i32, 32); pub const DDKERNELCAPS_CAPTURE_SYSMEM = @as(i32, 64); pub const DDKERNELCAPS_CAPTURE_NONLOCALVIDMEM = @as(i32, 128); pub const DDKERNELCAPS_FIELDPOLARITY = @as(i32, 256); pub const DDKERNELCAPS_CAPTURE_INVERTED = @as(i32, 512); pub const DDIRQ_DISPLAY_VSYNC = @as(i32, 1); pub const DDIRQ_RESERVED1 = @as(i32, 2); pub const DDIRQ_VPORT0_VSYNC = @as(i32, 4); pub const DDIRQ_VPORT0_LINE = @as(i32, 8); pub const DDIRQ_VPORT1_VSYNC = @as(i32, 16); pub const DDIRQ_VPORT1_LINE = @as(i32, 32); pub const DDIRQ_VPORT2_VSYNC = @as(i32, 64); pub const DDIRQ_VPORT2_LINE = @as(i32, 128); pub const DDIRQ_VPORT3_VSYNC = @as(i32, 256); pub const DDIRQ_VPORT3_LINE = @as(i32, 512); pub const DDIRQ_VPORT4_VSYNC = @as(i32, 1024); pub const DDIRQ_VPORT4_LINE = @as(i32, 2048); pub const DDIRQ_VPORT5_VSYNC = @as(i32, 4096); pub const DDIRQ_VPORT5_LINE = @as(i32, 8192); pub const DDIRQ_VPORT6_VSYNC = @as(i32, 16384); pub const DDIRQ_VPORT6_LINE = @as(i32, 32768); pub const DDIRQ_VPORT7_VSYNC = @as(i32, 65536); pub const DDIRQ_VPORT7_LINE = @as(i32, 131072); pub const DDIRQ_VPORT8_VSYNC = @as(i32, 262144); pub const DDIRQ_VPORT8_LINE = @as(i32, 524288); pub const DDIRQ_VPORT9_VSYNC = @as(i32, 65536); pub const DDIRQ_VPORT9_LINE = @as(i32, 131072); pub const SURFACEALIGN_DISCARDABLE = @as(i32, 1); pub const VMEMHEAP_LINEAR = @as(i32, 1); pub const VMEMHEAP_RECTANGULAR = @as(i32, 2); pub const VMEMHEAP_ALIGNMENT = @as(i32, 4); pub const DDVPTYPE_E_HREFH_VREFH = Guid.initString("54f39980-da60-11cf-9b06-00a0c903a3b8"); pub const DDVPTYPE_E_HREFH_VREFL = Guid.initString("92783220-da60-11cf-9b06-00a0c903a3b8"); pub const DDVPTYPE_E_HREFL_VREFH = Guid.initString("a07a02e0-da60-11cf-9b06-00a0c903a3b8"); pub const DDVPTYPE_E_HREFL_VREFL = Guid.initString("e09c77e0-da60-11cf-9b06-00a0c903a3b8"); pub const DDVPTYPE_CCIR656 = Guid.initString("fca326a0-da60-11cf-9b06-00a0c903a3b8"); pub const DDVPTYPE_BROOKTREE = Guid.initString("1352a560-da61-11cf-9b06-00a0c903a3b8"); pub const DDVPTYPE_PHILIPS = Guid.initString("332cf160-da61-11cf-9b06-00a0c903a3b8"); pub const DDVPD_WIDTH = @as(i32, 1); pub const DDVPD_HEIGHT = @as(i32, 2); pub const DDVPD_ID = @as(i32, 4); pub const DDVPD_CAPS = @as(i32, 8); pub const DDVPD_FX = @as(i32, 16); pub const DDVPD_AUTOFLIP = @as(i32, 32); pub const DDVPD_ALIGN = @as(i32, 64); pub const DDVPD_PREFERREDAUTOFLIP = @as(i32, 128); pub const DDVPD_FILTERQUALITY = @as(i32, 256); pub const DDVPCONNECT_DOUBLECLOCK = @as(i32, 1); pub const DDVPCONNECT_VACT = @as(i32, 2); pub const DDVPCONNECT_INVERTPOLARITY = @as(i32, 4); pub const DDVPCONNECT_DISCARDSVREFDATA = @as(i32, 8); pub const DDVPCONNECT_HALFLINE = @as(i32, 16); pub const DDVPCONNECT_INTERLACED = @as(i32, 32); pub const DDVPCONNECT_SHAREEVEN = @as(i32, 64); pub const DDVPCONNECT_SHAREODD = @as(i32, 128); pub const DDVPCAPS_AUTOFLIP = @as(i32, 1); pub const DDVPCAPS_INTERLACED = @as(i32, 2); pub const DDVPCAPS_NONINTERLACED = @as(i32, 4); pub const DDVPCAPS_READBACKFIELD = @as(i32, 8); pub const DDVPCAPS_READBACKLINE = @as(i32, 16); pub const DDVPCAPS_SHAREABLE = @as(i32, 32); pub const DDVPCAPS_SKIPEVENFIELDS = @as(i32, 64); pub const DDVPCAPS_SKIPODDFIELDS = @as(i32, 128); pub const DDVPCAPS_SYNCMASTER = @as(i32, 256); pub const DDVPCAPS_VBISURFACE = @as(i32, 512); pub const DDVPCAPS_COLORCONTROL = @as(i32, 1024); pub const DDVPCAPS_OVERSAMPLEDVBI = @as(i32, 2048); pub const DDVPCAPS_SYSTEMMEMORY = @as(i32, 4096); pub const DDVPCAPS_VBIANDVIDEOINDEPENDENT = @as(i32, 8192); pub const DDVPCAPS_HARDWAREDEINTERLACE = @as(i32, 16384); pub const DDVPFX_CROPTOPDATA = @as(i32, 1); pub const DDVPFX_CROPX = @as(i32, 2); pub const DDVPFX_CROPY = @as(i32, 4); pub const DDVPFX_INTERLEAVE = @as(i32, 8); pub const DDVPFX_MIRRORLEFTRIGHT = @as(i32, 16); pub const DDVPFX_MIRRORUPDOWN = @as(i32, 32); pub const DDVPFX_PRESHRINKX = @as(i32, 64); pub const DDVPFX_PRESHRINKY = @as(i32, 128); pub const DDVPFX_PRESHRINKXB = @as(i32, 256); pub const DDVPFX_PRESHRINKYB = @as(i32, 512); pub const DDVPFX_PRESHRINKXS = @as(i32, 1024); pub const DDVPFX_PRESHRINKYS = @as(i32, 2048); pub const DDVPFX_PRESTRETCHX = @as(i32, 4096); pub const DDVPFX_PRESTRETCHY = @as(i32, 8192); pub const DDVPFX_PRESTRETCHXN = @as(i32, 16384); pub const DDVPFX_PRESTRETCHYN = @as(i32, 32768); pub const DDVPFX_VBICONVERT = @as(i32, 65536); pub const DDVPFX_VBINOSCALE = @as(i32, 131072); pub const DDVPFX_IGNOREVBIXCROP = @as(i32, 262144); pub const DDVPFX_VBINOINTERLEAVE = @as(i32, 524288); pub const DDVP_AUTOFLIP = @as(i32, 1); pub const DDVP_CONVERT = @as(i32, 2); pub const DDVP_CROP = @as(i32, 4); pub const DDVP_INTERLEAVE = @as(i32, 8); pub const DDVP_MIRRORLEFTRIGHT = @as(i32, 16); pub const DDVP_MIRRORUPDOWN = @as(i32, 32); pub const DDVP_PRESCALE = @as(i32, 64); pub const DDVP_SKIPEVENFIELDS = @as(i32, 128); pub const DDVP_SKIPODDFIELDS = @as(i32, 256); pub const DDVP_SYNCMASTER = @as(i32, 512); pub const DDVP_VBICONVERT = @as(i32, 1024); pub const DDVP_VBINOSCALE = @as(i32, 2048); pub const DDVP_OVERRIDEBOBWEAVE = @as(i32, 4096); pub const DDVP_IGNOREVBIXCROP = @as(i32, 8192); pub const DDVP_VBINOINTERLEAVE = @as(i32, 16384); pub const DDVP_HARDWAREDEINTERLACE = @as(i32, 32768); pub const DDVPFORMAT_VIDEO = @as(i32, 1); pub const DDVPFORMAT_VBI = @as(i32, 2); pub const DDVPTARGET_VIDEO = @as(i32, 1); pub const DDVPTARGET_VBI = @as(i32, 2); pub const DDVPWAIT_BEGIN = @as(i32, 1); pub const DDVPWAIT_END = @as(i32, 2); pub const DDVPWAIT_LINE = @as(i32, 3); pub const DDVPFLIP_VIDEO = @as(i32, 1); pub const DDVPFLIP_VBI = @as(i32, 2); pub const DDVPSQ_NOSIGNAL = @as(i32, 1); pub const DDVPSQ_SIGNALOK = @as(i32, 2); pub const DDVPB_VIDEOPORT = @as(i32, 1); pub const DDVPB_OVERLAY = @as(i32, 2); pub const DDVPB_TYPE = @as(i32, 4); pub const DDVPBCAPS_SOURCE = @as(i32, 1); pub const DDVPBCAPS_DESTINATION = @as(i32, 2); pub const DDVPCREATE_VBIONLY = @as(i32, 1); pub const DDVPCREATE_VIDEOONLY = @as(i32, 2); pub const DDVPSTATUS_VBIONLY = @as(i32, 1); pub const DDVPSTATUS_VIDEOONLY = @as(i32, 2); pub const GUID_DxApi = Guid.initString("8a79bef0-b915-11d0-9144-080036d2ef02"); pub const MDL_MAPPED_TO_SYSTEM_VA = @as(u32, 1); pub const MDL_PAGES_LOCKED = @as(u32, 2); pub const MDL_SOURCE_IS_NONPAGED_POOL = @as(u32, 4); pub const MDL_ALLOCATED_FIXED_SIZE = @as(u32, 8); pub const MDL_PARTIAL = @as(u32, 16); pub const MDL_PARTIAL_HAS_BEEN_MAPPED = @as(u32, 32); pub const MDL_IO_PAGE_READ = @as(u32, 64); pub const MDL_WRITE_OPERATION = @as(u32, 128); pub const MDL_PARENT_MAPPED_SYSTEM_VA = @as(u32, 256); pub const MDL_LOCK_HELD = @as(u32, 512); pub const MDL_SCATTER_GATHER_VA = @as(u32, 1024); pub const MDL_IO_SPACE = @as(u32, 2048); pub const MDL_NETWORK_HEADER = @as(u32, 4096); pub const MDL_MAPPING_CAN_FAIL = @as(u32, 8192); pub const MDL_ALLOCATED_MUST_SUCCEED = @as(u32, 16384); pub const MDL_64_BIT_VA = @as(u32, 32768); pub const DX_OK = @as(u32, 0); pub const DXERR_UNSUPPORTED = @as(u32, 2147500033); pub const DXERR_GENERIC = @as(u32, 2147500037); pub const DXERR_OUTOFCAPS = @as(u32, 2289434984); pub const DDIRQ_BUSMASTER = @as(i32, 2); pub const IRQINFO_HANDLED = @as(u32, 1); pub const IRQINFO_NOTHANDLED = @as(u32, 2); pub const DDSKIP_SKIPNEXT = @as(u32, 1); pub const DDSKIP_ENABLENEXT = @as(u32, 2); pub const DDTRANSFER_SYSTEMMEMORY = @as(u32, 1); pub const DDTRANSFER_NONLOCALVIDMEM = @as(u32, 2); pub const DDTRANSFER_INVERT = @as(u32, 4); pub const DDTRANSFER_CANCEL = @as(u32, 128); pub const DDTRANSFER_HALFLINES = @as(u32, 256); pub const DXAPI_HALVERSION = @as(u32, 1); //-------------------------------------------------------------------------------- // Section: Types (466) //-------------------------------------------------------------------------------- pub const _DDFXROP = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const LPDDENUMCALLBACKA = fn( param0: ?*Guid, param1: ?PSTR, param2: ?PSTR, param3: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const LPDDENUMCALLBACKW = fn( param0: ?*Guid, param1: ?PWSTR, param2: ?PWSTR, param3: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const LPDDENUMCALLBACKEXA = fn( param0: ?*Guid, param1: ?PSTR, param2: ?PSTR, param3: ?*anyopaque, param4: ?HMONITOR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const LPDDENUMCALLBACKEXW = fn( param0: ?*Guid, param1: ?PWSTR, param2: ?PWSTR, param3: ?*anyopaque, param4: ?HMONITOR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const LPDIRECTDRAWENUMERATEEXA = fn( lpCallback: ?LPDDENUMCALLBACKEXA, lpContext: ?*anyopaque, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const LPDIRECTDRAWENUMERATEEXW = fn( lpCallback: ?LPDDENUMCALLBACKEXW, lpContext: ?*anyopaque, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const LPDDENUMMODESCALLBACK = fn( param0: ?*DDSURFACEDESC, param1: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const LPDDENUMMODESCALLBACK2 = fn( param0: ?*DDSURFACEDESC2, param1: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const LPDDENUMSURFACESCALLBACK = fn( param0: ?*IDirectDrawSurface, param1: ?*DDSURFACEDESC, param2: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const LPDDENUMSURFACESCALLBACK2 = fn( param0: ?*IDirectDrawSurface4, param1: ?*DDSURFACEDESC2, param2: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const LPDDENUMSURFACESCALLBACK7 = fn( param0: ?*IDirectDrawSurface7, param1: ?*DDSURFACEDESC2, param2: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const DDARGB = extern struct { blue: u8, green: u8, red: u8, alpha: u8, }; pub const DDRGBA = extern struct { red: u8, green: u8, blue: u8, alpha: u8, }; pub const DDCOLORKEY = extern struct { dwColorSpaceLowValue: u32, dwColorSpaceHighValue: u32, }; pub const DDBLTFX = extern struct { dwSize: u32, dwDDFX: u32, dwROP: u32, dwDDROP: u32, dwRotationAngle: u32, dwZBufferOpCode: u32, dwZBufferLow: u32, dwZBufferHigh: u32, dwZBufferBaseDest: u32, dwZDestConstBitDepth: u32, Anonymous1: extern union { dwZDestConst: u32, lpDDSZBufferDest: ?*IDirectDrawSurface, }, dwZSrcConstBitDepth: u32, Anonymous2: extern union { dwZSrcConst: u32, lpDDSZBufferSrc: ?*IDirectDrawSurface, }, dwAlphaEdgeBlendBitDepth: u32, dwAlphaEdgeBlend: u32, dwReserved: u32, dwAlphaDestConstBitDepth: u32, Anonymous3: extern union { dwAlphaDestConst: u32, lpDDSAlphaDest: ?*IDirectDrawSurface, }, dwAlphaSrcConstBitDepth: u32, Anonymous4: extern union { dwAlphaSrcConst: u32, lpDDSAlphaSrc: ?*IDirectDrawSurface, }, Anonymous5: extern union { dwFillColor: u32, dwFillDepth: u32, dwFillPixel: u32, lpDDSPattern: ?*IDirectDrawSurface, }, ddckDestColorkey: DDCOLORKEY, ddckSrcColorkey: DDCOLORKEY, }; pub const DDSCAPS = extern struct { dwCaps: u32, }; pub const DDOSCAPS = extern struct { dwCaps: u32, }; pub const DDSCAPSEX = extern struct { dwCaps2: u32, dwCaps3: u32, Anonymous: extern union { dwCaps4: u32, dwVolumeDepth: u32, }, }; pub const DDSCAPS2 = extern struct { dwCaps: u32, dwCaps2: u32, dwCaps3: u32, Anonymous: extern union { dwCaps4: u32, dwVolumeDepth: u32, }, }; pub const DDCAPS_DX1 = extern struct { dwSize: u32, dwCaps: u32, dwCaps2: u32, dwCKeyCaps: u32, dwFXCaps: u32, dwFXAlphaCaps: u32, dwPalCaps: u32, dwSVCaps: u32, dwAlphaBltConstBitDepths: u32, dwAlphaBltPixelBitDepths: u32, dwAlphaBltSurfaceBitDepths: u32, dwAlphaOverlayConstBitDepths: u32, dwAlphaOverlayPixelBitDepths: u32, dwAlphaOverlaySurfaceBitDepths: u32, dwZBufferBitDepths: u32, dwVidMemTotal: u32, dwVidMemFree: u32, dwMaxVisibleOverlays: u32, dwCurrVisibleOverlays: u32, dwNumFourCCCodes: u32, dwAlignBoundarySrc: u32, dwAlignSizeSrc: u32, dwAlignBoundaryDest: u32, dwAlignSizeDest: u32, dwAlignStrideAlign: u32, dwRops: [8]u32, ddsCaps: DDSCAPS, dwMinOverlayStretch: u32, dwMaxOverlayStretch: u32, dwMinLiveVideoStretch: u32, dwMaxLiveVideoStretch: u32, dwMinHwCodecStretch: u32, dwMaxHwCodecStretch: u32, dwReserved1: u32, dwReserved2: u32, dwReserved3: u32, }; pub const DDCAPS_DX3 = extern struct { dwSize: u32, dwCaps: u32, dwCaps2: u32, dwCKeyCaps: u32, dwFXCaps: u32, dwFXAlphaCaps: u32, dwPalCaps: u32, dwSVCaps: u32, dwAlphaBltConstBitDepths: u32, dwAlphaBltPixelBitDepths: u32, dwAlphaBltSurfaceBitDepths: u32, dwAlphaOverlayConstBitDepths: u32, dwAlphaOverlayPixelBitDepths: u32, dwAlphaOverlaySurfaceBitDepths: u32, dwZBufferBitDepths: u32, dwVidMemTotal: u32, dwVidMemFree: u32, dwMaxVisibleOverlays: u32, dwCurrVisibleOverlays: u32, dwNumFourCCCodes: u32, dwAlignBoundarySrc: u32, dwAlignSizeSrc: u32, dwAlignBoundaryDest: u32, dwAlignSizeDest: u32, dwAlignStrideAlign: u32, dwRops: [8]u32, ddsCaps: DDSCAPS, dwMinOverlayStretch: u32, dwMaxOverlayStretch: u32, dwMinLiveVideoStretch: u32, dwMaxLiveVideoStretch: u32, dwMinHwCodecStretch: u32, dwMaxHwCodecStretch: u32, dwReserved1: u32, dwReserved2: u32, dwReserved3: u32, dwSVBCaps: u32, dwSVBCKeyCaps: u32, dwSVBFXCaps: u32, dwSVBRops: [8]u32, dwVSBCaps: u32, dwVSBCKeyCaps: u32, dwVSBFXCaps: u32, dwVSBRops: [8]u32, dwSSBCaps: u32, dwSSBCKeyCaps: u32, dwSSBFXCaps: u32, dwSSBRops: [8]u32, dwReserved4: u32, dwReserved5: u32, dwReserved6: u32, }; pub const DDCAPS_DX5 = extern struct { dwSize: u32, dwCaps: u32, dwCaps2: u32, dwCKeyCaps: u32, dwFXCaps: u32, dwFXAlphaCaps: u32, dwPalCaps: u32, dwSVCaps: u32, dwAlphaBltConstBitDepths: u32, dwAlphaBltPixelBitDepths: u32, dwAlphaBltSurfaceBitDepths: u32, dwAlphaOverlayConstBitDepths: u32, dwAlphaOverlayPixelBitDepths: u32, dwAlphaOverlaySurfaceBitDepths: u32, dwZBufferBitDepths: u32, dwVidMemTotal: u32, dwVidMemFree: u32, dwMaxVisibleOverlays: u32, dwCurrVisibleOverlays: u32, dwNumFourCCCodes: u32, dwAlignBoundarySrc: u32, dwAlignSizeSrc: u32, dwAlignBoundaryDest: u32, dwAlignSizeDest: u32, dwAlignStrideAlign: u32, dwRops: [8]u32, ddsCaps: DDSCAPS, dwMinOverlayStretch: u32, dwMaxOverlayStretch: u32, dwMinLiveVideoStretch: u32, dwMaxLiveVideoStretch: u32, dwMinHwCodecStretch: u32, dwMaxHwCodecStretch: u32, dwReserved1: u32, dwReserved2: u32, dwReserved3: u32, dwSVBCaps: u32, dwSVBCKeyCaps: u32, dwSVBFXCaps: u32, dwSVBRops: [8]u32, dwVSBCaps: u32, dwVSBCKeyCaps: u32, dwVSBFXCaps: u32, dwVSBRops: [8]u32, dwSSBCaps: u32, dwSSBCKeyCaps: u32, dwSSBFXCaps: u32, dwSSBRops: [8]u32, dwMaxVideoPorts: u32, dwCurrVideoPorts: u32, dwSVBCaps2: u32, dwNLVBCaps: u32, dwNLVBCaps2: u32, dwNLVBCKeyCaps: u32, dwNLVBFXCaps: u32, dwNLVBRops: [8]u32, }; pub const DDCAPS_DX6 = extern struct { dwSize: u32, dwCaps: u32, dwCaps2: u32, dwCKeyCaps: u32, dwFXCaps: u32, dwFXAlphaCaps: u32, dwPalCaps: u32, dwSVCaps: u32, dwAlphaBltConstBitDepths: u32, dwAlphaBltPixelBitDepths: u32, dwAlphaBltSurfaceBitDepths: u32, dwAlphaOverlayConstBitDepths: u32, dwAlphaOverlayPixelBitDepths: u32, dwAlphaOverlaySurfaceBitDepths: u32, dwZBufferBitDepths: u32, dwVidMemTotal: u32, dwVidMemFree: u32, dwMaxVisibleOverlays: u32, dwCurrVisibleOverlays: u32, dwNumFourCCCodes: u32, dwAlignBoundarySrc: u32, dwAlignSizeSrc: u32, dwAlignBoundaryDest: u32, dwAlignSizeDest: u32, dwAlignStrideAlign: u32, dwRops: [8]u32, ddsOldCaps: DDSCAPS, dwMinOverlayStretch: u32, dwMaxOverlayStretch: u32, dwMinLiveVideoStretch: u32, dwMaxLiveVideoStretch: u32, dwMinHwCodecStretch: u32, dwMaxHwCodecStretch: u32, dwReserved1: u32, dwReserved2: u32, dwReserved3: u32, dwSVBCaps: u32, dwSVBCKeyCaps: u32, dwSVBFXCaps: u32, dwSVBRops: [8]u32, dwVSBCaps: u32, dwVSBCKeyCaps: u32, dwVSBFXCaps: u32, dwVSBRops: [8]u32, dwSSBCaps: u32, dwSSBCKeyCaps: u32, dwSSBFXCaps: u32, dwSSBRops: [8]u32, dwMaxVideoPorts: u32, dwCurrVideoPorts: u32, dwSVBCaps2: u32, dwNLVBCaps: u32, dwNLVBCaps2: u32, dwNLVBCKeyCaps: u32, dwNLVBFXCaps: u32, dwNLVBRops: [8]u32, ddsCaps: DDSCAPS2, }; pub const DDCAPS_DX7 = extern struct { dwSize: u32, dwCaps: u32, dwCaps2: u32, dwCKeyCaps: u32, dwFXCaps: u32, dwFXAlphaCaps: u32, dwPalCaps: u32, dwSVCaps: u32, dwAlphaBltConstBitDepths: u32, dwAlphaBltPixelBitDepths: u32, dwAlphaBltSurfaceBitDepths: u32, dwAlphaOverlayConstBitDepths: u32, dwAlphaOverlayPixelBitDepths: u32, dwAlphaOverlaySurfaceBitDepths: u32, dwZBufferBitDepths: u32, dwVidMemTotal: u32, dwVidMemFree: u32, dwMaxVisibleOverlays: u32, dwCurrVisibleOverlays: u32, dwNumFourCCCodes: u32, dwAlignBoundarySrc: u32, dwAlignSizeSrc: u32, dwAlignBoundaryDest: u32, dwAlignSizeDest: u32, dwAlignStrideAlign: u32, dwRops: [8]u32, ddsOldCaps: DDSCAPS, dwMinOverlayStretch: u32, dwMaxOverlayStretch: u32, dwMinLiveVideoStretch: u32, dwMaxLiveVideoStretch: u32, dwMinHwCodecStretch: u32, dwMaxHwCodecStretch: u32, dwReserved1: u32, dwReserved2: u32, dwReserved3: u32, dwSVBCaps: u32, dwSVBCKeyCaps: u32, dwSVBFXCaps: u32, dwSVBRops: [8]u32, dwVSBCaps: u32, dwVSBCKeyCaps: u32, dwVSBFXCaps: u32, dwVSBRops: [8]u32, dwSSBCaps: u32, dwSSBCKeyCaps: u32, dwSSBFXCaps: u32, dwSSBRops: [8]u32, dwMaxVideoPorts: u32, dwCurrVideoPorts: u32, dwSVBCaps2: u32, dwNLVBCaps: u32, dwNLVBCaps2: u32, dwNLVBCKeyCaps: u32, dwNLVBFXCaps: u32, dwNLVBRops: [8]u32, ddsCaps: DDSCAPS2, }; pub const DDPIXELFORMAT = extern struct { dwSize: u32, dwFlags: u32, dwFourCC: u32, Anonymous1: extern union { dwRGBBitCount: u32, dwYUVBitCount: u32, dwZBufferBitDepth: u32, dwAlphaBitDepth: u32, dwLuminanceBitCount: u32, dwBumpBitCount: u32, dwPrivateFormatBitCount: u32, }, Anonymous2: extern union { dwRBitMask: u32, dwYBitMask: u32, dwStencilBitDepth: u32, dwLuminanceBitMask: u32, dwBumpDuBitMask: u32, dwOperations: u32, }, Anonymous3: extern union { dwGBitMask: u32, dwUBitMask: u32, dwZBitMask: u32, dwBumpDvBitMask: u32, MultiSampleCaps: extern struct { wFlipMSTypes: u16, wBltMSTypes: u16, }, }, Anonymous4: extern union { dwBBitMask: u32, dwVBitMask: u32, dwStencilBitMask: u32, dwBumpLuminanceBitMask: u32, }, Anonymous5: extern union { dwRGBAlphaBitMask: u32, dwYUVAlphaBitMask: u32, dwLuminanceAlphaBitMask: u32, dwRGBZBitMask: u32, dwYUVZBitMask: u32, }, }; pub const DDOVERLAYFX = extern struct { dwSize: u32, dwAlphaEdgeBlendBitDepth: u32, dwAlphaEdgeBlend: u32, dwReserved: u32, dwAlphaDestConstBitDepth: u32, Anonymous1: extern union { dwAlphaDestConst: u32, lpDDSAlphaDest: ?*IDirectDrawSurface, }, dwAlphaSrcConstBitDepth: u32, Anonymous2: extern union { dwAlphaSrcConst: u32, lpDDSAlphaSrc: ?*IDirectDrawSurface, }, dckDestColorkey: DDCOLORKEY, dckSrcColorkey: DDCOLORKEY, dwDDFX: u32, dwFlags: u32, }; pub const DDBLTBATCH = extern struct { lprDest: ?*RECT, lpDDSSrc: ?*IDirectDrawSurface, lprSrc: ?*RECT, dwFlags: u32, lpDDBltFx: ?*DDBLTFX, }; pub const DDGAMMARAMP = extern struct { red: [256]u16, green: [256]u16, blue: [256]u16, }; pub const DDDEVICEIDENTIFIER = extern struct { szDriver: [512]CHAR, szDescription: [512]CHAR, liDriverVersion: LARGE_INTEGER, dwVendorId: u32, dwDeviceId: u32, dwSubSysId: u32, dwRevision: u32, guidDeviceIdentifier: Guid, }; pub const DDDEVICEIDENTIFIER2 = extern struct { szDriver: [512]CHAR, szDescription: [512]CHAR, liDriverVersion: LARGE_INTEGER, dwVendorId: u32, dwDeviceId: u32, dwSubSysId: u32, dwRevision: u32, guidDeviceIdentifier: Guid, dwWHQLLevel: u32, }; pub const LPCLIPPERCALLBACK = fn( lpDDClipper: ?*IDirectDrawClipper, hWnd: ?HWND, code: u32, lpContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; const IID_IDirectDraw_Value = Guid.initString("6c14db80-a733-11ce-a521-0020af0be560"); pub const IID_IDirectDraw = &IID_IDirectDraw_Value; pub const IDirectDraw = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Compact: fn( self: *const IDirectDraw, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateClipper: fn( self: *const IDirectDraw, param0: u32, param1: ?*?*IDirectDrawClipper, param2: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePalette: fn( self: *const IDirectDraw, param0: u32, param1: ?*PALETTEENTRY, param2: ?*?*IDirectDrawPalette, param3: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateSurface: fn( self: *const IDirectDraw, param0: ?*DDSURFACEDESC, param1: ?*?*IDirectDrawSurface, param2: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DuplicateSurface: fn( self: *const IDirectDraw, param0: ?*IDirectDrawSurface, param1: ?*?*IDirectDrawSurface, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumDisplayModes: fn( self: *const IDirectDraw, param0: u32, param1: ?*DDSURFACEDESC, param2: ?*anyopaque, param3: ?LPDDENUMMODESCALLBACK, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumSurfaces: fn( self: *const IDirectDraw, param0: u32, param1: ?*DDSURFACEDESC, param2: ?*anyopaque, param3: ?LPDDENUMSURFACESCALLBACK, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FlipToGDISurface: fn( self: *const IDirectDraw, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCaps: fn( self: *const IDirectDraw, param0: ?*DDCAPS_DX7, param1: ?*DDCAPS_DX7, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDisplayMode: fn( self: *const IDirectDraw, param0: ?*DDSURFACEDESC, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFourCCCodes: fn( self: *const IDirectDraw, param0: ?*u32, param1: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGDISurface: fn( self: *const IDirectDraw, param0: ?*?*IDirectDrawSurface, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMonitorFrequency: fn( self: *const IDirectDraw, param0: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetScanLine: fn( self: *const IDirectDraw, param0: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetVerticalBlankStatus: fn( self: *const IDirectDraw, param0: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Initialize: fn( self: *const IDirectDraw, param0: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RestoreDisplayMode: fn( self: *const IDirectDraw, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetCooperativeLevel: fn( self: *const IDirectDraw, param0: ?HWND, param1: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDisplayMode: fn( self: *const IDirectDraw, param0: u32, param1: u32, param2: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WaitForVerticalBlank: fn( self: *const IDirectDraw, param0: u32, param1: ?HANDLE, ) 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 IDirectDraw_Compact(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw.VTable, self.vtable).Compact(@ptrCast(*const IDirectDraw, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw_CreateClipper(self: *const T, param0: u32, param1: ?*?*IDirectDrawClipper, param2: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw.VTable, self.vtable).CreateClipper(@ptrCast(*const IDirectDraw, self), param0, param1, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw_CreatePalette(self: *const T, param0: u32, param1: ?*PALETTEENTRY, param2: ?*?*IDirectDrawPalette, param3: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw.VTable, self.vtable).CreatePalette(@ptrCast(*const IDirectDraw, self), param0, param1, param2, param3); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw_CreateSurface(self: *const T, param0: ?*DDSURFACEDESC, param1: ?*?*IDirectDrawSurface, param2: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw.VTable, self.vtable).CreateSurface(@ptrCast(*const IDirectDraw, self), param0, param1, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw_DuplicateSurface(self: *const T, param0: ?*IDirectDrawSurface, param1: ?*?*IDirectDrawSurface) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw.VTable, self.vtable).DuplicateSurface(@ptrCast(*const IDirectDraw, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw_EnumDisplayModes(self: *const T, param0: u32, param1: ?*DDSURFACEDESC, param2: ?*anyopaque, param3: ?LPDDENUMMODESCALLBACK) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw.VTable, self.vtable).EnumDisplayModes(@ptrCast(*const IDirectDraw, self), param0, param1, param2, param3); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw_EnumSurfaces(self: *const T, param0: u32, param1: ?*DDSURFACEDESC, param2: ?*anyopaque, param3: ?LPDDENUMSURFACESCALLBACK) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw.VTable, self.vtable).EnumSurfaces(@ptrCast(*const IDirectDraw, self), param0, param1, param2, param3); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw_FlipToGDISurface(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw.VTable, self.vtable).FlipToGDISurface(@ptrCast(*const IDirectDraw, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw_GetCaps(self: *const T, param0: ?*DDCAPS_DX7, param1: ?*DDCAPS_DX7) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw.VTable, self.vtable).GetCaps(@ptrCast(*const IDirectDraw, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw_GetDisplayMode(self: *const T, param0: ?*DDSURFACEDESC) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw.VTable, self.vtable).GetDisplayMode(@ptrCast(*const IDirectDraw, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw_GetFourCCCodes(self: *const T, param0: ?*u32, param1: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw.VTable, self.vtable).GetFourCCCodes(@ptrCast(*const IDirectDraw, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw_GetGDISurface(self: *const T, param0: ?*?*IDirectDrawSurface) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw.VTable, self.vtable).GetGDISurface(@ptrCast(*const IDirectDraw, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw_GetMonitorFrequency(self: *const T, param0: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw.VTable, self.vtable).GetMonitorFrequency(@ptrCast(*const IDirectDraw, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw_GetScanLine(self: *const T, param0: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw.VTable, self.vtable).GetScanLine(@ptrCast(*const IDirectDraw, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw_GetVerticalBlankStatus(self: *const T, param0: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw.VTable, self.vtable).GetVerticalBlankStatus(@ptrCast(*const IDirectDraw, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw_Initialize(self: *const T, param0: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw.VTable, self.vtable).Initialize(@ptrCast(*const IDirectDraw, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw_RestoreDisplayMode(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw.VTable, self.vtable).RestoreDisplayMode(@ptrCast(*const IDirectDraw, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw_SetCooperativeLevel(self: *const T, param0: ?HWND, param1: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw.VTable, self.vtable).SetCooperativeLevel(@ptrCast(*const IDirectDraw, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw_SetDisplayMode(self: *const T, param0: u32, param1: u32, param2: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw.VTable, self.vtable).SetDisplayMode(@ptrCast(*const IDirectDraw, self), param0, param1, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw_WaitForVerticalBlank(self: *const T, param0: u32, param1: ?HANDLE) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw.VTable, self.vtable).WaitForVerticalBlank(@ptrCast(*const IDirectDraw, self), param0, param1); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectDraw2_Value = Guid.initString("b3a6f3e0-2b43-11cf-a2de-00aa00b93356"); pub const IID_IDirectDraw2 = &IID_IDirectDraw2_Value; pub const IDirectDraw2 = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Compact: fn( self: *const IDirectDraw2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateClipper: fn( self: *const IDirectDraw2, param0: u32, param1: ?*?*IDirectDrawClipper, param2: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePalette: fn( self: *const IDirectDraw2, param0: u32, param1: ?*PALETTEENTRY, param2: ?*?*IDirectDrawPalette, param3: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateSurface: fn( self: *const IDirectDraw2, param0: ?*DDSURFACEDESC, param1: ?*?*IDirectDrawSurface, param2: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DuplicateSurface: fn( self: *const IDirectDraw2, param0: ?*IDirectDrawSurface, param1: ?*?*IDirectDrawSurface, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumDisplayModes: fn( self: *const IDirectDraw2, param0: u32, param1: ?*DDSURFACEDESC, param2: ?*anyopaque, param3: ?LPDDENUMMODESCALLBACK, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumSurfaces: fn( self: *const IDirectDraw2, param0: u32, param1: ?*DDSURFACEDESC, param2: ?*anyopaque, param3: ?LPDDENUMSURFACESCALLBACK, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FlipToGDISurface: fn( self: *const IDirectDraw2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCaps: fn( self: *const IDirectDraw2, param0: ?*DDCAPS_DX7, param1: ?*DDCAPS_DX7, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDisplayMode: fn( self: *const IDirectDraw2, param0: ?*DDSURFACEDESC, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFourCCCodes: fn( self: *const IDirectDraw2, param0: ?*u32, param1: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGDISurface: fn( self: *const IDirectDraw2, param0: ?*?*IDirectDrawSurface, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMonitorFrequency: fn( self: *const IDirectDraw2, param0: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetScanLine: fn( self: *const IDirectDraw2, param0: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetVerticalBlankStatus: fn( self: *const IDirectDraw2, param0: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Initialize: fn( self: *const IDirectDraw2, param0: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RestoreDisplayMode: fn( self: *const IDirectDraw2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetCooperativeLevel: fn( self: *const IDirectDraw2, param0: ?HWND, param1: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDisplayMode: fn( self: *const IDirectDraw2, param0: u32, param1: u32, param2: u32, param3: u32, param4: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WaitForVerticalBlank: fn( self: *const IDirectDraw2, param0: u32, param1: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAvailableVidMem: fn( self: *const IDirectDraw2, param0: ?*DDSCAPS, param1: ?*u32, param2: ?*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 IDirectDraw2_Compact(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw2.VTable, self.vtable).Compact(@ptrCast(*const IDirectDraw2, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw2_CreateClipper(self: *const T, param0: u32, param1: ?*?*IDirectDrawClipper, param2: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw2.VTable, self.vtable).CreateClipper(@ptrCast(*const IDirectDraw2, self), param0, param1, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw2_CreatePalette(self: *const T, param0: u32, param1: ?*PALETTEENTRY, param2: ?*?*IDirectDrawPalette, param3: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw2.VTable, self.vtable).CreatePalette(@ptrCast(*const IDirectDraw2, self), param0, param1, param2, param3); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw2_CreateSurface(self: *const T, param0: ?*DDSURFACEDESC, param1: ?*?*IDirectDrawSurface, param2: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw2.VTable, self.vtable).CreateSurface(@ptrCast(*const IDirectDraw2, self), param0, param1, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw2_DuplicateSurface(self: *const T, param0: ?*IDirectDrawSurface, param1: ?*?*IDirectDrawSurface) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw2.VTable, self.vtable).DuplicateSurface(@ptrCast(*const IDirectDraw2, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw2_EnumDisplayModes(self: *const T, param0: u32, param1: ?*DDSURFACEDESC, param2: ?*anyopaque, param3: ?LPDDENUMMODESCALLBACK) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw2.VTable, self.vtable).EnumDisplayModes(@ptrCast(*const IDirectDraw2, self), param0, param1, param2, param3); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw2_EnumSurfaces(self: *const T, param0: u32, param1: ?*DDSURFACEDESC, param2: ?*anyopaque, param3: ?LPDDENUMSURFACESCALLBACK) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw2.VTable, self.vtable).EnumSurfaces(@ptrCast(*const IDirectDraw2, self), param0, param1, param2, param3); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw2_FlipToGDISurface(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw2.VTable, self.vtable).FlipToGDISurface(@ptrCast(*const IDirectDraw2, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw2_GetCaps(self: *const T, param0: ?*DDCAPS_DX7, param1: ?*DDCAPS_DX7) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw2.VTable, self.vtable).GetCaps(@ptrCast(*const IDirectDraw2, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw2_GetDisplayMode(self: *const T, param0: ?*DDSURFACEDESC) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw2.VTable, self.vtable).GetDisplayMode(@ptrCast(*const IDirectDraw2, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw2_GetFourCCCodes(self: *const T, param0: ?*u32, param1: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw2.VTable, self.vtable).GetFourCCCodes(@ptrCast(*const IDirectDraw2, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw2_GetGDISurface(self: *const T, param0: ?*?*IDirectDrawSurface) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw2.VTable, self.vtable).GetGDISurface(@ptrCast(*const IDirectDraw2, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw2_GetMonitorFrequency(self: *const T, param0: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw2.VTable, self.vtable).GetMonitorFrequency(@ptrCast(*const IDirectDraw2, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw2_GetScanLine(self: *const T, param0: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw2.VTable, self.vtable).GetScanLine(@ptrCast(*const IDirectDraw2, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw2_GetVerticalBlankStatus(self: *const T, param0: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw2.VTable, self.vtable).GetVerticalBlankStatus(@ptrCast(*const IDirectDraw2, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw2_Initialize(self: *const T, param0: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw2.VTable, self.vtable).Initialize(@ptrCast(*const IDirectDraw2, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw2_RestoreDisplayMode(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw2.VTable, self.vtable).RestoreDisplayMode(@ptrCast(*const IDirectDraw2, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw2_SetCooperativeLevel(self: *const T, param0: ?HWND, param1: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw2.VTable, self.vtable).SetCooperativeLevel(@ptrCast(*const IDirectDraw2, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw2_SetDisplayMode(self: *const T, param0: u32, param1: u32, param2: u32, param3: u32, param4: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw2.VTable, self.vtable).SetDisplayMode(@ptrCast(*const IDirectDraw2, self), param0, param1, param2, param3, param4); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw2_WaitForVerticalBlank(self: *const T, param0: u32, param1: ?HANDLE) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw2.VTable, self.vtable).WaitForVerticalBlank(@ptrCast(*const IDirectDraw2, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw2_GetAvailableVidMem(self: *const T, param0: ?*DDSCAPS, param1: ?*u32, param2: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw2.VTable, self.vtable).GetAvailableVidMem(@ptrCast(*const IDirectDraw2, self), param0, param1, param2); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectDraw4_Value = Guid.initString("9c59509a-39bd-11d1-8c4a-00c04fd930c5"); pub const IID_IDirectDraw4 = &IID_IDirectDraw4_Value; pub const IDirectDraw4 = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Compact: fn( self: *const IDirectDraw4, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateClipper: fn( self: *const IDirectDraw4, param0: u32, param1: ?*?*IDirectDrawClipper, param2: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePalette: fn( self: *const IDirectDraw4, param0: u32, param1: ?*PALETTEENTRY, param2: ?*?*IDirectDrawPalette, param3: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateSurface: fn( self: *const IDirectDraw4, param0: ?*DDSURFACEDESC2, param1: ?*?*IDirectDrawSurface4, param2: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DuplicateSurface: fn( self: *const IDirectDraw4, param0: ?*IDirectDrawSurface4, param1: ?*?*IDirectDrawSurface4, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumDisplayModes: fn( self: *const IDirectDraw4, param0: u32, param1: ?*DDSURFACEDESC2, param2: ?*anyopaque, param3: ?LPDDENUMMODESCALLBACK2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumSurfaces: fn( self: *const IDirectDraw4, param0: u32, param1: ?*DDSURFACEDESC2, param2: ?*anyopaque, param3: ?LPDDENUMSURFACESCALLBACK2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FlipToGDISurface: fn( self: *const IDirectDraw4, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCaps: fn( self: *const IDirectDraw4, param0: ?*DDCAPS_DX7, param1: ?*DDCAPS_DX7, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDisplayMode: fn( self: *const IDirectDraw4, param0: ?*DDSURFACEDESC2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFourCCCodes: fn( self: *const IDirectDraw4, param0: ?*u32, param1: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGDISurface: fn( self: *const IDirectDraw4, param0: ?*?*IDirectDrawSurface4, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMonitorFrequency: fn( self: *const IDirectDraw4, param0: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetScanLine: fn( self: *const IDirectDraw4, param0: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetVerticalBlankStatus: fn( self: *const IDirectDraw4, param0: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Initialize: fn( self: *const IDirectDraw4, param0: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RestoreDisplayMode: fn( self: *const IDirectDraw4, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetCooperativeLevel: fn( self: *const IDirectDraw4, param0: ?HWND, param1: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDisplayMode: fn( self: *const IDirectDraw4, param0: u32, param1: u32, param2: u32, param3: u32, param4: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WaitForVerticalBlank: fn( self: *const IDirectDraw4, param0: u32, param1: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAvailableVidMem: fn( self: *const IDirectDraw4, param0: ?*DDSCAPS2, param1: ?*u32, param2: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSurfaceFromDC: fn( self: *const IDirectDraw4, param0: ?HDC, param1: ?*?*IDirectDrawSurface4, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RestoreAllSurfaces: fn( self: *const IDirectDraw4, ) callconv(@import("std").os.windows.WINAPI) HRESULT, TestCooperativeLevel: fn( self: *const IDirectDraw4, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDeviceIdentifier: fn( self: *const IDirectDraw4, param0: ?*DDDEVICEIDENTIFIER, param1: 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 IDirectDraw4_Compact(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw4.VTable, self.vtable).Compact(@ptrCast(*const IDirectDraw4, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw4_CreateClipper(self: *const T, param0: u32, param1: ?*?*IDirectDrawClipper, param2: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw4.VTable, self.vtable).CreateClipper(@ptrCast(*const IDirectDraw4, self), param0, param1, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw4_CreatePalette(self: *const T, param0: u32, param1: ?*PALETTEENTRY, param2: ?*?*IDirectDrawPalette, param3: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw4.VTable, self.vtable).CreatePalette(@ptrCast(*const IDirectDraw4, self), param0, param1, param2, param3); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw4_CreateSurface(self: *const T, param0: ?*DDSURFACEDESC2, param1: ?*?*IDirectDrawSurface4, param2: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw4.VTable, self.vtable).CreateSurface(@ptrCast(*const IDirectDraw4, self), param0, param1, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw4_DuplicateSurface(self: *const T, param0: ?*IDirectDrawSurface4, param1: ?*?*IDirectDrawSurface4) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw4.VTable, self.vtable).DuplicateSurface(@ptrCast(*const IDirectDraw4, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw4_EnumDisplayModes(self: *const T, param0: u32, param1: ?*DDSURFACEDESC2, param2: ?*anyopaque, param3: ?LPDDENUMMODESCALLBACK2) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw4.VTable, self.vtable).EnumDisplayModes(@ptrCast(*const IDirectDraw4, self), param0, param1, param2, param3); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw4_EnumSurfaces(self: *const T, param0: u32, param1: ?*DDSURFACEDESC2, param2: ?*anyopaque, param3: ?LPDDENUMSURFACESCALLBACK2) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw4.VTable, self.vtable).EnumSurfaces(@ptrCast(*const IDirectDraw4, self), param0, param1, param2, param3); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw4_FlipToGDISurface(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw4.VTable, self.vtable).FlipToGDISurface(@ptrCast(*const IDirectDraw4, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw4_GetCaps(self: *const T, param0: ?*DDCAPS_DX7, param1: ?*DDCAPS_DX7) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw4.VTable, self.vtable).GetCaps(@ptrCast(*const IDirectDraw4, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw4_GetDisplayMode(self: *const T, param0: ?*DDSURFACEDESC2) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw4.VTable, self.vtable).GetDisplayMode(@ptrCast(*const IDirectDraw4, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw4_GetFourCCCodes(self: *const T, param0: ?*u32, param1: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw4.VTable, self.vtable).GetFourCCCodes(@ptrCast(*const IDirectDraw4, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw4_GetGDISurface(self: *const T, param0: ?*?*IDirectDrawSurface4) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw4.VTable, self.vtable).GetGDISurface(@ptrCast(*const IDirectDraw4, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw4_GetMonitorFrequency(self: *const T, param0: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw4.VTable, self.vtable).GetMonitorFrequency(@ptrCast(*const IDirectDraw4, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw4_GetScanLine(self: *const T, param0: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw4.VTable, self.vtable).GetScanLine(@ptrCast(*const IDirectDraw4, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw4_GetVerticalBlankStatus(self: *const T, param0: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw4.VTable, self.vtable).GetVerticalBlankStatus(@ptrCast(*const IDirectDraw4, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw4_Initialize(self: *const T, param0: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw4.VTable, self.vtable).Initialize(@ptrCast(*const IDirectDraw4, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw4_RestoreDisplayMode(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw4.VTable, self.vtable).RestoreDisplayMode(@ptrCast(*const IDirectDraw4, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw4_SetCooperativeLevel(self: *const T, param0: ?HWND, param1: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw4.VTable, self.vtable).SetCooperativeLevel(@ptrCast(*const IDirectDraw4, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw4_SetDisplayMode(self: *const T, param0: u32, param1: u32, param2: u32, param3: u32, param4: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw4.VTable, self.vtable).SetDisplayMode(@ptrCast(*const IDirectDraw4, self), param0, param1, param2, param3, param4); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw4_WaitForVerticalBlank(self: *const T, param0: u32, param1: ?HANDLE) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw4.VTable, self.vtable).WaitForVerticalBlank(@ptrCast(*const IDirectDraw4, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw4_GetAvailableVidMem(self: *const T, param0: ?*DDSCAPS2, param1: ?*u32, param2: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw4.VTable, self.vtable).GetAvailableVidMem(@ptrCast(*const IDirectDraw4, self), param0, param1, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw4_GetSurfaceFromDC(self: *const T, param0: ?HDC, param1: ?*?*IDirectDrawSurface4) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw4.VTable, self.vtable).GetSurfaceFromDC(@ptrCast(*const IDirectDraw4, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw4_RestoreAllSurfaces(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw4.VTable, self.vtable).RestoreAllSurfaces(@ptrCast(*const IDirectDraw4, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw4_TestCooperativeLevel(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw4.VTable, self.vtable).TestCooperativeLevel(@ptrCast(*const IDirectDraw4, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw4_GetDeviceIdentifier(self: *const T, param0: ?*DDDEVICEIDENTIFIER, param1: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw4.VTable, self.vtable).GetDeviceIdentifier(@ptrCast(*const IDirectDraw4, self), param0, param1); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectDraw7_Value = Guid.initString("15e65ec0-3b9c-11d2-b92f-00609797ea5b"); pub const IID_IDirectDraw7 = &IID_IDirectDraw7_Value; pub const IDirectDraw7 = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Compact: fn( self: *const IDirectDraw7, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateClipper: fn( self: *const IDirectDraw7, param0: u32, param1: ?*?*IDirectDrawClipper, param2: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePalette: fn( self: *const IDirectDraw7, param0: u32, param1: ?*PALETTEENTRY, param2: ?*?*IDirectDrawPalette, param3: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateSurface: fn( self: *const IDirectDraw7, param0: ?*DDSURFACEDESC2, param1: ?*?*IDirectDrawSurface7, param2: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DuplicateSurface: fn( self: *const IDirectDraw7, param0: ?*IDirectDrawSurface7, param1: ?*?*IDirectDrawSurface7, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumDisplayModes: fn( self: *const IDirectDraw7, param0: u32, param1: ?*DDSURFACEDESC2, param2: ?*anyopaque, param3: ?LPDDENUMMODESCALLBACK2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumSurfaces: fn( self: *const IDirectDraw7, param0: u32, param1: ?*DDSURFACEDESC2, param2: ?*anyopaque, param3: ?LPDDENUMSURFACESCALLBACK7, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FlipToGDISurface: fn( self: *const IDirectDraw7, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCaps: fn( self: *const IDirectDraw7, param0: ?*DDCAPS_DX7, param1: ?*DDCAPS_DX7, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDisplayMode: fn( self: *const IDirectDraw7, param0: ?*DDSURFACEDESC2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFourCCCodes: fn( self: *const IDirectDraw7, param0: ?*u32, param1: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGDISurface: fn( self: *const IDirectDraw7, param0: ?*?*IDirectDrawSurface7, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMonitorFrequency: fn( self: *const IDirectDraw7, param0: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetScanLine: fn( self: *const IDirectDraw7, param0: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetVerticalBlankStatus: fn( self: *const IDirectDraw7, param0: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Initialize: fn( self: *const IDirectDraw7, param0: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RestoreDisplayMode: fn( self: *const IDirectDraw7, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetCooperativeLevel: fn( self: *const IDirectDraw7, param0: ?HWND, param1: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDisplayMode: fn( self: *const IDirectDraw7, param0: u32, param1: u32, param2: u32, param3: u32, param4: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WaitForVerticalBlank: fn( self: *const IDirectDraw7, param0: u32, param1: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAvailableVidMem: fn( self: *const IDirectDraw7, param0: ?*DDSCAPS2, param1: ?*u32, param2: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSurfaceFromDC: fn( self: *const IDirectDraw7, param0: ?HDC, param1: ?*?*IDirectDrawSurface7, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RestoreAllSurfaces: fn( self: *const IDirectDraw7, ) callconv(@import("std").os.windows.WINAPI) HRESULT, TestCooperativeLevel: fn( self: *const IDirectDraw7, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDeviceIdentifier: fn( self: *const IDirectDraw7, param0: ?*DDDEVICEIDENTIFIER2, param1: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, StartModeTest: fn( self: *const IDirectDraw7, param0: ?*SIZE, param1: u32, param2: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EvaluateMode: fn( self: *const IDirectDraw7, param0: u32, param1: ?*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 IDirectDraw7_Compact(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw7.VTable, self.vtable).Compact(@ptrCast(*const IDirectDraw7, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw7_CreateClipper(self: *const T, param0: u32, param1: ?*?*IDirectDrawClipper, param2: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw7.VTable, self.vtable).CreateClipper(@ptrCast(*const IDirectDraw7, self), param0, param1, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw7_CreatePalette(self: *const T, param0: u32, param1: ?*PALETTEENTRY, param2: ?*?*IDirectDrawPalette, param3: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw7.VTable, self.vtable).CreatePalette(@ptrCast(*const IDirectDraw7, self), param0, param1, param2, param3); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw7_CreateSurface(self: *const T, param0: ?*DDSURFACEDESC2, param1: ?*?*IDirectDrawSurface7, param2: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw7.VTable, self.vtable).CreateSurface(@ptrCast(*const IDirectDraw7, self), param0, param1, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw7_DuplicateSurface(self: *const T, param0: ?*IDirectDrawSurface7, param1: ?*?*IDirectDrawSurface7) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw7.VTable, self.vtable).DuplicateSurface(@ptrCast(*const IDirectDraw7, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw7_EnumDisplayModes(self: *const T, param0: u32, param1: ?*DDSURFACEDESC2, param2: ?*anyopaque, param3: ?LPDDENUMMODESCALLBACK2) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw7.VTable, self.vtable).EnumDisplayModes(@ptrCast(*const IDirectDraw7, self), param0, param1, param2, param3); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw7_EnumSurfaces(self: *const T, param0: u32, param1: ?*DDSURFACEDESC2, param2: ?*anyopaque, param3: ?LPDDENUMSURFACESCALLBACK7) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw7.VTable, self.vtable).EnumSurfaces(@ptrCast(*const IDirectDraw7, self), param0, param1, param2, param3); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw7_FlipToGDISurface(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw7.VTable, self.vtable).FlipToGDISurface(@ptrCast(*const IDirectDraw7, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw7_GetCaps(self: *const T, param0: ?*DDCAPS_DX7, param1: ?*DDCAPS_DX7) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw7.VTable, self.vtable).GetCaps(@ptrCast(*const IDirectDraw7, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw7_GetDisplayMode(self: *const T, param0: ?*DDSURFACEDESC2) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw7.VTable, self.vtable).GetDisplayMode(@ptrCast(*const IDirectDraw7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw7_GetFourCCCodes(self: *const T, param0: ?*u32, param1: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw7.VTable, self.vtable).GetFourCCCodes(@ptrCast(*const IDirectDraw7, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw7_GetGDISurface(self: *const T, param0: ?*?*IDirectDrawSurface7) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw7.VTable, self.vtable).GetGDISurface(@ptrCast(*const IDirectDraw7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw7_GetMonitorFrequency(self: *const T, param0: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw7.VTable, self.vtable).GetMonitorFrequency(@ptrCast(*const IDirectDraw7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw7_GetScanLine(self: *const T, param0: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw7.VTable, self.vtable).GetScanLine(@ptrCast(*const IDirectDraw7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw7_GetVerticalBlankStatus(self: *const T, param0: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw7.VTable, self.vtable).GetVerticalBlankStatus(@ptrCast(*const IDirectDraw7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw7_Initialize(self: *const T, param0: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw7.VTable, self.vtable).Initialize(@ptrCast(*const IDirectDraw7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw7_RestoreDisplayMode(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw7.VTable, self.vtable).RestoreDisplayMode(@ptrCast(*const IDirectDraw7, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw7_SetCooperativeLevel(self: *const T, param0: ?HWND, param1: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw7.VTable, self.vtable).SetCooperativeLevel(@ptrCast(*const IDirectDraw7, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw7_SetDisplayMode(self: *const T, param0: u32, param1: u32, param2: u32, param3: u32, param4: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw7.VTable, self.vtable).SetDisplayMode(@ptrCast(*const IDirectDraw7, self), param0, param1, param2, param3, param4); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw7_WaitForVerticalBlank(self: *const T, param0: u32, param1: ?HANDLE) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw7.VTable, self.vtable).WaitForVerticalBlank(@ptrCast(*const IDirectDraw7, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw7_GetAvailableVidMem(self: *const T, param0: ?*DDSCAPS2, param1: ?*u32, param2: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw7.VTable, self.vtable).GetAvailableVidMem(@ptrCast(*const IDirectDraw7, self), param0, param1, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw7_GetSurfaceFromDC(self: *const T, param0: ?HDC, param1: ?*?*IDirectDrawSurface7) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw7.VTable, self.vtable).GetSurfaceFromDC(@ptrCast(*const IDirectDraw7, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw7_RestoreAllSurfaces(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw7.VTable, self.vtable).RestoreAllSurfaces(@ptrCast(*const IDirectDraw7, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw7_TestCooperativeLevel(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw7.VTable, self.vtable).TestCooperativeLevel(@ptrCast(*const IDirectDraw7, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw7_GetDeviceIdentifier(self: *const T, param0: ?*DDDEVICEIDENTIFIER2, param1: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw7.VTable, self.vtable).GetDeviceIdentifier(@ptrCast(*const IDirectDraw7, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw7_StartModeTest(self: *const T, param0: ?*SIZE, param1: u32, param2: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw7.VTable, self.vtable).StartModeTest(@ptrCast(*const IDirectDraw7, self), param0, param1, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDraw7_EvaluateMode(self: *const T, param0: u32, param1: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDraw7.VTable, self.vtable).EvaluateMode(@ptrCast(*const IDirectDraw7, self), param0, param1); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectDrawPalette_Value = Guid.initString("6c14db84-a733-11ce-a521-0020af0be560"); pub const IID_IDirectDrawPalette = &IID_IDirectDrawPalette_Value; pub const IDirectDrawPalette = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCaps: fn( self: *const IDirectDrawPalette, param0: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEntries: fn( self: *const IDirectDrawPalette, param0: u32, param1: u32, param2: u32, param3: ?*PALETTEENTRY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Initialize: fn( self: *const IDirectDrawPalette, param0: ?*IDirectDraw, param1: u32, param2: ?*PALETTEENTRY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetEntries: fn( self: *const IDirectDrawPalette, param0: u32, param1: u32, param2: u32, param3: ?*PALETTEENTRY, ) 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 IDirectDrawPalette_GetCaps(self: *const T, param0: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawPalette.VTable, self.vtable).GetCaps(@ptrCast(*const IDirectDrawPalette, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawPalette_GetEntries(self: *const T, param0: u32, param1: u32, param2: u32, param3: ?*PALETTEENTRY) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawPalette.VTable, self.vtable).GetEntries(@ptrCast(*const IDirectDrawPalette, self), param0, param1, param2, param3); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawPalette_Initialize(self: *const T, param0: ?*IDirectDraw, param1: u32, param2: ?*PALETTEENTRY) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawPalette.VTable, self.vtable).Initialize(@ptrCast(*const IDirectDrawPalette, self), param0, param1, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawPalette_SetEntries(self: *const T, param0: u32, param1: u32, param2: u32, param3: ?*PALETTEENTRY) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawPalette.VTable, self.vtable).SetEntries(@ptrCast(*const IDirectDrawPalette, self), param0, param1, param2, param3); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectDrawClipper_Value = Guid.initString("6c14db85-a733-11ce-a521-0020af0be560"); pub const IID_IDirectDrawClipper = &IID_IDirectDrawClipper_Value; pub const IDirectDrawClipper = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetClipList: fn( self: *const IDirectDrawClipper, param0: ?*RECT, param1: ?*RGNDATA, param2: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetHWnd: fn( self: *const IDirectDrawClipper, param0: ?*?HWND, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Initialize: fn( self: *const IDirectDrawClipper, param0: ?*IDirectDraw, param1: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsClipListChanged: fn( self: *const IDirectDrawClipper, param0: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetClipList: fn( self: *const IDirectDrawClipper, param0: ?*RGNDATA, param1: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetHWnd: fn( self: *const IDirectDrawClipper, param0: u32, param1: ?HWND, ) 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 IDirectDrawClipper_GetClipList(self: *const T, param0: ?*RECT, param1: ?*RGNDATA, param2: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawClipper.VTable, self.vtable).GetClipList(@ptrCast(*const IDirectDrawClipper, self), param0, param1, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawClipper_GetHWnd(self: *const T, param0: ?*?HWND) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawClipper.VTable, self.vtable).GetHWnd(@ptrCast(*const IDirectDrawClipper, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawClipper_Initialize(self: *const T, param0: ?*IDirectDraw, param1: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawClipper.VTable, self.vtable).Initialize(@ptrCast(*const IDirectDrawClipper, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawClipper_IsClipListChanged(self: *const T, param0: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawClipper.VTable, self.vtable).IsClipListChanged(@ptrCast(*const IDirectDrawClipper, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawClipper_SetClipList(self: *const T, param0: ?*RGNDATA, param1: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawClipper.VTable, self.vtable).SetClipList(@ptrCast(*const IDirectDrawClipper, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawClipper_SetHWnd(self: *const T, param0: u32, param1: ?HWND) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawClipper.VTable, self.vtable).SetHWnd(@ptrCast(*const IDirectDrawClipper, self), param0, param1); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectDrawSurface_Value = Guid.initString("6c14db81-a733-11ce-a521-0020af0be560"); pub const IID_IDirectDrawSurface = &IID_IDirectDrawSurface_Value; pub const IDirectDrawSurface = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AddAttachedSurface: fn( self: *const IDirectDrawSurface, param0: ?*IDirectDrawSurface, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddOverlayDirtyRect: fn( self: *const IDirectDrawSurface, param0: ?*RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Blt: fn( self: *const IDirectDrawSurface, param0: ?*RECT, param1: ?*IDirectDrawSurface, param2: ?*RECT, param3: u32, param4: ?*DDBLTFX, ) callconv(@import("std").os.windows.WINAPI) HRESULT, BltBatch: fn( self: *const IDirectDrawSurface, param0: ?*DDBLTBATCH, param1: u32, param2: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, BltFast: fn( self: *const IDirectDrawSurface, param0: u32, param1: u32, param2: ?*IDirectDrawSurface, param3: ?*RECT, param4: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteAttachedSurface: fn( self: *const IDirectDrawSurface, param0: u32, param1: ?*IDirectDrawSurface, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumAttachedSurfaces: fn( self: *const IDirectDrawSurface, param0: ?*anyopaque, param1: ?LPDDENUMSURFACESCALLBACK, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumOverlayZOrders: fn( self: *const IDirectDrawSurface, param0: u32, param1: ?*anyopaque, param2: ?LPDDENUMSURFACESCALLBACK, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Flip: fn( self: *const IDirectDrawSurface, param0: ?*IDirectDrawSurface, param1: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAttachedSurface: fn( self: *const IDirectDrawSurface, param0: ?*DDSCAPS, param1: ?*?*IDirectDrawSurface, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBltStatus: fn( self: *const IDirectDrawSurface, param0: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCaps: fn( self: *const IDirectDrawSurface, param0: ?*DDSCAPS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetClipper: fn( self: *const IDirectDrawSurface, param0: ?*?*IDirectDrawClipper, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetColorKey: fn( self: *const IDirectDrawSurface, param0: u32, param1: ?*DDCOLORKEY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDC: fn( self: *const IDirectDrawSurface, param0: ?*?HDC, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFlipStatus: fn( self: *const IDirectDrawSurface, param0: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOverlayPosition: fn( self: *const IDirectDrawSurface, param0: ?*i32, param1: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPalette: fn( self: *const IDirectDrawSurface, param0: ?*?*IDirectDrawPalette, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPixelFormat: fn( self: *const IDirectDrawSurface, param0: ?*DDPIXELFORMAT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSurfaceDesc: fn( self: *const IDirectDrawSurface, param0: ?*DDSURFACEDESC, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Initialize: fn( self: *const IDirectDrawSurface, param0: ?*IDirectDraw, param1: ?*DDSURFACEDESC, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsLost: fn( self: *const IDirectDrawSurface, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Lock: fn( self: *const IDirectDrawSurface, param0: ?*RECT, param1: ?*DDSURFACEDESC, param2: u32, param3: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ReleaseDC: fn( self: *const IDirectDrawSurface, param0: ?HDC, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Restore: fn( self: *const IDirectDrawSurface, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetClipper: fn( self: *const IDirectDrawSurface, param0: ?*IDirectDrawClipper, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetColorKey: fn( self: *const IDirectDrawSurface, param0: u32, param1: ?*DDCOLORKEY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetOverlayPosition: fn( self: *const IDirectDrawSurface, param0: i32, param1: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPalette: fn( self: *const IDirectDrawSurface, param0: ?*IDirectDrawPalette, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Unlock: fn( self: *const IDirectDrawSurface, param0: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpdateOverlay: fn( self: *const IDirectDrawSurface, param0: ?*RECT, param1: ?*IDirectDrawSurface, param2: ?*RECT, param3: u32, param4: ?*DDOVERLAYFX, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpdateOverlayDisplay: fn( self: *const IDirectDrawSurface, param0: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpdateOverlayZOrder: fn( self: *const IDirectDrawSurface, param0: u32, param1: ?*IDirectDrawSurface, ) 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 IDirectDrawSurface_AddAttachedSurface(self: *const T, param0: ?*IDirectDrawSurface) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).AddAttachedSurface(@ptrCast(*const IDirectDrawSurface, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_AddOverlayDirtyRect(self: *const T, param0: ?*RECT) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).AddOverlayDirtyRect(@ptrCast(*const IDirectDrawSurface, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_Blt(self: *const T, param0: ?*RECT, param1: ?*IDirectDrawSurface, param2: ?*RECT, param3: u32, param4: ?*DDBLTFX) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).Blt(@ptrCast(*const IDirectDrawSurface, self), param0, param1, param2, param3, param4); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_BltBatch(self: *const T, param0: ?*DDBLTBATCH, param1: u32, param2: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).BltBatch(@ptrCast(*const IDirectDrawSurface, self), param0, param1, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_BltFast(self: *const T, param0: u32, param1: u32, param2: ?*IDirectDrawSurface, param3: ?*RECT, param4: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).BltFast(@ptrCast(*const IDirectDrawSurface, self), param0, param1, param2, param3, param4); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_DeleteAttachedSurface(self: *const T, param0: u32, param1: ?*IDirectDrawSurface) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).DeleteAttachedSurface(@ptrCast(*const IDirectDrawSurface, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_EnumAttachedSurfaces(self: *const T, param0: ?*anyopaque, param1: ?LPDDENUMSURFACESCALLBACK) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).EnumAttachedSurfaces(@ptrCast(*const IDirectDrawSurface, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_EnumOverlayZOrders(self: *const T, param0: u32, param1: ?*anyopaque, param2: ?LPDDENUMSURFACESCALLBACK) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).EnumOverlayZOrders(@ptrCast(*const IDirectDrawSurface, self), param0, param1, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_Flip(self: *const T, param0: ?*IDirectDrawSurface, param1: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).Flip(@ptrCast(*const IDirectDrawSurface, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_GetAttachedSurface(self: *const T, param0: ?*DDSCAPS, param1: ?*?*IDirectDrawSurface) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).GetAttachedSurface(@ptrCast(*const IDirectDrawSurface, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_GetBltStatus(self: *const T, param0: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).GetBltStatus(@ptrCast(*const IDirectDrawSurface, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_GetCaps(self: *const T, param0: ?*DDSCAPS) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).GetCaps(@ptrCast(*const IDirectDrawSurface, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_GetClipper(self: *const T, param0: ?*?*IDirectDrawClipper) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).GetClipper(@ptrCast(*const IDirectDrawSurface, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_GetColorKey(self: *const T, param0: u32, param1: ?*DDCOLORKEY) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).GetColorKey(@ptrCast(*const IDirectDrawSurface, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_GetDC(self: *const T, param0: ?*?HDC) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).GetDC(@ptrCast(*const IDirectDrawSurface, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_GetFlipStatus(self: *const T, param0: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).GetFlipStatus(@ptrCast(*const IDirectDrawSurface, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_GetOverlayPosition(self: *const T, param0: ?*i32, param1: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).GetOverlayPosition(@ptrCast(*const IDirectDrawSurface, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_GetPalette(self: *const T, param0: ?*?*IDirectDrawPalette) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).GetPalette(@ptrCast(*const IDirectDrawSurface, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_GetPixelFormat(self: *const T, param0: ?*DDPIXELFORMAT) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).GetPixelFormat(@ptrCast(*const IDirectDrawSurface, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_GetSurfaceDesc(self: *const T, param0: ?*DDSURFACEDESC) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).GetSurfaceDesc(@ptrCast(*const IDirectDrawSurface, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_Initialize(self: *const T, param0: ?*IDirectDraw, param1: ?*DDSURFACEDESC) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).Initialize(@ptrCast(*const IDirectDrawSurface, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_IsLost(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).IsLost(@ptrCast(*const IDirectDrawSurface, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_Lock(self: *const T, param0: ?*RECT, param1: ?*DDSURFACEDESC, param2: u32, param3: ?HANDLE) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).Lock(@ptrCast(*const IDirectDrawSurface, self), param0, param1, param2, param3); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_ReleaseDC(self: *const T, param0: ?HDC) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).ReleaseDC(@ptrCast(*const IDirectDrawSurface, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_Restore(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).Restore(@ptrCast(*const IDirectDrawSurface, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_SetClipper(self: *const T, param0: ?*IDirectDrawClipper) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).SetClipper(@ptrCast(*const IDirectDrawSurface, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_SetColorKey(self: *const T, param0: u32, param1: ?*DDCOLORKEY) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).SetColorKey(@ptrCast(*const IDirectDrawSurface, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_SetOverlayPosition(self: *const T, param0: i32, param1: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).SetOverlayPosition(@ptrCast(*const IDirectDrawSurface, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_SetPalette(self: *const T, param0: ?*IDirectDrawPalette) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).SetPalette(@ptrCast(*const IDirectDrawSurface, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_Unlock(self: *const T, param0: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).Unlock(@ptrCast(*const IDirectDrawSurface, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_UpdateOverlay(self: *const T, param0: ?*RECT, param1: ?*IDirectDrawSurface, param2: ?*RECT, param3: u32, param4: ?*DDOVERLAYFX) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).UpdateOverlay(@ptrCast(*const IDirectDrawSurface, self), param0, param1, param2, param3, param4); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_UpdateOverlayDisplay(self: *const T, param0: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).UpdateOverlayDisplay(@ptrCast(*const IDirectDrawSurface, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface_UpdateOverlayZOrder(self: *const T, param0: u32, param1: ?*IDirectDrawSurface) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface.VTable, self.vtable).UpdateOverlayZOrder(@ptrCast(*const IDirectDrawSurface, self), param0, param1); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectDrawSurface2_Value = Guid.initString("57805885-6eec-11cf-9441-a82303c10e27"); pub const IID_IDirectDrawSurface2 = &IID_IDirectDrawSurface2_Value; pub const IDirectDrawSurface2 = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AddAttachedSurface: fn( self: *const IDirectDrawSurface2, param0: ?*IDirectDrawSurface2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddOverlayDirtyRect: fn( self: *const IDirectDrawSurface2, param0: ?*RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Blt: fn( self: *const IDirectDrawSurface2, param0: ?*RECT, param1: ?*IDirectDrawSurface2, param2: ?*RECT, param3: u32, param4: ?*DDBLTFX, ) callconv(@import("std").os.windows.WINAPI) HRESULT, BltBatch: fn( self: *const IDirectDrawSurface2, param0: ?*DDBLTBATCH, param1: u32, param2: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, BltFast: fn( self: *const IDirectDrawSurface2, param0: u32, param1: u32, param2: ?*IDirectDrawSurface2, param3: ?*RECT, param4: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteAttachedSurface: fn( self: *const IDirectDrawSurface2, param0: u32, param1: ?*IDirectDrawSurface2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumAttachedSurfaces: fn( self: *const IDirectDrawSurface2, param0: ?*anyopaque, param1: ?LPDDENUMSURFACESCALLBACK, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumOverlayZOrders: fn( self: *const IDirectDrawSurface2, param0: u32, param1: ?*anyopaque, param2: ?LPDDENUMSURFACESCALLBACK, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Flip: fn( self: *const IDirectDrawSurface2, param0: ?*IDirectDrawSurface2, param1: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAttachedSurface: fn( self: *const IDirectDrawSurface2, param0: ?*DDSCAPS, param1: ?*?*IDirectDrawSurface2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBltStatus: fn( self: *const IDirectDrawSurface2, param0: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCaps: fn( self: *const IDirectDrawSurface2, param0: ?*DDSCAPS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetClipper: fn( self: *const IDirectDrawSurface2, param0: ?*?*IDirectDrawClipper, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetColorKey: fn( self: *const IDirectDrawSurface2, param0: u32, param1: ?*DDCOLORKEY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDC: fn( self: *const IDirectDrawSurface2, param0: ?*?HDC, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFlipStatus: fn( self: *const IDirectDrawSurface2, param0: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOverlayPosition: fn( self: *const IDirectDrawSurface2, param0: ?*i32, param1: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPalette: fn( self: *const IDirectDrawSurface2, param0: ?*?*IDirectDrawPalette, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPixelFormat: fn( self: *const IDirectDrawSurface2, param0: ?*DDPIXELFORMAT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSurfaceDesc: fn( self: *const IDirectDrawSurface2, param0: ?*DDSURFACEDESC, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Initialize: fn( self: *const IDirectDrawSurface2, param0: ?*IDirectDraw, param1: ?*DDSURFACEDESC, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsLost: fn( self: *const IDirectDrawSurface2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Lock: fn( self: *const IDirectDrawSurface2, param0: ?*RECT, param1: ?*DDSURFACEDESC, param2: u32, param3: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ReleaseDC: fn( self: *const IDirectDrawSurface2, param0: ?HDC, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Restore: fn( self: *const IDirectDrawSurface2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetClipper: fn( self: *const IDirectDrawSurface2, param0: ?*IDirectDrawClipper, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetColorKey: fn( self: *const IDirectDrawSurface2, param0: u32, param1: ?*DDCOLORKEY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetOverlayPosition: fn( self: *const IDirectDrawSurface2, param0: i32, param1: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPalette: fn( self: *const IDirectDrawSurface2, param0: ?*IDirectDrawPalette, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Unlock: fn( self: *const IDirectDrawSurface2, param0: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpdateOverlay: fn( self: *const IDirectDrawSurface2, param0: ?*RECT, param1: ?*IDirectDrawSurface2, param2: ?*RECT, param3: u32, param4: ?*DDOVERLAYFX, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpdateOverlayDisplay: fn( self: *const IDirectDrawSurface2, param0: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpdateOverlayZOrder: fn( self: *const IDirectDrawSurface2, param0: u32, param1: ?*IDirectDrawSurface2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDDInterface: fn( self: *const IDirectDrawSurface2, param0: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PageLock: fn( self: *const IDirectDrawSurface2, param0: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PageUnlock: fn( self: *const IDirectDrawSurface2, param0: 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 IDirectDrawSurface2_AddAttachedSurface(self: *const T, param0: ?*IDirectDrawSurface2) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).AddAttachedSurface(@ptrCast(*const IDirectDrawSurface2, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_AddOverlayDirtyRect(self: *const T, param0: ?*RECT) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).AddOverlayDirtyRect(@ptrCast(*const IDirectDrawSurface2, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_Blt(self: *const T, param0: ?*RECT, param1: ?*IDirectDrawSurface2, param2: ?*RECT, param3: u32, param4: ?*DDBLTFX) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).Blt(@ptrCast(*const IDirectDrawSurface2, self), param0, param1, param2, param3, param4); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_BltBatch(self: *const T, param0: ?*DDBLTBATCH, param1: u32, param2: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).BltBatch(@ptrCast(*const IDirectDrawSurface2, self), param0, param1, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_BltFast(self: *const T, param0: u32, param1: u32, param2: ?*IDirectDrawSurface2, param3: ?*RECT, param4: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).BltFast(@ptrCast(*const IDirectDrawSurface2, self), param0, param1, param2, param3, param4); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_DeleteAttachedSurface(self: *const T, param0: u32, param1: ?*IDirectDrawSurface2) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).DeleteAttachedSurface(@ptrCast(*const IDirectDrawSurface2, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_EnumAttachedSurfaces(self: *const T, param0: ?*anyopaque, param1: ?LPDDENUMSURFACESCALLBACK) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).EnumAttachedSurfaces(@ptrCast(*const IDirectDrawSurface2, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_EnumOverlayZOrders(self: *const T, param0: u32, param1: ?*anyopaque, param2: ?LPDDENUMSURFACESCALLBACK) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).EnumOverlayZOrders(@ptrCast(*const IDirectDrawSurface2, self), param0, param1, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_Flip(self: *const T, param0: ?*IDirectDrawSurface2, param1: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).Flip(@ptrCast(*const IDirectDrawSurface2, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_GetAttachedSurface(self: *const T, param0: ?*DDSCAPS, param1: ?*?*IDirectDrawSurface2) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).GetAttachedSurface(@ptrCast(*const IDirectDrawSurface2, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_GetBltStatus(self: *const T, param0: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).GetBltStatus(@ptrCast(*const IDirectDrawSurface2, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_GetCaps(self: *const T, param0: ?*DDSCAPS) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).GetCaps(@ptrCast(*const IDirectDrawSurface2, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_GetClipper(self: *const T, param0: ?*?*IDirectDrawClipper) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).GetClipper(@ptrCast(*const IDirectDrawSurface2, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_GetColorKey(self: *const T, param0: u32, param1: ?*DDCOLORKEY) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).GetColorKey(@ptrCast(*const IDirectDrawSurface2, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_GetDC(self: *const T, param0: ?*?HDC) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).GetDC(@ptrCast(*const IDirectDrawSurface2, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_GetFlipStatus(self: *const T, param0: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).GetFlipStatus(@ptrCast(*const IDirectDrawSurface2, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_GetOverlayPosition(self: *const T, param0: ?*i32, param1: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).GetOverlayPosition(@ptrCast(*const IDirectDrawSurface2, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_GetPalette(self: *const T, param0: ?*?*IDirectDrawPalette) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).GetPalette(@ptrCast(*const IDirectDrawSurface2, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_GetPixelFormat(self: *const T, param0: ?*DDPIXELFORMAT) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).GetPixelFormat(@ptrCast(*const IDirectDrawSurface2, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_GetSurfaceDesc(self: *const T, param0: ?*DDSURFACEDESC) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).GetSurfaceDesc(@ptrCast(*const IDirectDrawSurface2, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_Initialize(self: *const T, param0: ?*IDirectDraw, param1: ?*DDSURFACEDESC) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).Initialize(@ptrCast(*const IDirectDrawSurface2, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_IsLost(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).IsLost(@ptrCast(*const IDirectDrawSurface2, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_Lock(self: *const T, param0: ?*RECT, param1: ?*DDSURFACEDESC, param2: u32, param3: ?HANDLE) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).Lock(@ptrCast(*const IDirectDrawSurface2, self), param0, param1, param2, param3); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_ReleaseDC(self: *const T, param0: ?HDC) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).ReleaseDC(@ptrCast(*const IDirectDrawSurface2, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_Restore(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).Restore(@ptrCast(*const IDirectDrawSurface2, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_SetClipper(self: *const T, param0: ?*IDirectDrawClipper) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).SetClipper(@ptrCast(*const IDirectDrawSurface2, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_SetColorKey(self: *const T, param0: u32, param1: ?*DDCOLORKEY) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).SetColorKey(@ptrCast(*const IDirectDrawSurface2, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_SetOverlayPosition(self: *const T, param0: i32, param1: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).SetOverlayPosition(@ptrCast(*const IDirectDrawSurface2, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_SetPalette(self: *const T, param0: ?*IDirectDrawPalette) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).SetPalette(@ptrCast(*const IDirectDrawSurface2, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_Unlock(self: *const T, param0: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).Unlock(@ptrCast(*const IDirectDrawSurface2, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_UpdateOverlay(self: *const T, param0: ?*RECT, param1: ?*IDirectDrawSurface2, param2: ?*RECT, param3: u32, param4: ?*DDOVERLAYFX) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).UpdateOverlay(@ptrCast(*const IDirectDrawSurface2, self), param0, param1, param2, param3, param4); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_UpdateOverlayDisplay(self: *const T, param0: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).UpdateOverlayDisplay(@ptrCast(*const IDirectDrawSurface2, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_UpdateOverlayZOrder(self: *const T, param0: u32, param1: ?*IDirectDrawSurface2) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).UpdateOverlayZOrder(@ptrCast(*const IDirectDrawSurface2, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_GetDDInterface(self: *const T, param0: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).GetDDInterface(@ptrCast(*const IDirectDrawSurface2, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_PageLock(self: *const T, param0: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).PageLock(@ptrCast(*const IDirectDrawSurface2, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface2_PageUnlock(self: *const T, param0: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface2.VTable, self.vtable).PageUnlock(@ptrCast(*const IDirectDrawSurface2, self), param0); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectDrawSurface3_Value = Guid.initString("da044e00-69b2-11d0-a1d5-00aa00b8dfbb"); pub const IID_IDirectDrawSurface3 = &IID_IDirectDrawSurface3_Value; pub const IDirectDrawSurface3 = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AddAttachedSurface: fn( self: *const IDirectDrawSurface3, param0: ?*IDirectDrawSurface3, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddOverlayDirtyRect: fn( self: *const IDirectDrawSurface3, param0: ?*RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Blt: fn( self: *const IDirectDrawSurface3, param0: ?*RECT, param1: ?*IDirectDrawSurface3, param2: ?*RECT, param3: u32, param4: ?*DDBLTFX, ) callconv(@import("std").os.windows.WINAPI) HRESULT, BltBatch: fn( self: *const IDirectDrawSurface3, param0: ?*DDBLTBATCH, param1: u32, param2: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, BltFast: fn( self: *const IDirectDrawSurface3, param0: u32, param1: u32, param2: ?*IDirectDrawSurface3, param3: ?*RECT, param4: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteAttachedSurface: fn( self: *const IDirectDrawSurface3, param0: u32, param1: ?*IDirectDrawSurface3, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumAttachedSurfaces: fn( self: *const IDirectDrawSurface3, param0: ?*anyopaque, param1: ?LPDDENUMSURFACESCALLBACK, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumOverlayZOrders: fn( self: *const IDirectDrawSurface3, param0: u32, param1: ?*anyopaque, param2: ?LPDDENUMSURFACESCALLBACK, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Flip: fn( self: *const IDirectDrawSurface3, param0: ?*IDirectDrawSurface3, param1: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAttachedSurface: fn( self: *const IDirectDrawSurface3, param0: ?*DDSCAPS, param1: ?*?*IDirectDrawSurface3, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBltStatus: fn( self: *const IDirectDrawSurface3, param0: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCaps: fn( self: *const IDirectDrawSurface3, param0: ?*DDSCAPS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetClipper: fn( self: *const IDirectDrawSurface3, param0: ?*?*IDirectDrawClipper, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetColorKey: fn( self: *const IDirectDrawSurface3, param0: u32, param1: ?*DDCOLORKEY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDC: fn( self: *const IDirectDrawSurface3, param0: ?*?HDC, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFlipStatus: fn( self: *const IDirectDrawSurface3, param0: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOverlayPosition: fn( self: *const IDirectDrawSurface3, param0: ?*i32, param1: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPalette: fn( self: *const IDirectDrawSurface3, param0: ?*?*IDirectDrawPalette, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPixelFormat: fn( self: *const IDirectDrawSurface3, param0: ?*DDPIXELFORMAT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSurfaceDesc: fn( self: *const IDirectDrawSurface3, param0: ?*DDSURFACEDESC, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Initialize: fn( self: *const IDirectDrawSurface3, param0: ?*IDirectDraw, param1: ?*DDSURFACEDESC, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsLost: fn( self: *const IDirectDrawSurface3, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Lock: fn( self: *const IDirectDrawSurface3, param0: ?*RECT, param1: ?*DDSURFACEDESC, param2: u32, param3: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ReleaseDC: fn( self: *const IDirectDrawSurface3, param0: ?HDC, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Restore: fn( self: *const IDirectDrawSurface3, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetClipper: fn( self: *const IDirectDrawSurface3, param0: ?*IDirectDrawClipper, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetColorKey: fn( self: *const IDirectDrawSurface3, param0: u32, param1: ?*DDCOLORKEY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetOverlayPosition: fn( self: *const IDirectDrawSurface3, param0: i32, param1: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPalette: fn( self: *const IDirectDrawSurface3, param0: ?*IDirectDrawPalette, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Unlock: fn( self: *const IDirectDrawSurface3, param0: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpdateOverlay: fn( self: *const IDirectDrawSurface3, param0: ?*RECT, param1: ?*IDirectDrawSurface3, param2: ?*RECT, param3: u32, param4: ?*DDOVERLAYFX, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpdateOverlayDisplay: fn( self: *const IDirectDrawSurface3, param0: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpdateOverlayZOrder: fn( self: *const IDirectDrawSurface3, param0: u32, param1: ?*IDirectDrawSurface3, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDDInterface: fn( self: *const IDirectDrawSurface3, param0: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PageLock: fn( self: *const IDirectDrawSurface3, param0: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PageUnlock: fn( self: *const IDirectDrawSurface3, param0: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSurfaceDesc: fn( self: *const IDirectDrawSurface3, param0: ?*DDSURFACEDESC, param1: 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 IDirectDrawSurface3_AddAttachedSurface(self: *const T, param0: ?*IDirectDrawSurface3) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).AddAttachedSurface(@ptrCast(*const IDirectDrawSurface3, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_AddOverlayDirtyRect(self: *const T, param0: ?*RECT) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).AddOverlayDirtyRect(@ptrCast(*const IDirectDrawSurface3, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_Blt(self: *const T, param0: ?*RECT, param1: ?*IDirectDrawSurface3, param2: ?*RECT, param3: u32, param4: ?*DDBLTFX) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).Blt(@ptrCast(*const IDirectDrawSurface3, self), param0, param1, param2, param3, param4); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_BltBatch(self: *const T, param0: ?*DDBLTBATCH, param1: u32, param2: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).BltBatch(@ptrCast(*const IDirectDrawSurface3, self), param0, param1, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_BltFast(self: *const T, param0: u32, param1: u32, param2: ?*IDirectDrawSurface3, param3: ?*RECT, param4: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).BltFast(@ptrCast(*const IDirectDrawSurface3, self), param0, param1, param2, param3, param4); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_DeleteAttachedSurface(self: *const T, param0: u32, param1: ?*IDirectDrawSurface3) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).DeleteAttachedSurface(@ptrCast(*const IDirectDrawSurface3, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_EnumAttachedSurfaces(self: *const T, param0: ?*anyopaque, param1: ?LPDDENUMSURFACESCALLBACK) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).EnumAttachedSurfaces(@ptrCast(*const IDirectDrawSurface3, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_EnumOverlayZOrders(self: *const T, param0: u32, param1: ?*anyopaque, param2: ?LPDDENUMSURFACESCALLBACK) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).EnumOverlayZOrders(@ptrCast(*const IDirectDrawSurface3, self), param0, param1, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_Flip(self: *const T, param0: ?*IDirectDrawSurface3, param1: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).Flip(@ptrCast(*const IDirectDrawSurface3, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_GetAttachedSurface(self: *const T, param0: ?*DDSCAPS, param1: ?*?*IDirectDrawSurface3) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).GetAttachedSurface(@ptrCast(*const IDirectDrawSurface3, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_GetBltStatus(self: *const T, param0: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).GetBltStatus(@ptrCast(*const IDirectDrawSurface3, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_GetCaps(self: *const T, param0: ?*DDSCAPS) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).GetCaps(@ptrCast(*const IDirectDrawSurface3, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_GetClipper(self: *const T, param0: ?*?*IDirectDrawClipper) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).GetClipper(@ptrCast(*const IDirectDrawSurface3, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_GetColorKey(self: *const T, param0: u32, param1: ?*DDCOLORKEY) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).GetColorKey(@ptrCast(*const IDirectDrawSurface3, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_GetDC(self: *const T, param0: ?*?HDC) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).GetDC(@ptrCast(*const IDirectDrawSurface3, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_GetFlipStatus(self: *const T, param0: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).GetFlipStatus(@ptrCast(*const IDirectDrawSurface3, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_GetOverlayPosition(self: *const T, param0: ?*i32, param1: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).GetOverlayPosition(@ptrCast(*const IDirectDrawSurface3, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_GetPalette(self: *const T, param0: ?*?*IDirectDrawPalette) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).GetPalette(@ptrCast(*const IDirectDrawSurface3, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_GetPixelFormat(self: *const T, param0: ?*DDPIXELFORMAT) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).GetPixelFormat(@ptrCast(*const IDirectDrawSurface3, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_GetSurfaceDesc(self: *const T, param0: ?*DDSURFACEDESC) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).GetSurfaceDesc(@ptrCast(*const IDirectDrawSurface3, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_Initialize(self: *const T, param0: ?*IDirectDraw, param1: ?*DDSURFACEDESC) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).Initialize(@ptrCast(*const IDirectDrawSurface3, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_IsLost(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).IsLost(@ptrCast(*const IDirectDrawSurface3, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_Lock(self: *const T, param0: ?*RECT, param1: ?*DDSURFACEDESC, param2: u32, param3: ?HANDLE) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).Lock(@ptrCast(*const IDirectDrawSurface3, self), param0, param1, param2, param3); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_ReleaseDC(self: *const T, param0: ?HDC) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).ReleaseDC(@ptrCast(*const IDirectDrawSurface3, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_Restore(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).Restore(@ptrCast(*const IDirectDrawSurface3, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_SetClipper(self: *const T, param0: ?*IDirectDrawClipper) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).SetClipper(@ptrCast(*const IDirectDrawSurface3, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_SetColorKey(self: *const T, param0: u32, param1: ?*DDCOLORKEY) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).SetColorKey(@ptrCast(*const IDirectDrawSurface3, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_SetOverlayPosition(self: *const T, param0: i32, param1: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).SetOverlayPosition(@ptrCast(*const IDirectDrawSurface3, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_SetPalette(self: *const T, param0: ?*IDirectDrawPalette) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).SetPalette(@ptrCast(*const IDirectDrawSurface3, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_Unlock(self: *const T, param0: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).Unlock(@ptrCast(*const IDirectDrawSurface3, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_UpdateOverlay(self: *const T, param0: ?*RECT, param1: ?*IDirectDrawSurface3, param2: ?*RECT, param3: u32, param4: ?*DDOVERLAYFX) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).UpdateOverlay(@ptrCast(*const IDirectDrawSurface3, self), param0, param1, param2, param3, param4); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_UpdateOverlayDisplay(self: *const T, param0: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).UpdateOverlayDisplay(@ptrCast(*const IDirectDrawSurface3, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_UpdateOverlayZOrder(self: *const T, param0: u32, param1: ?*IDirectDrawSurface3) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).UpdateOverlayZOrder(@ptrCast(*const IDirectDrawSurface3, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_GetDDInterface(self: *const T, param0: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).GetDDInterface(@ptrCast(*const IDirectDrawSurface3, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_PageLock(self: *const T, param0: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).PageLock(@ptrCast(*const IDirectDrawSurface3, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_PageUnlock(self: *const T, param0: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).PageUnlock(@ptrCast(*const IDirectDrawSurface3, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface3_SetSurfaceDesc(self: *const T, param0: ?*DDSURFACEDESC, param1: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface3.VTable, self.vtable).SetSurfaceDesc(@ptrCast(*const IDirectDrawSurface3, self), param0, param1); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectDrawSurface4_Value = Guid.initString("0b2b8630-ad35-11d0-8ea6-00609797ea5b"); pub const IID_IDirectDrawSurface4 = &IID_IDirectDrawSurface4_Value; pub const IDirectDrawSurface4 = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AddAttachedSurface: fn( self: *const IDirectDrawSurface4, param0: ?*IDirectDrawSurface4, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddOverlayDirtyRect: fn( self: *const IDirectDrawSurface4, param0: ?*RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Blt: fn( self: *const IDirectDrawSurface4, param0: ?*RECT, param1: ?*IDirectDrawSurface4, param2: ?*RECT, param3: u32, param4: ?*DDBLTFX, ) callconv(@import("std").os.windows.WINAPI) HRESULT, BltBatch: fn( self: *const IDirectDrawSurface4, param0: ?*DDBLTBATCH, param1: u32, param2: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, BltFast: fn( self: *const IDirectDrawSurface4, param0: u32, param1: u32, param2: ?*IDirectDrawSurface4, param3: ?*RECT, param4: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteAttachedSurface: fn( self: *const IDirectDrawSurface4, param0: u32, param1: ?*IDirectDrawSurface4, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumAttachedSurfaces: fn( self: *const IDirectDrawSurface4, param0: ?*anyopaque, param1: ?LPDDENUMSURFACESCALLBACK2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumOverlayZOrders: fn( self: *const IDirectDrawSurface4, param0: u32, param1: ?*anyopaque, param2: ?LPDDENUMSURFACESCALLBACK2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Flip: fn( self: *const IDirectDrawSurface4, param0: ?*IDirectDrawSurface4, param1: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAttachedSurface: fn( self: *const IDirectDrawSurface4, param0: ?*DDSCAPS2, param1: ?*?*IDirectDrawSurface4, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBltStatus: fn( self: *const IDirectDrawSurface4, param0: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCaps: fn( self: *const IDirectDrawSurface4, param0: ?*DDSCAPS2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetClipper: fn( self: *const IDirectDrawSurface4, param0: ?*?*IDirectDrawClipper, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetColorKey: fn( self: *const IDirectDrawSurface4, param0: u32, param1: ?*DDCOLORKEY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDC: fn( self: *const IDirectDrawSurface4, param0: ?*?HDC, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFlipStatus: fn( self: *const IDirectDrawSurface4, param0: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOverlayPosition: fn( self: *const IDirectDrawSurface4, param0: ?*i32, param1: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPalette: fn( self: *const IDirectDrawSurface4, param0: ?*?*IDirectDrawPalette, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPixelFormat: fn( self: *const IDirectDrawSurface4, param0: ?*DDPIXELFORMAT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSurfaceDesc: fn( self: *const IDirectDrawSurface4, param0: ?*DDSURFACEDESC2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Initialize: fn( self: *const IDirectDrawSurface4, param0: ?*IDirectDraw, param1: ?*DDSURFACEDESC2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsLost: fn( self: *const IDirectDrawSurface4, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Lock: fn( self: *const IDirectDrawSurface4, param0: ?*RECT, param1: ?*DDSURFACEDESC2, param2: u32, param3: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ReleaseDC: fn( self: *const IDirectDrawSurface4, param0: ?HDC, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Restore: fn( self: *const IDirectDrawSurface4, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetClipper: fn( self: *const IDirectDrawSurface4, param0: ?*IDirectDrawClipper, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetColorKey: fn( self: *const IDirectDrawSurface4, param0: u32, param1: ?*DDCOLORKEY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetOverlayPosition: fn( self: *const IDirectDrawSurface4, param0: i32, param1: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPalette: fn( self: *const IDirectDrawSurface4, param0: ?*IDirectDrawPalette, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Unlock: fn( self: *const IDirectDrawSurface4, param0: ?*RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpdateOverlay: fn( self: *const IDirectDrawSurface4, param0: ?*RECT, param1: ?*IDirectDrawSurface4, param2: ?*RECT, param3: u32, param4: ?*DDOVERLAYFX, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpdateOverlayDisplay: fn( self: *const IDirectDrawSurface4, param0: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpdateOverlayZOrder: fn( self: *const IDirectDrawSurface4, param0: u32, param1: ?*IDirectDrawSurface4, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDDInterface: fn( self: *const IDirectDrawSurface4, param0: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PageLock: fn( self: *const IDirectDrawSurface4, param0: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PageUnlock: fn( self: *const IDirectDrawSurface4, param0: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSurfaceDesc: fn( self: *const IDirectDrawSurface4, param0: ?*DDSURFACEDESC2, param1: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPrivateData: fn( self: *const IDirectDrawSurface4, param0: ?*const Guid, param1: ?*anyopaque, param2: u32, param3: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPrivateData: fn( self: *const IDirectDrawSurface4, param0: ?*const Guid, param1: ?*anyopaque, param2: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FreePrivateData: fn( self: *const IDirectDrawSurface4, param0: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetUniquenessValue: fn( self: *const IDirectDrawSurface4, param0: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ChangeUniquenessValue: fn( self: *const IDirectDrawSurface4, ) 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 IDirectDrawSurface4_AddAttachedSurface(self: *const T, param0: ?*IDirectDrawSurface4) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).AddAttachedSurface(@ptrCast(*const IDirectDrawSurface4, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_AddOverlayDirtyRect(self: *const T, param0: ?*RECT) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).AddOverlayDirtyRect(@ptrCast(*const IDirectDrawSurface4, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_Blt(self: *const T, param0: ?*RECT, param1: ?*IDirectDrawSurface4, param2: ?*RECT, param3: u32, param4: ?*DDBLTFX) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).Blt(@ptrCast(*const IDirectDrawSurface4, self), param0, param1, param2, param3, param4); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_BltBatch(self: *const T, param0: ?*DDBLTBATCH, param1: u32, param2: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).BltBatch(@ptrCast(*const IDirectDrawSurface4, self), param0, param1, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_BltFast(self: *const T, param0: u32, param1: u32, param2: ?*IDirectDrawSurface4, param3: ?*RECT, param4: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).BltFast(@ptrCast(*const IDirectDrawSurface4, self), param0, param1, param2, param3, param4); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_DeleteAttachedSurface(self: *const T, param0: u32, param1: ?*IDirectDrawSurface4) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).DeleteAttachedSurface(@ptrCast(*const IDirectDrawSurface4, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_EnumAttachedSurfaces(self: *const T, param0: ?*anyopaque, param1: ?LPDDENUMSURFACESCALLBACK2) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).EnumAttachedSurfaces(@ptrCast(*const IDirectDrawSurface4, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_EnumOverlayZOrders(self: *const T, param0: u32, param1: ?*anyopaque, param2: ?LPDDENUMSURFACESCALLBACK2) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).EnumOverlayZOrders(@ptrCast(*const IDirectDrawSurface4, self), param0, param1, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_Flip(self: *const T, param0: ?*IDirectDrawSurface4, param1: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).Flip(@ptrCast(*const IDirectDrawSurface4, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_GetAttachedSurface(self: *const T, param0: ?*DDSCAPS2, param1: ?*?*IDirectDrawSurface4) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).GetAttachedSurface(@ptrCast(*const IDirectDrawSurface4, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_GetBltStatus(self: *const T, param0: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).GetBltStatus(@ptrCast(*const IDirectDrawSurface4, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_GetCaps(self: *const T, param0: ?*DDSCAPS2) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).GetCaps(@ptrCast(*const IDirectDrawSurface4, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_GetClipper(self: *const T, param0: ?*?*IDirectDrawClipper) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).GetClipper(@ptrCast(*const IDirectDrawSurface4, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_GetColorKey(self: *const T, param0: u32, param1: ?*DDCOLORKEY) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).GetColorKey(@ptrCast(*const IDirectDrawSurface4, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_GetDC(self: *const T, param0: ?*?HDC) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).GetDC(@ptrCast(*const IDirectDrawSurface4, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_GetFlipStatus(self: *const T, param0: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).GetFlipStatus(@ptrCast(*const IDirectDrawSurface4, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_GetOverlayPosition(self: *const T, param0: ?*i32, param1: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).GetOverlayPosition(@ptrCast(*const IDirectDrawSurface4, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_GetPalette(self: *const T, param0: ?*?*IDirectDrawPalette) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).GetPalette(@ptrCast(*const IDirectDrawSurface4, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_GetPixelFormat(self: *const T, param0: ?*DDPIXELFORMAT) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).GetPixelFormat(@ptrCast(*const IDirectDrawSurface4, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_GetSurfaceDesc(self: *const T, param0: ?*DDSURFACEDESC2) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).GetSurfaceDesc(@ptrCast(*const IDirectDrawSurface4, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_Initialize(self: *const T, param0: ?*IDirectDraw, param1: ?*DDSURFACEDESC2) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).Initialize(@ptrCast(*const IDirectDrawSurface4, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_IsLost(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).IsLost(@ptrCast(*const IDirectDrawSurface4, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_Lock(self: *const T, param0: ?*RECT, param1: ?*DDSURFACEDESC2, param2: u32, param3: ?HANDLE) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).Lock(@ptrCast(*const IDirectDrawSurface4, self), param0, param1, param2, param3); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_ReleaseDC(self: *const T, param0: ?HDC) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).ReleaseDC(@ptrCast(*const IDirectDrawSurface4, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_Restore(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).Restore(@ptrCast(*const IDirectDrawSurface4, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_SetClipper(self: *const T, param0: ?*IDirectDrawClipper) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).SetClipper(@ptrCast(*const IDirectDrawSurface4, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_SetColorKey(self: *const T, param0: u32, param1: ?*DDCOLORKEY) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).SetColorKey(@ptrCast(*const IDirectDrawSurface4, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_SetOverlayPosition(self: *const T, param0: i32, param1: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).SetOverlayPosition(@ptrCast(*const IDirectDrawSurface4, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_SetPalette(self: *const T, param0: ?*IDirectDrawPalette) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).SetPalette(@ptrCast(*const IDirectDrawSurface4, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_Unlock(self: *const T, param0: ?*RECT) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).Unlock(@ptrCast(*const IDirectDrawSurface4, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_UpdateOverlay(self: *const T, param0: ?*RECT, param1: ?*IDirectDrawSurface4, param2: ?*RECT, param3: u32, param4: ?*DDOVERLAYFX) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).UpdateOverlay(@ptrCast(*const IDirectDrawSurface4, self), param0, param1, param2, param3, param4); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_UpdateOverlayDisplay(self: *const T, param0: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).UpdateOverlayDisplay(@ptrCast(*const IDirectDrawSurface4, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_UpdateOverlayZOrder(self: *const T, param0: u32, param1: ?*IDirectDrawSurface4) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).UpdateOverlayZOrder(@ptrCast(*const IDirectDrawSurface4, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_GetDDInterface(self: *const T, param0: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).GetDDInterface(@ptrCast(*const IDirectDrawSurface4, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_PageLock(self: *const T, param0: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).PageLock(@ptrCast(*const IDirectDrawSurface4, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_PageUnlock(self: *const T, param0: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).PageUnlock(@ptrCast(*const IDirectDrawSurface4, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_SetSurfaceDesc(self: *const T, param0: ?*DDSURFACEDESC2, param1: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).SetSurfaceDesc(@ptrCast(*const IDirectDrawSurface4, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_SetPrivateData(self: *const T, param0: ?*const Guid, param1: ?*anyopaque, param2: u32, param3: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).SetPrivateData(@ptrCast(*const IDirectDrawSurface4, self), param0, param1, param2, param3); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_GetPrivateData(self: *const T, param0: ?*const Guid, param1: ?*anyopaque, param2: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).GetPrivateData(@ptrCast(*const IDirectDrawSurface4, self), param0, param1, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_FreePrivateData(self: *const T, param0: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).FreePrivateData(@ptrCast(*const IDirectDrawSurface4, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_GetUniquenessValue(self: *const T, param0: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).GetUniquenessValue(@ptrCast(*const IDirectDrawSurface4, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface4_ChangeUniquenessValue(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface4.VTable, self.vtable).ChangeUniquenessValue(@ptrCast(*const IDirectDrawSurface4, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectDrawSurface7_Value = Guid.initString("06675a80-3b9b-11d2-b92f-00609797ea5b"); pub const IID_IDirectDrawSurface7 = &IID_IDirectDrawSurface7_Value; pub const IDirectDrawSurface7 = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AddAttachedSurface: fn( self: *const IDirectDrawSurface7, param0: ?*IDirectDrawSurface7, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddOverlayDirtyRect: fn( self: *const IDirectDrawSurface7, param0: ?*RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Blt: fn( self: *const IDirectDrawSurface7, param0: ?*RECT, param1: ?*IDirectDrawSurface7, param2: ?*RECT, param3: u32, param4: ?*DDBLTFX, ) callconv(@import("std").os.windows.WINAPI) HRESULT, BltBatch: fn( self: *const IDirectDrawSurface7, param0: ?*DDBLTBATCH, param1: u32, param2: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, BltFast: fn( self: *const IDirectDrawSurface7, param0: u32, param1: u32, param2: ?*IDirectDrawSurface7, param3: ?*RECT, param4: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteAttachedSurface: fn( self: *const IDirectDrawSurface7, param0: u32, param1: ?*IDirectDrawSurface7, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumAttachedSurfaces: fn( self: *const IDirectDrawSurface7, param0: ?*anyopaque, param1: ?LPDDENUMSURFACESCALLBACK7, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumOverlayZOrders: fn( self: *const IDirectDrawSurface7, param0: u32, param1: ?*anyopaque, param2: ?LPDDENUMSURFACESCALLBACK7, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Flip: fn( self: *const IDirectDrawSurface7, param0: ?*IDirectDrawSurface7, param1: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAttachedSurface: fn( self: *const IDirectDrawSurface7, param0: ?*DDSCAPS2, param1: ?*?*IDirectDrawSurface7, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBltStatus: fn( self: *const IDirectDrawSurface7, param0: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCaps: fn( self: *const IDirectDrawSurface7, param0: ?*DDSCAPS2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetClipper: fn( self: *const IDirectDrawSurface7, param0: ?*?*IDirectDrawClipper, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetColorKey: fn( self: *const IDirectDrawSurface7, param0: u32, param1: ?*DDCOLORKEY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDC: fn( self: *const IDirectDrawSurface7, param0: ?*?HDC, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFlipStatus: fn( self: *const IDirectDrawSurface7, param0: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOverlayPosition: fn( self: *const IDirectDrawSurface7, param0: ?*i32, param1: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPalette: fn( self: *const IDirectDrawSurface7, param0: ?*?*IDirectDrawPalette, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPixelFormat: fn( self: *const IDirectDrawSurface7, param0: ?*DDPIXELFORMAT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSurfaceDesc: fn( self: *const IDirectDrawSurface7, param0: ?*DDSURFACEDESC2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Initialize: fn( self: *const IDirectDrawSurface7, param0: ?*IDirectDraw, param1: ?*DDSURFACEDESC2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsLost: fn( self: *const IDirectDrawSurface7, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Lock: fn( self: *const IDirectDrawSurface7, param0: ?*RECT, param1: ?*DDSURFACEDESC2, param2: u32, param3: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ReleaseDC: fn( self: *const IDirectDrawSurface7, param0: ?HDC, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Restore: fn( self: *const IDirectDrawSurface7, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetClipper: fn( self: *const IDirectDrawSurface7, param0: ?*IDirectDrawClipper, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetColorKey: fn( self: *const IDirectDrawSurface7, param0: u32, param1: ?*DDCOLORKEY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetOverlayPosition: fn( self: *const IDirectDrawSurface7, param0: i32, param1: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPalette: fn( self: *const IDirectDrawSurface7, param0: ?*IDirectDrawPalette, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Unlock: fn( self: *const IDirectDrawSurface7, param0: ?*RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpdateOverlay: fn( self: *const IDirectDrawSurface7, param0: ?*RECT, param1: ?*IDirectDrawSurface7, param2: ?*RECT, param3: u32, param4: ?*DDOVERLAYFX, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpdateOverlayDisplay: fn( self: *const IDirectDrawSurface7, param0: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpdateOverlayZOrder: fn( self: *const IDirectDrawSurface7, param0: u32, param1: ?*IDirectDrawSurface7, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDDInterface: fn( self: *const IDirectDrawSurface7, param0: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PageLock: fn( self: *const IDirectDrawSurface7, param0: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PageUnlock: fn( self: *const IDirectDrawSurface7, param0: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSurfaceDesc: fn( self: *const IDirectDrawSurface7, param0: ?*DDSURFACEDESC2, param1: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPrivateData: fn( self: *const IDirectDrawSurface7, param0: ?*const Guid, param1: ?*anyopaque, param2: u32, param3: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPrivateData: fn( self: *const IDirectDrawSurface7, param0: ?*const Guid, param1: ?*anyopaque, param2: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FreePrivateData: fn( self: *const IDirectDrawSurface7, param0: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetUniquenessValue: fn( self: *const IDirectDrawSurface7, param0: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ChangeUniquenessValue: fn( self: *const IDirectDrawSurface7, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPriority: fn( self: *const IDirectDrawSurface7, param0: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPriority: fn( self: *const IDirectDrawSurface7, param0: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetLOD: fn( self: *const IDirectDrawSurface7, param0: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLOD: fn( self: *const IDirectDrawSurface7, param0: ?*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 IDirectDrawSurface7_AddAttachedSurface(self: *const T, param0: ?*IDirectDrawSurface7) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).AddAttachedSurface(@ptrCast(*const IDirectDrawSurface7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_AddOverlayDirtyRect(self: *const T, param0: ?*RECT) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).AddOverlayDirtyRect(@ptrCast(*const IDirectDrawSurface7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_Blt(self: *const T, param0: ?*RECT, param1: ?*IDirectDrawSurface7, param2: ?*RECT, param3: u32, param4: ?*DDBLTFX) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).Blt(@ptrCast(*const IDirectDrawSurface7, self), param0, param1, param2, param3, param4); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_BltBatch(self: *const T, param0: ?*DDBLTBATCH, param1: u32, param2: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).BltBatch(@ptrCast(*const IDirectDrawSurface7, self), param0, param1, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_BltFast(self: *const T, param0: u32, param1: u32, param2: ?*IDirectDrawSurface7, param3: ?*RECT, param4: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).BltFast(@ptrCast(*const IDirectDrawSurface7, self), param0, param1, param2, param3, param4); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_DeleteAttachedSurface(self: *const T, param0: u32, param1: ?*IDirectDrawSurface7) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).DeleteAttachedSurface(@ptrCast(*const IDirectDrawSurface7, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_EnumAttachedSurfaces(self: *const T, param0: ?*anyopaque, param1: ?LPDDENUMSURFACESCALLBACK7) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).EnumAttachedSurfaces(@ptrCast(*const IDirectDrawSurface7, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_EnumOverlayZOrders(self: *const T, param0: u32, param1: ?*anyopaque, param2: ?LPDDENUMSURFACESCALLBACK7) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).EnumOverlayZOrders(@ptrCast(*const IDirectDrawSurface7, self), param0, param1, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_Flip(self: *const T, param0: ?*IDirectDrawSurface7, param1: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).Flip(@ptrCast(*const IDirectDrawSurface7, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_GetAttachedSurface(self: *const T, param0: ?*DDSCAPS2, param1: ?*?*IDirectDrawSurface7) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).GetAttachedSurface(@ptrCast(*const IDirectDrawSurface7, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_GetBltStatus(self: *const T, param0: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).GetBltStatus(@ptrCast(*const IDirectDrawSurface7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_GetCaps(self: *const T, param0: ?*DDSCAPS2) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).GetCaps(@ptrCast(*const IDirectDrawSurface7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_GetClipper(self: *const T, param0: ?*?*IDirectDrawClipper) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).GetClipper(@ptrCast(*const IDirectDrawSurface7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_GetColorKey(self: *const T, param0: u32, param1: ?*DDCOLORKEY) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).GetColorKey(@ptrCast(*const IDirectDrawSurface7, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_GetDC(self: *const T, param0: ?*?HDC) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).GetDC(@ptrCast(*const IDirectDrawSurface7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_GetFlipStatus(self: *const T, param0: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).GetFlipStatus(@ptrCast(*const IDirectDrawSurface7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_GetOverlayPosition(self: *const T, param0: ?*i32, param1: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).GetOverlayPosition(@ptrCast(*const IDirectDrawSurface7, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_GetPalette(self: *const T, param0: ?*?*IDirectDrawPalette) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).GetPalette(@ptrCast(*const IDirectDrawSurface7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_GetPixelFormat(self: *const T, param0: ?*DDPIXELFORMAT) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).GetPixelFormat(@ptrCast(*const IDirectDrawSurface7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_GetSurfaceDesc(self: *const T, param0: ?*DDSURFACEDESC2) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).GetSurfaceDesc(@ptrCast(*const IDirectDrawSurface7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_Initialize(self: *const T, param0: ?*IDirectDraw, param1: ?*DDSURFACEDESC2) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).Initialize(@ptrCast(*const IDirectDrawSurface7, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_IsLost(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).IsLost(@ptrCast(*const IDirectDrawSurface7, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_Lock(self: *const T, param0: ?*RECT, param1: ?*DDSURFACEDESC2, param2: u32, param3: ?HANDLE) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).Lock(@ptrCast(*const IDirectDrawSurface7, self), param0, param1, param2, param3); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_ReleaseDC(self: *const T, param0: ?HDC) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).ReleaseDC(@ptrCast(*const IDirectDrawSurface7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_Restore(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).Restore(@ptrCast(*const IDirectDrawSurface7, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_SetClipper(self: *const T, param0: ?*IDirectDrawClipper) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).SetClipper(@ptrCast(*const IDirectDrawSurface7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_SetColorKey(self: *const T, param0: u32, param1: ?*DDCOLORKEY) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).SetColorKey(@ptrCast(*const IDirectDrawSurface7, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_SetOverlayPosition(self: *const T, param0: i32, param1: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).SetOverlayPosition(@ptrCast(*const IDirectDrawSurface7, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_SetPalette(self: *const T, param0: ?*IDirectDrawPalette) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).SetPalette(@ptrCast(*const IDirectDrawSurface7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_Unlock(self: *const T, param0: ?*RECT) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).Unlock(@ptrCast(*const IDirectDrawSurface7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_UpdateOverlay(self: *const T, param0: ?*RECT, param1: ?*IDirectDrawSurface7, param2: ?*RECT, param3: u32, param4: ?*DDOVERLAYFX) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).UpdateOverlay(@ptrCast(*const IDirectDrawSurface7, self), param0, param1, param2, param3, param4); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_UpdateOverlayDisplay(self: *const T, param0: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).UpdateOverlayDisplay(@ptrCast(*const IDirectDrawSurface7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_UpdateOverlayZOrder(self: *const T, param0: u32, param1: ?*IDirectDrawSurface7) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).UpdateOverlayZOrder(@ptrCast(*const IDirectDrawSurface7, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_GetDDInterface(self: *const T, param0: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).GetDDInterface(@ptrCast(*const IDirectDrawSurface7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_PageLock(self: *const T, param0: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).PageLock(@ptrCast(*const IDirectDrawSurface7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_PageUnlock(self: *const T, param0: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).PageUnlock(@ptrCast(*const IDirectDrawSurface7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_SetSurfaceDesc(self: *const T, param0: ?*DDSURFACEDESC2, param1: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).SetSurfaceDesc(@ptrCast(*const IDirectDrawSurface7, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_SetPrivateData(self: *const T, param0: ?*const Guid, param1: ?*anyopaque, param2: u32, param3: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).SetPrivateData(@ptrCast(*const IDirectDrawSurface7, self), param0, param1, param2, param3); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_GetPrivateData(self: *const T, param0: ?*const Guid, param1: ?*anyopaque, param2: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).GetPrivateData(@ptrCast(*const IDirectDrawSurface7, self), param0, param1, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_FreePrivateData(self: *const T, param0: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).FreePrivateData(@ptrCast(*const IDirectDrawSurface7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_GetUniquenessValue(self: *const T, param0: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).GetUniquenessValue(@ptrCast(*const IDirectDrawSurface7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_ChangeUniquenessValue(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).ChangeUniquenessValue(@ptrCast(*const IDirectDrawSurface7, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_SetPriority(self: *const T, param0: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).SetPriority(@ptrCast(*const IDirectDrawSurface7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_GetPriority(self: *const T, param0: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).GetPriority(@ptrCast(*const IDirectDrawSurface7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_SetLOD(self: *const T, param0: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).SetLOD(@ptrCast(*const IDirectDrawSurface7, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurface7_GetLOD(self: *const T, param0: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurface7.VTable, self.vtable).GetLOD(@ptrCast(*const IDirectDrawSurface7, self), param0); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectDrawColorControl_Value = Guid.initString("4b9f0ee0-0d7e-11d0-9b06-00a0c903a3b8"); pub const IID_IDirectDrawColorControl = &IID_IDirectDrawColorControl_Value; pub const IDirectDrawColorControl = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetColorControls: fn( self: *const IDirectDrawColorControl, param0: ?*DDCOLORCONTROL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetColorControls: fn( self: *const IDirectDrawColorControl, param0: ?*DDCOLORCONTROL, ) 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 IDirectDrawColorControl_GetColorControls(self: *const T, param0: ?*DDCOLORCONTROL) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawColorControl.VTable, self.vtable).GetColorControls(@ptrCast(*const IDirectDrawColorControl, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawColorControl_SetColorControls(self: *const T, param0: ?*DDCOLORCONTROL) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawColorControl.VTable, self.vtable).SetColorControls(@ptrCast(*const IDirectDrawColorControl, self), param0); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectDrawGammaControl_Value = Guid.initString("69c11c3e-b46b-11d1-ad7a-00c04fc29b4e"); pub const IID_IDirectDrawGammaControl = &IID_IDirectDrawGammaControl_Value; pub const IDirectDrawGammaControl = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetGammaRamp: fn( self: *const IDirectDrawGammaControl, param0: u32, param1: ?*DDGAMMARAMP, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetGammaRamp: fn( self: *const IDirectDrawGammaControl, param0: u32, param1: ?*DDGAMMARAMP, ) 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 IDirectDrawGammaControl_GetGammaRamp(self: *const T, param0: u32, param1: ?*DDGAMMARAMP) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawGammaControl.VTable, self.vtable).GetGammaRamp(@ptrCast(*const IDirectDrawGammaControl, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawGammaControl_SetGammaRamp(self: *const T, param0: u32, param1: ?*DDGAMMARAMP) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawGammaControl.VTable, self.vtable).SetGammaRamp(@ptrCast(*const IDirectDrawGammaControl, self), param0, param1); } };} pub usingnamespace MethodMixin(@This()); }; pub const DDSURFACEDESC = extern struct { dwSize: u32, dwFlags: u32, dwHeight: u32, dwWidth: u32, Anonymous1: extern union { lPitch: i32, dwLinearSize: u32, }, dwBackBufferCount: u32, Anonymous2: extern union { dwMipMapCount: u32, dwZBufferBitDepth: u32, dwRefreshRate: u32, }, dwAlphaBitDepth: u32, dwReserved: u32, lpSurface: ?*anyopaque, ddckCKDestOverlay: DDCOLORKEY, ddckCKDestBlt: DDCOLORKEY, ddckCKSrcOverlay: DDCOLORKEY, ddckCKSrcBlt: DDCOLORKEY, ddpfPixelFormat: DDPIXELFORMAT, ddsCaps: DDSCAPS, }; pub const DDSURFACEDESC2 = extern struct { dwSize: u32, dwFlags: u32, dwHeight: u32, dwWidth: u32, Anonymous1: extern union { lPitch: i32, dwLinearSize: u32, }, Anonymous2: extern union { dwBackBufferCount: u32, dwDepth: u32, }, Anonymous3: extern union { dwMipMapCount: u32, dwRefreshRate: u32, dwSrcVBHandle: u32, }, dwAlphaBitDepth: u32, dwReserved: u32, lpSurface: ?*anyopaque, Anonymous4: extern union { ddckCKDestOverlay: DDCOLORKEY, dwEmptyFaceColor: u32, }, ddckCKDestBlt: DDCOLORKEY, ddckCKSrcOverlay: DDCOLORKEY, ddckCKSrcBlt: DDCOLORKEY, Anonymous5: extern union { ddpfPixelFormat: DDPIXELFORMAT, dwFVF: u32, }, ddsCaps: DDSCAPS2, dwTextureStage: u32, }; pub const DDOPTSURFACEDESC = extern struct { dwSize: u32, dwFlags: u32, ddSCaps: DDSCAPS2, ddOSCaps: DDOSCAPS, guid: Guid, dwCompressionRatio: u32, }; pub const DDCOLORCONTROL = extern struct { dwSize: u32, dwFlags: u32, lBrightness: i32, lContrast: i32, lHue: i32, lSaturation: i32, lSharpness: i32, lGamma: i32, lColorEnable: i32, dwReserved1: u32, }; pub const IDDVideoPortContainerVtbl = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const IDirectDrawVideoPortVtbl = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const IDirectDrawVideoPortNotifyVtbl = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const LPDDENUMVIDEOCALLBACK = fn( param0: ?*DDVIDEOPORTCAPS, param1: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; const IID_IDDVideoPortContainer_Value = Guid.initString("6c142760-a733-11ce-a521-0020af0be560"); pub const IID_IDDVideoPortContainer = &IID_IDDVideoPortContainer_Value; pub const IDDVideoPortContainer = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CreateVideoPort: fn( self: *const IDDVideoPortContainer, param0: u32, param1: ?*DDVIDEOPORTDESC, param2: ?*?*IDirectDrawVideoPort, param3: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumVideoPorts: fn( self: *const IDDVideoPortContainer, param0: u32, param1: ?*DDVIDEOPORTCAPS, param2: ?*anyopaque, param3: ?LPDDENUMVIDEOCALLBACK, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetVideoPortConnectInfo: fn( self: *const IDDVideoPortContainer, param0: u32, pcInfo: ?*u32, param2: ?[*]DDVIDEOPORTCONNECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryVideoPortStatus: fn( self: *const IDDVideoPortContainer, param0: u32, param1: ?*DDVIDEOPORTSTATUS, ) 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 IDDVideoPortContainer_CreateVideoPort(self: *const T, param0: u32, param1: ?*DDVIDEOPORTDESC, param2: ?*?*IDirectDrawVideoPort, param3: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IDDVideoPortContainer.VTable, self.vtable).CreateVideoPort(@ptrCast(*const IDDVideoPortContainer, self), param0, param1, param2, param3); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDDVideoPortContainer_EnumVideoPorts(self: *const T, param0: u32, param1: ?*DDVIDEOPORTCAPS, param2: ?*anyopaque, param3: ?LPDDENUMVIDEOCALLBACK) callconv(.Inline) HRESULT { return @ptrCast(*const IDDVideoPortContainer.VTable, self.vtable).EnumVideoPorts(@ptrCast(*const IDDVideoPortContainer, self), param0, param1, param2, param3); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDDVideoPortContainer_GetVideoPortConnectInfo(self: *const T, param0: u32, pcInfo: ?*u32, param2: ?[*]DDVIDEOPORTCONNECT) callconv(.Inline) HRESULT { return @ptrCast(*const IDDVideoPortContainer.VTable, self.vtable).GetVideoPortConnectInfo(@ptrCast(*const IDDVideoPortContainer, self), param0, pcInfo, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDDVideoPortContainer_QueryVideoPortStatus(self: *const T, param0: u32, param1: ?*DDVIDEOPORTSTATUS) callconv(.Inline) HRESULT { return @ptrCast(*const IDDVideoPortContainer.VTable, self.vtable).QueryVideoPortStatus(@ptrCast(*const IDDVideoPortContainer, self), param0, param1); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectDrawVideoPort_Value = Guid.initString("b36d93e0-2b43-11cf-a2de-00aa00b93356"); pub const IID_IDirectDrawVideoPort = &IID_IDirectDrawVideoPort_Value; pub const IDirectDrawVideoPort = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Flip: fn( self: *const IDirectDrawVideoPort, param0: ?*IDirectDrawSurface, param1: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBandwidthInfo: fn( self: *const IDirectDrawVideoPort, param0: ?*DDPIXELFORMAT, param1: u32, param2: u32, param3: u32, param4: ?*DDVIDEOPORTBANDWIDTH, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetColorControls: fn( self: *const IDirectDrawVideoPort, param0: ?*DDCOLORCONTROL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetInputFormats: fn( self: *const IDirectDrawVideoPort, lpNumFormats: ?*u32, param1: ?[*]DDPIXELFORMAT, param2: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOutputFormats: fn( self: *const IDirectDrawVideoPort, param0: ?*DDPIXELFORMAT, lpNumFormats: ?*u32, param2: ?[*]DDPIXELFORMAT, param3: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFieldPolarity: fn( self: *const IDirectDrawVideoPort, param0: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetVideoLine: fn( self: *const IDirectDrawVideoPort, param0: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetVideoSignalStatus: fn( self: *const IDirectDrawVideoPort, param0: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetColorControls: fn( self: *const IDirectDrawVideoPort, param0: ?*DDCOLORCONTROL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetTargetSurface: fn( self: *const IDirectDrawVideoPort, param0: ?*IDirectDrawSurface, param1: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, StartVideo: fn( self: *const IDirectDrawVideoPort, param0: ?*DDVIDEOPORTINFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT, StopVideo: fn( self: *const IDirectDrawVideoPort, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpdateVideo: fn( self: *const IDirectDrawVideoPort, param0: ?*DDVIDEOPORTINFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WaitForSync: fn( self: *const IDirectDrawVideoPort, param0: u32, param1: u32, param2: 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 IDirectDrawVideoPort_Flip(self: *const T, param0: ?*IDirectDrawSurface, param1: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawVideoPort.VTable, self.vtable).Flip(@ptrCast(*const IDirectDrawVideoPort, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawVideoPort_GetBandwidthInfo(self: *const T, param0: ?*DDPIXELFORMAT, param1: u32, param2: u32, param3: u32, param4: ?*DDVIDEOPORTBANDWIDTH) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawVideoPort.VTable, self.vtable).GetBandwidthInfo(@ptrCast(*const IDirectDrawVideoPort, self), param0, param1, param2, param3, param4); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawVideoPort_GetColorControls(self: *const T, param0: ?*DDCOLORCONTROL) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawVideoPort.VTable, self.vtable).GetColorControls(@ptrCast(*const IDirectDrawVideoPort, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawVideoPort_GetInputFormats(self: *const T, lpNumFormats: ?*u32, param1: ?[*]DDPIXELFORMAT, param2: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawVideoPort.VTable, self.vtable).GetInputFormats(@ptrCast(*const IDirectDrawVideoPort, self), lpNumFormats, param1, param2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawVideoPort_GetOutputFormats(self: *const T, param0: ?*DDPIXELFORMAT, lpNumFormats: ?*u32, param2: ?[*]DDPIXELFORMAT, param3: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawVideoPort.VTable, self.vtable).GetOutputFormats(@ptrCast(*const IDirectDrawVideoPort, self), param0, lpNumFormats, param2, param3); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawVideoPort_GetFieldPolarity(self: *const T, param0: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawVideoPort.VTable, self.vtable).GetFieldPolarity(@ptrCast(*const IDirectDrawVideoPort, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawVideoPort_GetVideoLine(self: *const T, param0: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawVideoPort.VTable, self.vtable).GetVideoLine(@ptrCast(*const IDirectDrawVideoPort, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawVideoPort_GetVideoSignalStatus(self: *const T, param0: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawVideoPort.VTable, self.vtable).GetVideoSignalStatus(@ptrCast(*const IDirectDrawVideoPort, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawVideoPort_SetColorControls(self: *const T, param0: ?*DDCOLORCONTROL) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawVideoPort.VTable, self.vtable).SetColorControls(@ptrCast(*const IDirectDrawVideoPort, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawVideoPort_SetTargetSurface(self: *const T, param0: ?*IDirectDrawSurface, param1: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawVideoPort.VTable, self.vtable).SetTargetSurface(@ptrCast(*const IDirectDrawVideoPort, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawVideoPort_StartVideo(self: *const T, param0: ?*DDVIDEOPORTINFO) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawVideoPort.VTable, self.vtable).StartVideo(@ptrCast(*const IDirectDrawVideoPort, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawVideoPort_StopVideo(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawVideoPort.VTable, self.vtable).StopVideo(@ptrCast(*const IDirectDrawVideoPort, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawVideoPort_UpdateVideo(self: *const T, param0: ?*DDVIDEOPORTINFO) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawVideoPort.VTable, self.vtable).UpdateVideo(@ptrCast(*const IDirectDrawVideoPort, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawVideoPort_WaitForSync(self: *const T, param0: u32, param1: u32, param2: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawVideoPort.VTable, self.vtable).WaitForSync(@ptrCast(*const IDirectDrawVideoPort, self), param0, param1, param2); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectDrawVideoPortNotify_Value = Guid.initString("a655fb94-0589-4e57-b333-567a89468c88"); pub const IID_IDirectDrawVideoPortNotify = &IID_IDirectDrawVideoPortNotify_Value; pub const IDirectDrawVideoPortNotify = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AcquireNotification: fn( self: *const IDirectDrawVideoPortNotify, param0: ?*?HANDLE, param1: ?*DDVIDEOPORTNOTIFY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ReleaseNotification: fn( self: *const IDirectDrawVideoPortNotify, param0: ?HANDLE, ) 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 IDirectDrawVideoPortNotify_AcquireNotification(self: *const T, param0: ?*?HANDLE, param1: ?*DDVIDEOPORTNOTIFY) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawVideoPortNotify.VTable, self.vtable).AcquireNotification(@ptrCast(*const IDirectDrawVideoPortNotify, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawVideoPortNotify_ReleaseNotification(self: *const T, param0: ?HANDLE) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawVideoPortNotify.VTable, self.vtable).ReleaseNotification(@ptrCast(*const IDirectDrawVideoPortNotify, self), param0); } };} pub usingnamespace MethodMixin(@This()); }; pub const DDVIDEOPORTCONNECT = extern struct { dwSize: u32, dwPortWidth: u32, guidTypeID: Guid, dwFlags: u32, dwReserved1: usize, }; pub const DDVIDEOPORTCAPS = extern struct { dwSize: u32, dwFlags: u32, dwMaxWidth: u32, dwMaxVBIWidth: u32, dwMaxHeight: u32, dwVideoPortID: u32, dwCaps: u32, dwFX: u32, dwNumAutoFlipSurfaces: u32, dwAlignVideoPortBoundary: u32, dwAlignVideoPortPrescaleWidth: u32, dwAlignVideoPortCropBoundary: u32, dwAlignVideoPortCropWidth: u32, dwPreshrinkXStep: u32, dwPreshrinkYStep: u32, dwNumVBIAutoFlipSurfaces: u32, dwNumPreferredAutoflip: u32, wNumFilterTapsX: u16, wNumFilterTapsY: u16, }; pub const DDVIDEOPORTDESC = extern struct { dwSize: u32, dwFieldWidth: u32, dwVBIWidth: u32, dwFieldHeight: u32, dwMicrosecondsPerField: u32, dwMaxPixelsPerSecond: u32, dwVideoPortID: u32, dwReserved1: u32, VideoPortType: DDVIDEOPORTCONNECT, dwReserved2: usize, dwReserved3: usize, }; pub const DDVIDEOPORTINFO = extern struct { dwSize: u32, dwOriginX: u32, dwOriginY: u32, dwVPFlags: u32, rCrop: RECT, dwPrescaleWidth: u32, dwPrescaleHeight: u32, lpddpfInputFormat: ?*DDPIXELFORMAT, lpddpfVBIInputFormat: ?*DDPIXELFORMAT, lpddpfVBIOutputFormat: ?*DDPIXELFORMAT, dwVBIHeight: u32, dwReserved1: usize, dwReserved2: usize, }; pub const DDVIDEOPORTBANDWIDTH = extern struct { dwSize: u32, dwCaps: u32, dwOverlay: u32, dwColorkey: u32, dwYInterpolate: u32, dwYInterpAndColorkey: u32, dwReserved1: usize, dwReserved2: usize, }; pub const DDVIDEOPORTSTATUS = extern struct { dwSize: u32, bInUse: BOOL, dwFlags: u32, dwReserved1: u32, VideoPortType: DDVIDEOPORTCONNECT, dwReserved2: usize, dwReserved3: usize, }; pub const DDVIDEOPORTNOTIFY = extern struct { ApproximateTimeStamp: LARGE_INTEGER, lField: i32, dwSurfaceIndex: u32, lDone: i32, }; const IID_IDirectDrawKernel_Value = Guid.initString("8d56c120-6a08-11d0-9b06-00a0c903a3b8"); pub const IID_IDirectDrawKernel = &IID_IDirectDrawKernel_Value; pub const IDirectDrawKernel = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCaps: fn( self: *const IDirectDrawKernel, param0: ?*DDKERNELCAPS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetKernelHandle: fn( self: *const IDirectDrawKernel, param0: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ReleaseKernelHandle: fn( self: *const IDirectDrawKernel, ) 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 IDirectDrawKernel_GetCaps(self: *const T, param0: ?*DDKERNELCAPS) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawKernel.VTable, self.vtable).GetCaps(@ptrCast(*const IDirectDrawKernel, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawKernel_GetKernelHandle(self: *const T, param0: ?*usize) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawKernel.VTable, self.vtable).GetKernelHandle(@ptrCast(*const IDirectDrawKernel, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawKernel_ReleaseKernelHandle(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawKernel.VTable, self.vtable).ReleaseKernelHandle(@ptrCast(*const IDirectDrawKernel, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectDrawSurfaceKernel_Value = Guid.initString("60755da0-6a40-11d0-9b06-00a0c903a3b8"); pub const IID_IDirectDrawSurfaceKernel = &IID_IDirectDrawSurfaceKernel_Value; pub const IDirectDrawSurfaceKernel = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetKernelHandle: fn( self: *const IDirectDrawSurfaceKernel, param0: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ReleaseKernelHandle: fn( self: *const IDirectDrawSurfaceKernel, ) 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 IDirectDrawSurfaceKernel_GetKernelHandle(self: *const T, param0: ?*usize) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurfaceKernel.VTable, self.vtable).GetKernelHandle(@ptrCast(*const IDirectDrawSurfaceKernel, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectDrawSurfaceKernel_ReleaseKernelHandle(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectDrawSurfaceKernel.VTable, self.vtable).ReleaseKernelHandle(@ptrCast(*const IDirectDrawSurfaceKernel, self)); } };} pub usingnamespace MethodMixin(@This()); }; pub const DDKERNELCAPS = extern struct { dwSize: u32, dwCaps: u32, dwIRQCaps: u32, }; pub const SURFACEALIGNMENT = extern struct { Anonymous: extern union { Linear: extern struct { dwStartAlignment: u32, dwPitchAlignment: u32, dwFlags: u32, dwReserved2: u32, }, Rectangular: extern struct { dwXAlignment: u32, dwYAlignment: u32, dwFlags: u32, dwReserved2: u32, }, }, }; pub const HEAPALIGNMENT = extern struct { dwSize: u32, ddsCaps: DDSCAPS, dwReserved: u32, ExecuteBuffer: SURFACEALIGNMENT, Overlay: SURFACEALIGNMENT, Texture: SURFACEALIGNMENT, ZBuffer: SURFACEALIGNMENT, AlphaBuffer: SURFACEALIGNMENT, Offscreen: SURFACEALIGNMENT, FlipTarget: SURFACEALIGNMENT, }; pub const DD_GETHEAPALIGNMENTDATA = extern struct { dwInstance: usize, dwHeap: u32, ddRVal: HRESULT, GetHeapAlignment: ?*anyopaque, Alignment: HEAPALIGNMENT, }; pub const VMEML = extern struct { next: ?*VMEML, ptr: usize, size: u32, bDiscardable: BOOL, }; pub const VMEMR = extern struct { next: ?*VMEMR, prev: ?*VMEMR, pUp: ?*VMEMR, pDown: ?*VMEMR, pLeft: ?*VMEMR, pRight: ?*VMEMR, ptr: usize, size: u32, x: u32, y: u32, cx: u32, cy: u32, flags: u32, pBits: usize, bDiscardable: BOOL, }; pub const VMEMHEAP = extern struct { dwFlags: u32, stride: u32, freeList: ?*anyopaque, allocList: ?*anyopaque, dwTotalSize: u32, fpGARTLin: usize, fpGARTDev: usize, dwCommitedSize: u32, dwCoalesceCount: u32, Alignment: HEAPALIGNMENT, ddsCapsEx: DDSCAPSEX, ddsCapsExAlt: DDSCAPSEX, liPhysAGPBase: LARGE_INTEGER, hdevAGP: ?HANDLE, pvPhysRsrv: ?*anyopaque, pAgpCommitMask: ?*u8, dwAgpCommitMaskSize: u32, }; pub const PROCESS_LIST = extern struct { lpLink: ?*PROCESS_LIST, dwProcessId: u32, dwRefCnt: u32, dwAlphaDepth: u32, dwZDepth: u32, }; pub const DDMONITORINFO = extern struct { Manufacturer: u16, Product: u16, SerialNumber: u32, DeviceIdentifier: Guid, Mode640x480: i32, Mode800x600: i32, Mode1024x768: i32, Mode1280x1024: i32, Mode1600x1200: i32, ModeReserved1: i32, ModeReserved2: i32, ModeReserved3: i32, }; pub const IDirectDrawClipperVtbl = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const IDirectDrawPaletteVtbl = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const IDirectDrawSurfaceVtbl = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const IDirectDrawSurface2Vtbl = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const IDirectDrawSurface3Vtbl = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const IDirectDrawSurface4Vtbl = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const IDirectDrawSurface7Vtbl = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const IDirectDrawColorControlVtbl = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const IDirectDrawVtbl = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const IDirectDraw2Vtbl = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const IDirectDraw4Vtbl = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const IDirectDraw7Vtbl = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const IDirectDrawKernelVtbl = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const IDirectDrawSurfaceKernelVtbl = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const IDirectDrawGammaControlVtbl = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const DD32BITDRIVERDATA = extern struct { szName: [260]CHAR, szEntryPoint: [64]CHAR, dwContext: u32, }; pub const DDVERSIONDATA = extern struct { dwHALVersion: u32, dwReserved1: usize, dwReserved2: usize, }; pub const LPDD32BITDRIVERINIT = fn( dwContext: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub const VIDMEM = extern struct { dwFlags: u32, fpStart: usize, Anonymous1: extern union { fpEnd: usize, dwWidth: u32, }, ddsCaps: DDSCAPS, ddsCapsAlt: DDSCAPS, Anonymous2: extern union { lpHeap: ?*VMEMHEAP, dwHeight: u32, }, }; pub const VIDMEMINFO = extern struct { fpPrimary: usize, dwFlags: u32, dwDisplayWidth: u32, dwDisplayHeight: u32, lDisplayPitch: i32, ddpfDisplay: DDPIXELFORMAT, dwOffscreenAlign: u32, dwOverlayAlign: u32, dwTextureAlign: u32, dwZBufferAlign: u32, dwAlphaAlign: u32, dwNumHeaps: u32, pvmList: ?*VIDMEM, }; pub const HEAPALIAS = extern struct { fpVidMem: usize, lpAlias: ?*anyopaque, dwAliasSize: u32, }; pub const HEAPALIASINFO = extern struct { dwRefCnt: u32, dwFlags: u32, dwNumHeaps: u32, lpAliases: ?*HEAPALIAS, }; pub const IUNKNOWN_LIST = extern struct { lpLink: ?*IUNKNOWN_LIST, lpGuid: ?*Guid, lpIUnknown: ?*IUnknown, }; pub const LPDDHEL_INIT = fn( param0: ?*DDRAWI_DIRECTDRAW_GBL, param1: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const LPDDHAL_SETCOLORKEY = fn( param0: ?*DDHAL_DRVSETCOLORKEYDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHAL_CANCREATESURFACE = fn( param0: ?*DDHAL_CANCREATESURFACEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this function pointer causes dependency loop problems, so it's stubbed out pub const LPDDHAL_WAITFORVERTICALBLANK = fn() callconv(@import("std").os.windows.WINAPI) void; pub const LPDDHAL_CREATESURFACE = fn( param0: ?*DDHAL_CREATESURFACEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHAL_DESTROYDRIVER = fn( param0: ?*DDHAL_DESTROYDRIVERDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHAL_SETMODE = fn( param0: ?*DDHAL_SETMODEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHAL_CREATEPALETTE = fn( param0: ?*DDHAL_CREATEPALETTEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHAL_GETSCANLINE = fn( param0: ?*DDHAL_GETSCANLINEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHAL_SETEXCLUSIVEMODE = fn( param0: ?*DDHAL_SETEXCLUSIVEMODEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHAL_FLIPTOGDISURFACE = fn( param0: ?*DDHAL_FLIPTOGDISURFACEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHAL_GETDRIVERINFO = fn( param0: ?*DDHAL_GETDRIVERINFODATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DDHAL_DDCALLBACKS = extern struct { dwSize: u32, dwFlags: u32, DestroyDriver: ?LPDDHAL_DESTROYDRIVER, CreateSurface: ?LPDDHAL_CREATESURFACE, SetColorKey: ?LPDDHAL_SETCOLORKEY, SetMode: ?LPDDHAL_SETMODE, WaitForVerticalBlank: ?LPDDHAL_WAITFORVERTICALBLANK, CanCreateSurface: ?LPDDHAL_CANCREATESURFACE, CreatePalette: ?LPDDHAL_CREATEPALETTE, GetScanLine: ?LPDDHAL_GETSCANLINE, SetExclusiveMode: ?LPDDHAL_SETEXCLUSIVEMODE, FlipToGDISurface: ?LPDDHAL_FLIPTOGDISURFACE, }; pub const LPDDHALPALCB_DESTROYPALETTE = fn( param0: ?*DDHAL_DESTROYPALETTEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALPALCB_SETENTRIES = fn( param0: ?*DDHAL_SETENTRIESDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DDHAL_DDPALETTECALLBACKS = extern struct { dwSize: u32, dwFlags: u32, DestroyPalette: ?LPDDHALPALCB_DESTROYPALETTE, SetEntries: ?LPDDHALPALCB_SETENTRIES, }; pub const LPDDHALSURFCB_LOCK = fn( param0: ?*DDHAL_LOCKDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALSURFCB_UNLOCK = fn( param0: ?*DDHAL_UNLOCKDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALSURFCB_BLT = fn( param0: ?*DDHAL_BLTDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALSURFCB_UPDATEOVERLAY = fn( param0: ?*DDHAL_UPDATEOVERLAYDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALSURFCB_SETOVERLAYPOSITION = fn( param0: ?*DDHAL_SETOVERLAYPOSITIONDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALSURFCB_SETPALETTE = fn( param0: ?*DDHAL_SETPALETTEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALSURFCB_FLIP = fn( param0: ?*DDHAL_FLIPDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALSURFCB_DESTROYSURFACE = fn( param0: ?*DDHAL_DESTROYSURFACEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALSURFCB_SETCLIPLIST = fn( param0: ?*DDHAL_SETCLIPLISTDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALSURFCB_ADDATTACHEDSURFACE = fn( param0: ?*DDHAL_ADDATTACHEDSURFACEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALSURFCB_SETCOLORKEY = fn( param0: ?*DDHAL_SETCOLORKEYDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALSURFCB_GETBLTSTATUS = fn( param0: ?*DDHAL_GETBLTSTATUSDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALSURFCB_GETFLIPSTATUS = fn( param0: ?*DDHAL_GETFLIPSTATUSDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DDHAL_DDSURFACECALLBACKS = extern struct { dwSize: u32, dwFlags: u32, DestroySurface: ?LPDDHALSURFCB_DESTROYSURFACE, Flip: ?LPDDHALSURFCB_FLIP, SetClipList: ?LPDDHALSURFCB_SETCLIPLIST, Lock: ?LPDDHALSURFCB_LOCK, Unlock: ?LPDDHALSURFCB_UNLOCK, Blt: ?LPDDHALSURFCB_BLT, SetColorKey: ?LPDDHALSURFCB_SETCOLORKEY, AddAttachedSurface: ?LPDDHALSURFCB_ADDATTACHEDSURFACE, GetBltStatus: ?LPDDHALSURFCB_GETBLTSTATUS, GetFlipStatus: ?LPDDHALSURFCB_GETFLIPSTATUS, UpdateOverlay: ?LPDDHALSURFCB_UPDATEOVERLAY, SetOverlayPosition: ?LPDDHALSURFCB_SETOVERLAYPOSITION, reserved4: ?*anyopaque, SetPalette: ?LPDDHALSURFCB_SETPALETTE, }; pub const LPDDHAL_GETAVAILDRIVERMEMORY = fn( param0: ?*DDHAL_GETAVAILDRIVERMEMORYDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHAL_UPDATENONLOCALHEAP = fn( param0: ?*DDHAL_UPDATENONLOCALHEAPDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHAL_GETHEAPALIGNMENT = fn( param0: ?*DDHAL_GETHEAPALIGNMENTDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DDHAL_DDMISCELLANEOUSCALLBACKS = extern struct { dwSize: u32, dwFlags: u32, GetAvailDriverMemory: ?LPDDHAL_GETAVAILDRIVERMEMORY, UpdateNonLocalHeap: ?LPDDHAL_UPDATENONLOCALHEAP, GetHeapAlignment: ?LPDDHAL_GETHEAPALIGNMENT, GetSysmemBltStatus: ?LPDDHALSURFCB_GETBLTSTATUS, }; pub const LPDDHAL_CREATESURFACEEX = fn( param0: ?*DDHAL_CREATESURFACEEXDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHAL_GETDRIVERSTATE = fn( param0: ?*DDHAL_GETDRIVERSTATEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHAL_DESTROYDDLOCAL = fn( param0: ?*DDHAL_DESTROYDDLOCALDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DDHAL_DDMISCELLANEOUS2CALLBACKS = extern struct { dwSize: u32, dwFlags: u32, Reserved: ?*anyopaque, CreateSurfaceEx: ?LPDDHAL_CREATESURFACEEX, GetDriverState: ?LPDDHAL_GETDRIVERSTATE, DestroyDDLocal: ?LPDDHAL_DESTROYDDLOCAL, }; pub const LPDDHALEXEBUFCB_CANCREATEEXEBUF = fn( param0: ?*DDHAL_CANCREATESURFACEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALEXEBUFCB_CREATEEXEBUF = fn( param0: ?*DDHAL_CREATESURFACEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALEXEBUFCB_DESTROYEXEBUF = fn( param0: ?*DDHAL_DESTROYSURFACEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALEXEBUFCB_LOCKEXEBUF = fn( param0: ?*DDHAL_LOCKDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALEXEBUFCB_UNLOCKEXEBUF = fn( param0: ?*DDHAL_UNLOCKDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DDHAL_DDEXEBUFCALLBACKS = extern struct { dwSize: u32, dwFlags: u32, CanCreateExecuteBuffer: ?LPDDHALEXEBUFCB_CANCREATEEXEBUF, CreateExecuteBuffer: ?LPDDHALEXEBUFCB_CREATEEXEBUF, DestroyExecuteBuffer: ?LPDDHALEXEBUFCB_DESTROYEXEBUF, LockExecuteBuffer: ?LPDDHALEXEBUFCB_LOCKEXEBUF, UnlockExecuteBuffer: ?LPDDHALEXEBUFCB_UNLOCKEXEBUF, }; pub const LPDDHALVPORTCB_CANCREATEVIDEOPORT = fn( param0: ?*DDHAL_CANCREATEVPORTDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALVPORTCB_CREATEVIDEOPORT = fn( param0: ?*DDHAL_CREATEVPORTDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALVPORTCB_FLIP = fn( param0: ?*DDHAL_FLIPVPORTDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALVPORTCB_GETBANDWIDTH = fn( param0: ?*DDHAL_GETVPORTBANDWIDTHDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALVPORTCB_GETINPUTFORMATS = fn( param0: ?*DDHAL_GETVPORTINPUTFORMATDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALVPORTCB_GETOUTPUTFORMATS = fn( param0: ?*DDHAL_GETVPORTOUTPUTFORMATDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALVPORTCB_GETFIELD = fn( param0: ?*DDHAL_GETVPORTFIELDDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALVPORTCB_GETLINE = fn( param0: ?*DDHAL_GETVPORTLINEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALVPORTCB_GETVPORTCONNECT = fn( param0: ?*DDHAL_GETVPORTCONNECTDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALVPORTCB_DESTROYVPORT = fn( param0: ?*DDHAL_DESTROYVPORTDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALVPORTCB_GETFLIPSTATUS = fn( param0: ?*DDHAL_GETVPORTFLIPSTATUSDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALVPORTCB_UPDATE = fn( param0: ?*DDHAL_UPDATEVPORTDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALVPORTCB_WAITFORSYNC = fn( param0: ?*DDHAL_WAITFORVPORTSYNCDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALVPORTCB_GETSIGNALSTATUS = fn( param0: ?*DDHAL_GETVPORTSIGNALDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALVPORTCB_COLORCONTROL = fn( param0: ?*DDHAL_VPORTCOLORDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DDHAL_DDVIDEOPORTCALLBACKS = extern struct { dwSize: u32, dwFlags: u32, CanCreateVideoPort: ?LPDDHALVPORTCB_CANCREATEVIDEOPORT, CreateVideoPort: ?LPDDHALVPORTCB_CREATEVIDEOPORT, FlipVideoPort: ?LPDDHALVPORTCB_FLIP, GetVideoPortBandwidth: ?LPDDHALVPORTCB_GETBANDWIDTH, GetVideoPortInputFormats: ?LPDDHALVPORTCB_GETINPUTFORMATS, GetVideoPortOutputFormats: ?LPDDHALVPORTCB_GETOUTPUTFORMATS, lpReserved1: ?*anyopaque, GetVideoPortField: ?LPDDHALVPORTCB_GETFIELD, GetVideoPortLine: ?LPDDHALVPORTCB_GETLINE, GetVideoPortConnectInfo: ?LPDDHALVPORTCB_GETVPORTCONNECT, DestroyVideoPort: ?LPDDHALVPORTCB_DESTROYVPORT, GetVideoPortFlipStatus: ?LPDDHALVPORTCB_GETFLIPSTATUS, UpdateVideoPort: ?LPDDHALVPORTCB_UPDATE, WaitForVideoPortSync: ?LPDDHALVPORTCB_WAITFORSYNC, GetVideoSignalStatus: ?LPDDHALVPORTCB_GETSIGNALSTATUS, ColorControl: ?LPDDHALVPORTCB_COLORCONTROL, }; pub const LPDDHALCOLORCB_COLORCONTROL = fn( param0: ?*DDHAL_COLORCONTROLDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DDHAL_DDCOLORCONTROLCALLBACKS = extern struct { dwSize: u32, dwFlags: u32, ColorControl: ?LPDDHALCOLORCB_COLORCONTROL, }; pub const LPDDHALKERNELCB_SYNCSURFACE = fn( param0: ?*DDHAL_SYNCSURFACEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALKERNELCB_SYNCVIDEOPORT = fn( param0: ?*DDHAL_SYNCVIDEOPORTDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DDHAL_DDKERNELCALLBACKS = extern struct { dwSize: u32, dwFlags: u32, SyncSurfaceData: ?LPDDHALKERNELCB_SYNCSURFACE, SyncVideoPortData: ?LPDDHALKERNELCB_SYNCVIDEOPORT, }; pub const LPDDGAMMACALIBRATORPROC = fn( param0: ?*DDGAMMARAMP, param1: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const LPDDHALMOCOMPCB_GETGUIDS = fn( param0: ?*DDHAL_GETMOCOMPGUIDSDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALMOCOMPCB_GETFORMATS = fn( param0: ?*DDHAL_GETMOCOMPFORMATSDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALMOCOMPCB_CREATE = fn( param0: ?*DDHAL_CREATEMOCOMPDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALMOCOMPCB_GETCOMPBUFFINFO = fn( param0: ?*DDHAL_GETMOCOMPCOMPBUFFDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALMOCOMPCB_GETINTERNALINFO = fn( param0: ?*DDHAL_GETINTERNALMOCOMPDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALMOCOMPCB_BEGINFRAME = fn( param0: ?*DDHAL_BEGINMOCOMPFRAMEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALMOCOMPCB_ENDFRAME = fn( param0: ?*DDHAL_ENDMOCOMPFRAMEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALMOCOMPCB_RENDER = fn( param0: ?*DDHAL_RENDERMOCOMPDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALMOCOMPCB_QUERYSTATUS = fn( param0: ?*DDHAL_QUERYMOCOMPSTATUSDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const LPDDHALMOCOMPCB_DESTROY = fn( param0: ?*DDHAL_DESTROYMOCOMPDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DDHAL_DDMOTIONCOMPCALLBACKS = extern struct { dwSize: u32, dwFlags: u32, GetMoCompGuids: ?LPDDHALMOCOMPCB_GETGUIDS, GetMoCompFormats: ?LPDDHALMOCOMPCB_GETFORMATS, CreateMoComp: ?LPDDHALMOCOMPCB_CREATE, GetMoCompBuffInfo: ?LPDDHALMOCOMPCB_GETCOMPBUFFINFO, GetInternalMoCompInfo: ?LPDDHALMOCOMPCB_GETINTERNALINFO, BeginMoCompFrame: ?LPDDHALMOCOMPCB_BEGINFRAME, EndMoCompFrame: ?LPDDHALMOCOMPCB_ENDFRAME, RenderMoComp: ?LPDDHALMOCOMPCB_RENDER, QueryMoCompStatus: ?LPDDHALMOCOMPCB_QUERYSTATUS, DestroyMoComp: ?LPDDHALMOCOMPCB_DESTROY, }; pub const DDNONLOCALVIDMEMCAPS = extern struct { dwSize: u32, dwNLVBCaps: u32, dwNLVBCaps2: u32, dwNLVBCKeyCaps: u32, dwNLVBFXCaps: u32, dwNLVBRops: [8]u32, }; pub const DDMORESURFACECAPS = extern struct { pub const ExtendedHeapRestrictions = extern struct { ddsCapsEx: DDSCAPSEX, ddsCapsExAlt: DDSCAPSEX, }; dwSize: u32, ddsCapsMore: DDSCAPSEX, ddsExtendedHeapRestrictions: [1]ExtendedHeapRestrictions, }; pub const DDSTEREOMODE = extern struct { dwSize: u32, dwHeight: u32, dwWidth: u32, dwBpp: u32, dwRefreshRate: u32, bSupported: BOOL, }; pub const DDRAWI_DDRAWPALETTE_INT = extern struct { lpVtbl: ?*anyopaque, lpLcl: ?*DDRAWI_DDRAWPALETTE_LCL, lpLink: ?*DDRAWI_DDRAWPALETTE_INT, dwIntRefCnt: u32, }; pub const DDRAWI_DDRAWPALETTE_GBL = extern struct { dwRefCnt: u32, dwFlags: u32, lpDD_lcl: ?*DDRAWI_DIRECTDRAW_LCL, dwProcessId: u32, lpColorTable: ?*PALETTEENTRY, Anonymous: extern union { dwReserved1: usize, hHELGDIPalette: ?HPALETTE, }, dwDriverReserved: u32, dwContentsStamp: u32, dwSaveStamp: u32, dwHandle: u32, }; pub const DDRAWI_DDRAWPALETTE_LCL = extern struct { lpPalMore: u32, lpGbl: ?*DDRAWI_DDRAWPALETTE_GBL, dwUnused0: usize, dwLocalRefCnt: u32, pUnkOuter: ?*IUnknown, lpDD_lcl: ?*DDRAWI_DIRECTDRAW_LCL, dwReserved1: usize, dwDDRAWReserved1: usize, dwDDRAWReserved2: usize, dwDDRAWReserved3: usize, }; pub const DDRAWI_DDRAWCLIPPER_INT = extern struct { lpVtbl: ?*anyopaque, lpLcl: ?*DDRAWI_DDRAWCLIPPER_LCL, lpLink: ?*DDRAWI_DDRAWCLIPPER_INT, dwIntRefCnt: u32, }; pub const DDRAWI_DDRAWCLIPPER_GBL = extern struct { dwRefCnt: u32, dwFlags: u32, lpDD: ?*DDRAWI_DIRECTDRAW_GBL, dwProcessId: u32, dwReserved1: usize, hWnd: usize, lpStaticClipList: ?*RGNDATA, }; pub const DDRAWI_DDRAWCLIPPER_LCL = extern struct { lpClipMore: u32, lpGbl: ?*DDRAWI_DDRAWCLIPPER_GBL, lpDD_lcl: ?*DDRAWI_DIRECTDRAW_LCL, dwLocalRefCnt: u32, pUnkOuter: ?*IUnknown, lpDD_int: ?*DDRAWI_DIRECTDRAW_INT, dwReserved1: usize, pAddrefedThisOwner: ?*IUnknown, }; pub const ATTACHLIST = extern struct { dwFlags: u32, lpLink: ?*ATTACHLIST, lpAttached: ?*DDRAWI_DDRAWSURFACE_LCL, lpIAttached: ?*DDRAWI_DDRAWSURFACE_INT, }; pub const DBLNODE = extern struct { next: ?*DBLNODE, prev: ?*DBLNODE, object: ?*DDRAWI_DDRAWSURFACE_LCL, object_int: ?*DDRAWI_DDRAWSURFACE_INT, }; pub const ACCESSRECTLIST = extern struct { lpLink: ?*ACCESSRECTLIST, rDest: RECT, lpOwner: ?*DDRAWI_DIRECTDRAW_LCL, lpSurfaceData: ?*anyopaque, dwFlags: u32, lpHeapAliasInfo: ?*HEAPALIASINFO, }; pub const DDRAWI_DDRAWSURFACE_INT = extern struct { lpVtbl: ?*anyopaque, lpLcl: ?*DDRAWI_DDRAWSURFACE_LCL, lpLink: ?*DDRAWI_DDRAWSURFACE_INT, dwIntRefCnt: u32, }; pub const DDRAWI_DDRAWSURFACE_GBL = extern struct { dwRefCnt: u32, dwGlobalFlags: u32, Anonymous1: extern union { lpRectList: ?*ACCESSRECTLIST, dwBlockSizeY: u32, lSlicePitch: i32, }, Anonymous2: extern union { lpVidMemHeap: ?*VMEMHEAP, dwBlockSizeX: u32, }, Anonymous3: extern union { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, lpDDHandle: ?*anyopaque, }, fpVidMem: usize, Anonymous4: extern union { lPitch: i32, dwLinearSize: u32, }, wHeight: u16, wWidth: u16, dwUsageCount: u32, dwReserved1: usize, ddpfSurface: DDPIXELFORMAT, }; pub const DDRAWI_DDRAWSURFACE_GBL_MORE = extern struct { dwSize: u32, Anonymous: extern union { dwPhysicalPageTable: u32, fpPhysicalVidMem: usize, }, pPageTable: ?*u32, cPages: u32, dwSavedDCContext: usize, fpAliasedVidMem: usize, dwDriverReserved: usize, dwHELReserved: usize, cPageUnlocks: u32, hKernelSurface: usize, dwKernelRefCnt: u32, lpColorInfo: ?*DDCOLORCONTROL, fpNTAlias: usize, dwContentsStamp: u32, lpvUnswappedDriverReserved: ?*anyopaque, lpDDRAWReserved2: ?*anyopaque, dwDDRAWReserved1: u32, dwDDRAWReserved2: u32, fpAliasOfVidMem: usize, }; pub const DDRAWI_DDRAWSURFACE_MORE = extern struct { dwSize: u32, lpIUnknowns: ?*IUNKNOWN_LIST, lpDD_lcl: ?*DDRAWI_DIRECTDRAW_LCL, dwPageLockCount: u32, dwBytesAllocated: u32, lpDD_int: ?*DDRAWI_DIRECTDRAW_INT, dwMipMapCount: u32, lpDDIClipper: ?*DDRAWI_DDRAWCLIPPER_INT, lpHeapAliasInfo: ?*HEAPALIASINFO, dwOverlayFlags: u32, rgjunc: ?*anyopaque, lpVideoPort: ?*DDRAWI_DDVIDEOPORT_LCL, lpddOverlayFX: ?*DDOVERLAYFX, ddsCapsEx: DDSCAPSEX, dwTextureStage: u32, lpDDRAWReserved: ?*anyopaque, lpDDRAWReserved2: ?*anyopaque, lpDDrawReserved3: ?*anyopaque, dwDDrawReserved4: u32, lpDDrawReserved5: ?*anyopaque, lpGammaRamp: ?*u32, lpOriginalGammaRamp: ?*u32, lpDDrawReserved6: ?*anyopaque, dwSurfaceHandle: u32, qwDDrawReserved8: [2]u32, lpDDrawReserved9: ?*anyopaque, cSurfaces: u32, pCreatedDDSurfaceDesc2: ?*DDSURFACEDESC2, slist: ?*?*DDRAWI_DDRAWSURFACE_LCL, dwFVF: u32, lpVB: ?*anyopaque, }; pub const DDRAWI_DDRAWSURFACE_LCL = extern struct { lpSurfMore: ?*DDRAWI_DDRAWSURFACE_MORE, lpGbl: ?*DDRAWI_DDRAWSURFACE_GBL, hDDSurface: usize, lpAttachList: ?*ATTACHLIST, lpAttachListFrom: ?*ATTACHLIST, dwLocalRefCnt: u32, dwProcessId: u32, dwFlags: u32, ddsCaps: DDSCAPS, Anonymous1: extern union { lpDDPalette: ?*DDRAWI_DDRAWPALETTE_INT, lp16DDPalette: ?*DDRAWI_DDRAWPALETTE_INT, }, Anonymous2: extern union { lpDDClipper: ?*DDRAWI_DDRAWCLIPPER_LCL, lp16DDClipper: ?*DDRAWI_DDRAWCLIPPER_INT, }, dwModeCreatedIn: u32, dwBackBufferCount: u32, ddckCKDestBlt: DDCOLORKEY, ddckCKSrcBlt: DDCOLORKEY, hDC: usize, dwReserved1: usize, ddckCKSrcOverlay: DDCOLORKEY, ddckCKDestOverlay: DDCOLORKEY, lpSurfaceOverlaying: ?*DDRAWI_DDRAWSURFACE_INT, dbnOverlayNode: DBLNODE, rcOverlaySrc: RECT, rcOverlayDest: RECT, dwClrXparent: u32, dwAlpha: u32, lOverlayX: i32, lOverlayY: i32, }; pub const DDHALMODEINFO = extern struct { dwWidth: u32, dwHeight: u32, lPitch: i32, dwBPP: u32, wFlags: u16, wRefreshRate: u16, dwRBitMask: u32, dwGBitMask: u32, dwBBitMask: u32, dwAlphaBitMask: u32, }; pub const DDRAWI_DIRECTDRAW_INT = extern struct { lpVtbl: ?*anyopaque, lpLcl: ?*DDRAWI_DIRECTDRAW_LCL, lpLink: ?*DDRAWI_DIRECTDRAW_INT, dwIntRefCnt: u32, }; pub const DDHAL_CALLBACKS = extern struct { cbDDCallbacks: DDHAL_DDCALLBACKS, cbDDSurfaceCallbacks: DDHAL_DDSURFACECALLBACKS, cbDDPaletteCallbacks: DDHAL_DDPALETTECALLBACKS, HALDD: DDHAL_DDCALLBACKS, HALDDSurface: DDHAL_DDSURFACECALLBACKS, HALDDPalette: DDHAL_DDPALETTECALLBACKS, HELDD: DDHAL_DDCALLBACKS, HELDDSurface: DDHAL_DDSURFACECALLBACKS, HELDDPalette: DDHAL_DDPALETTECALLBACKS, cbDDExeBufCallbacks: DDHAL_DDEXEBUFCALLBACKS, HALDDExeBuf: DDHAL_DDEXEBUFCALLBACKS, HELDDExeBuf: DDHAL_DDEXEBUFCALLBACKS, cbDDVideoPortCallbacks: DDHAL_DDVIDEOPORTCALLBACKS, HALDDVideoPort: DDHAL_DDVIDEOPORTCALLBACKS, cbDDColorControlCallbacks: DDHAL_DDCOLORCONTROLCALLBACKS, HALDDColorControl: DDHAL_DDCOLORCONTROLCALLBACKS, cbDDMiscellaneousCallbacks: DDHAL_DDMISCELLANEOUSCALLBACKS, HALDDMiscellaneous: DDHAL_DDMISCELLANEOUSCALLBACKS, cbDDKernelCallbacks: DDHAL_DDKERNELCALLBACKS, HALDDKernel: DDHAL_DDKERNELCALLBACKS, cbDDMotionCompCallbacks: DDHAL_DDMOTIONCOMPCALLBACKS, HALDDMotionComp: DDHAL_DDMOTIONCOMPCALLBACKS, }; pub const DDCORECAPS = extern struct { dwSize: u32, dwCaps: u32, dwCaps2: u32, dwCKeyCaps: u32, dwFXCaps: u32, dwFXAlphaCaps: u32, dwPalCaps: u32, dwSVCaps: u32, dwAlphaBltConstBitDepths: u32, dwAlphaBltPixelBitDepths: u32, dwAlphaBltSurfaceBitDepths: u32, dwAlphaOverlayConstBitDepths: u32, dwAlphaOverlayPixelBitDepths: u32, dwAlphaOverlaySurfaceBitDepths: u32, dwZBufferBitDepths: u32, dwVidMemTotal: u32, dwVidMemFree: u32, dwMaxVisibleOverlays: u32, dwCurrVisibleOverlays: u32, dwNumFourCCCodes: u32, dwAlignBoundarySrc: u32, dwAlignSizeSrc: u32, dwAlignBoundaryDest: u32, dwAlignSizeDest: u32, dwAlignStrideAlign: u32, dwRops: [8]u32, ddsCaps: DDSCAPS, dwMinOverlayStretch: u32, dwMaxOverlayStretch: u32, dwMinLiveVideoStretch: u32, dwMaxLiveVideoStretch: u32, dwMinHwCodecStretch: u32, dwMaxHwCodecStretch: u32, dwReserved1: u32, dwReserved2: u32, dwReserved3: u32, dwSVBCaps: u32, dwSVBCKeyCaps: u32, dwSVBFXCaps: u32, dwSVBRops: [8]u32, dwVSBCaps: u32, dwVSBCKeyCaps: u32, dwVSBFXCaps: u32, dwVSBRops: [8]u32, dwSSBCaps: u32, dwSSBCKeyCaps: u32, dwSSBFXCaps: u32, dwSSBRops: [8]u32, dwMaxVideoPorts: u32, dwCurrVideoPorts: u32, dwSVBCaps2: u32, }; pub const DDRAWI_DIRECTDRAW_GBL = extern struct { dwRefCnt: u32, dwFlags: u32, fpPrimaryOrig: usize, ddCaps: DDCORECAPS, dwInternal1: u32, dwUnused1: [9]u32, lpDDCBtmp: ?*DDHAL_CALLBACKS, dsList: ?*DDRAWI_DDRAWSURFACE_INT, palList: ?*DDRAWI_DDRAWPALETTE_INT, clipperList: ?*DDRAWI_DDRAWCLIPPER_INT, lp16DD: ?*DDRAWI_DIRECTDRAW_GBL, dwMaxOverlays: u32, dwCurrOverlays: u32, dwMonitorFrequency: u32, ddHELCaps: DDCORECAPS, dwUnused2: [50]u32, ddckCKDestOverlay: DDCOLORKEY, ddckCKSrcOverlay: DDCOLORKEY, vmiData: VIDMEMINFO, lpDriverHandle: ?*anyopaque, lpExclusiveOwner: ?*DDRAWI_DIRECTDRAW_LCL, dwModeIndex: u32, dwModeIndexOrig: u32, dwNumFourCC: u32, lpdwFourCC: ?*u32, dwNumModes: u32, lpModeInfo: ?*DDHALMODEINFO, plProcessList: PROCESS_LIST, dwSurfaceLockCount: u32, dwAliasedLockCnt: u32, dwReserved3: usize, hDD: usize, cObsolete: [12]CHAR, dwReserved1: u32, dwReserved2: u32, dbnOverlayRoot: DBLNODE, lpwPDeviceFlags: ?*u16, dwPDevice: u32, dwWin16LockCnt: u32, dwUnused3: u32, hInstance: u32, dwEvent16: u32, dwSaveNumModes: u32, lpD3DGlobalDriverData: usize, lpD3DHALCallbacks: usize, ddBothCaps: DDCORECAPS, lpDDVideoPortCaps: ?*DDVIDEOPORTCAPS, dvpList: ?*DDRAWI_DDVIDEOPORT_INT, lpD3DHALCallbacks2: usize, rectDevice: RECT, cMonitors: u32, gpbmiSrc: ?*anyopaque, gpbmiDest: ?*anyopaque, phaiHeapAliases: ?*HEAPALIASINFO, hKernelHandle: usize, pfnNotifyProc: usize, lpDDKernelCaps: ?*DDKERNELCAPS, lpddNLVCaps: ?*DDNONLOCALVIDMEMCAPS, lpddNLVHELCaps: ?*DDNONLOCALVIDMEMCAPS, lpddNLVBothCaps: ?*DDNONLOCALVIDMEMCAPS, lpD3DExtendedCaps: usize, dwDOSBoxEvent: u32, rectDesktop: RECT, cDriverName: [32]CHAR, lpD3DHALCallbacks3: usize, dwNumZPixelFormats: u32, lpZPixelFormats: ?*DDPIXELFORMAT, mcList: ?*DDRAWI_DDMOTIONCOMP_INT, hDDVxd: u32, ddsCapsMore: DDSCAPSEX, }; pub const DDRAWI_DIRECTDRAW_LCL = extern struct { lpDDMore: u32, lpGbl: ?*DDRAWI_DIRECTDRAW_GBL, dwUnused0: u32, dwLocalFlags: u32, dwLocalRefCnt: u32, dwProcessId: u32, pUnkOuter: ?*IUnknown, dwObsolete1: u32, hWnd: usize, hDC: usize, dwErrorMode: u32, lpPrimary: ?*DDRAWI_DDRAWSURFACE_INT, lpCB: ?*DDRAWI_DDRAWSURFACE_INT, dwPreferredMode: u32, hD3DInstance: ?HINSTANCE, pD3DIUnknown: ?*IUnknown, lpDDCB: ?*DDHAL_CALLBACKS, hDDVxd: usize, dwAppHackFlags: u32, hFocusWnd: usize, dwHotTracking: u32, dwIMEState: u32, hWndPopup: usize, hDD: usize, hGammaCalibrator: usize, lpGammaCalibrator: ?LPDDGAMMACALIBRATORPROC, }; pub const DDRAWI_DDVIDEOPORT_INT = extern struct { lpVtbl: ?*anyopaque, lpLcl: ?*DDRAWI_DDVIDEOPORT_LCL, lpLink: ?*DDRAWI_DDVIDEOPORT_INT, dwIntRefCnt: u32, dwFlags: u32, }; pub const DDRAWI_DDVIDEOPORT_LCL = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_LCL, ddvpDesc: DDVIDEOPORTDESC, ddvpInfo: DDVIDEOPORTINFO, lpSurface: ?*DDRAWI_DDRAWSURFACE_INT, lpVBISurface: ?*DDRAWI_DDRAWSURFACE_INT, lpFlipInts: ?*?*DDRAWI_DDRAWSURFACE_INT, dwNumAutoflip: u32, dwProcessID: u32, dwStateFlags: u32, dwFlags: u32, dwRefCnt: u32, fpLastFlip: usize, dwReserved1: usize, dwReserved2: usize, hDDVideoPort: ?HANDLE, dwNumVBIAutoflip: u32, lpVBIDesc: ?*DDVIDEOPORTDESC, lpVideoDesc: ?*DDVIDEOPORTDESC, lpVBIInfo: ?*DDVIDEOPORTINFO, lpVideoInfo: ?*DDVIDEOPORTINFO, dwVBIProcessID: u32, lpVPNotify: ?*DDRAWI_DDVIDEOPORT_INT, }; pub const DDRAWI_DDMOTIONCOMP_INT = extern struct { lpVtbl: ?*anyopaque, lpLcl: ?*DDRAWI_DDMOTIONCOMP_LCL, lpLink: ?*DDRAWI_DDMOTIONCOMP_INT, dwIntRefCnt: u32, }; pub const DDRAWI_DDMOTIONCOMP_LCL = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_LCL, guid: Guid, dwUncompWidth: u32, dwUncompHeight: u32, ddUncompPixelFormat: DDPIXELFORMAT, dwInternalFlags: u32, dwRefCnt: u32, dwProcessId: u32, hMoComp: ?HANDLE, dwDriverReserved1: u32, dwDriverReserved2: u32, dwDriverReserved3: u32, lpDriverReserved1: ?*anyopaque, lpDriverReserved2: ?*anyopaque, lpDriverReserved3: ?*anyopaque, }; pub const DDHALINFO = extern struct { dwSize: u32, lpDDCallbacks: ?*DDHAL_DDCALLBACKS, lpDDSurfaceCallbacks: ?*DDHAL_DDSURFACECALLBACKS, lpDDPaletteCallbacks: ?*DDHAL_DDPALETTECALLBACKS, vmiData: VIDMEMINFO, ddCaps: DDCORECAPS, dwMonitorFrequency: u32, GetDriverInfo: ?LPDDHAL_GETDRIVERINFO, dwModeIndex: u32, lpdwFourCC: ?*u32, dwNumModes: u32, lpModeInfo: ?*DDHALMODEINFO, dwFlags: u32, lpPDevice: ?*anyopaque, hInstance: u32, lpD3DGlobalDriverData: usize, lpD3DHALCallbacks: usize, lpDDExeBufCallbacks: ?*DDHAL_DDEXEBUFCALLBACKS, }; pub const LPDDHAL_SETINFO = fn( lpDDHalInfo: ?*DDHALINFO, reset: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const LPDDHAL_VIDMEMALLOC = fn( lpDD: ?*DDRAWI_DIRECTDRAW_GBL, heap: i32, dwWidth: u32, dwHeight: u32, ) callconv(@import("std").os.windows.WINAPI) usize; pub const LPDDHAL_VIDMEMFREE = fn( lpDD: ?*DDRAWI_DIRECTDRAW_GBL, heap: i32, fpMem: usize, ) callconv(@import("std").os.windows.WINAPI) void; pub const DDHALDDRAWFNS = extern struct { dwSize: u32, lpSetInfo: ?LPDDHAL_SETINFO, lpVidMemAlloc: ?LPDDHAL_VIDMEMALLOC, lpVidMemFree: ?LPDDHAL_VIDMEMFREE, }; pub const DDHAL_BLTDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, lpDDDestSurface: ?*DDRAWI_DDRAWSURFACE_LCL, rDest: RECTL, lpDDSrcSurface: ?*DDRAWI_DDRAWSURFACE_LCL, rSrc: RECTL, dwFlags: u32, dwROPFlags: u32, bltFX: DDBLTFX, ddRVal: HRESULT, Blt: ?LPDDHALSURFCB_BLT, IsClipped: BOOL, rOrigDest: RECTL, rOrigSrc: RECTL, dwRectCnt: u32, prDestRects: ?*RECT, }; pub const DDHAL_LOCKDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, lpDDSurface: ?*DDRAWI_DDRAWSURFACE_LCL, bHasRect: u32, rArea: RECTL, lpSurfData: ?*anyopaque, ddRVal: HRESULT, Lock: ?LPDDHALSURFCB_LOCK, dwFlags: u32, }; pub const DDHAL_UNLOCKDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, lpDDSurface: ?*DDRAWI_DDRAWSURFACE_LCL, ddRVal: HRESULT, Unlock: ?LPDDHALSURFCB_UNLOCK, }; pub const DDHAL_UPDATEOVERLAYDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, lpDDDestSurface: ?*DDRAWI_DDRAWSURFACE_LCL, rDest: RECTL, lpDDSrcSurface: ?*DDRAWI_DDRAWSURFACE_LCL, rSrc: RECTL, dwFlags: u32, overlayFX: DDOVERLAYFX, ddRVal: HRESULT, UpdateOverlay: ?LPDDHALSURFCB_UPDATEOVERLAY, }; pub const DDHAL_SETOVERLAYPOSITIONDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, lpDDSrcSurface: ?*DDRAWI_DDRAWSURFACE_LCL, lpDDDestSurface: ?*DDRAWI_DDRAWSURFACE_LCL, lXPos: i32, lYPos: i32, ddRVal: HRESULT, SetOverlayPosition: ?LPDDHALSURFCB_SETOVERLAYPOSITION, }; pub const DDHAL_SETPALETTEDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, lpDDSurface: ?*DDRAWI_DDRAWSURFACE_LCL, lpDDPalette: ?*DDRAWI_DDRAWPALETTE_GBL, ddRVal: HRESULT, SetPalette: ?LPDDHALSURFCB_SETPALETTE, Attach: BOOL, }; pub const DDHAL_FLIPDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, lpSurfCurr: ?*DDRAWI_DDRAWSURFACE_LCL, lpSurfTarg: ?*DDRAWI_DDRAWSURFACE_LCL, dwFlags: u32, ddRVal: HRESULT, Flip: ?LPDDHALSURFCB_FLIP, lpSurfCurrLeft: ?*DDRAWI_DDRAWSURFACE_LCL, lpSurfTargLeft: ?*DDRAWI_DDRAWSURFACE_LCL, }; pub const DDHAL_DESTROYSURFACEDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, lpDDSurface: ?*DDRAWI_DDRAWSURFACE_LCL, ddRVal: HRESULT, DestroySurface: ?LPDDHALSURFCB_DESTROYSURFACE, }; pub const DDHAL_SETCLIPLISTDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, lpDDSurface: ?*DDRAWI_DDRAWSURFACE_LCL, ddRVal: HRESULT, SetClipList: ?LPDDHALSURFCB_SETCLIPLIST, }; pub const DDHAL_ADDATTACHEDSURFACEDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, lpDDSurface: ?*DDRAWI_DDRAWSURFACE_LCL, lpSurfAttached: ?*DDRAWI_DDRAWSURFACE_LCL, ddRVal: HRESULT, AddAttachedSurface: ?LPDDHALSURFCB_ADDATTACHEDSURFACE, }; pub const DDHAL_SETCOLORKEYDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, lpDDSurface: ?*DDRAWI_DDRAWSURFACE_LCL, dwFlags: u32, ckNew: DDCOLORKEY, ddRVal: HRESULT, SetColorKey: ?LPDDHALSURFCB_SETCOLORKEY, }; pub const DDHAL_GETBLTSTATUSDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, lpDDSurface: ?*DDRAWI_DDRAWSURFACE_LCL, dwFlags: u32, ddRVal: HRESULT, GetBltStatus: ?LPDDHALSURFCB_GETBLTSTATUS, }; pub const DDHAL_GETFLIPSTATUSDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, lpDDSurface: ?*DDRAWI_DDRAWSURFACE_LCL, dwFlags: u32, ddRVal: HRESULT, GetFlipStatus: ?LPDDHALSURFCB_GETFLIPSTATUS, }; pub const DDHAL_DESTROYPALETTEDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, lpDDPalette: ?*DDRAWI_DDRAWPALETTE_GBL, ddRVal: HRESULT, DestroyPalette: ?LPDDHALPALCB_DESTROYPALETTE, }; pub const DDHAL_SETENTRIESDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, lpDDPalette: ?*DDRAWI_DDRAWPALETTE_GBL, dwBase: u32, dwNumEntries: u32, lpEntries: ?*PALETTEENTRY, ddRVal: HRESULT, SetEntries: ?LPDDHALPALCB_SETENTRIES, }; pub const DDHAL_CREATESURFACEDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, lpDDSurfaceDesc: ?*DDSURFACEDESC, lplpSList: ?*?*DDRAWI_DDRAWSURFACE_LCL, dwSCnt: u32, ddRVal: HRESULT, CreateSurface: ?LPDDHAL_CREATESURFACE, }; pub const DDHAL_CANCREATESURFACEDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, lpDDSurfaceDesc: ?*DDSURFACEDESC, bIsDifferentPixelFormat: u32, ddRVal: HRESULT, CanCreateSurface: ?LPDDHAL_CANCREATESURFACE, }; pub const DDHAL_CREATEPALETTEDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, lpDDPalette: ?*DDRAWI_DDRAWPALETTE_GBL, lpColorTable: ?*PALETTEENTRY, ddRVal: HRESULT, CreatePalette: ?LPDDHAL_CREATEPALETTE, is_excl: BOOL, }; pub const DDHAL_WAITFORVERTICALBLANKDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, dwFlags: u32, bIsInVB: u32, hEvent: usize, ddRVal: HRESULT, WaitForVerticalBlank: ?LPDDHAL_WAITFORVERTICALBLANK, }; pub const DDHAL_DESTROYDRIVERDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, ddRVal: HRESULT, DestroyDriver: ?LPDDHAL_DESTROYDRIVER, }; pub const DDHAL_SETMODEDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, dwModeIndex: u32, ddRVal: HRESULT, SetMode: ?LPDDHAL_SETMODE, inexcl: BOOL, useRefreshRate: BOOL, }; pub const DDHAL_DRVSETCOLORKEYDATA = extern struct { lpDDSurface: ?*DDRAWI_DDRAWSURFACE_LCL, dwFlags: u32, ckNew: DDCOLORKEY, ddRVal: HRESULT, SetColorKey: ?LPDDHAL_SETCOLORKEY, }; pub const DDHAL_GETSCANLINEDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, dwScanLine: u32, ddRVal: HRESULT, GetScanLine: ?LPDDHAL_GETSCANLINE, }; pub const DDHAL_SETEXCLUSIVEMODEDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, dwEnterExcl: u32, dwReserved: u32, ddRVal: HRESULT, SetExclusiveMode: ?LPDDHAL_SETEXCLUSIVEMODE, }; pub const DDHAL_FLIPTOGDISURFACEDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, dwToGDI: u32, dwReserved: u32, ddRVal: HRESULT, FlipToGDISurface: ?LPDDHAL_FLIPTOGDISURFACE, }; pub const DDHAL_CANCREATEVPORTDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_LCL, lpDDVideoPortDesc: ?*DDVIDEOPORTDESC, ddRVal: HRESULT, CanCreateVideoPort: ?LPDDHALVPORTCB_CANCREATEVIDEOPORT, }; pub const DDHAL_CREATEVPORTDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_LCL, lpDDVideoPortDesc: ?*DDVIDEOPORTDESC, lpVideoPort: ?*DDRAWI_DDVIDEOPORT_LCL, ddRVal: HRESULT, CreateVideoPort: ?LPDDHALVPORTCB_CREATEVIDEOPORT, }; pub const DDHAL_FLIPVPORTDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_LCL, lpVideoPort: ?*DDRAWI_DDVIDEOPORT_LCL, lpSurfCurr: ?*DDRAWI_DDRAWSURFACE_LCL, lpSurfTarg: ?*DDRAWI_DDRAWSURFACE_LCL, ddRVal: HRESULT, FlipVideoPort: ?LPDDHALVPORTCB_FLIP, }; pub const DDHAL_GETVPORTBANDWIDTHDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_LCL, lpVideoPort: ?*DDRAWI_DDVIDEOPORT_LCL, lpddpfFormat: ?*DDPIXELFORMAT, dwWidth: u32, dwHeight: u32, dwFlags: u32, lpBandwidth: ?*DDVIDEOPORTBANDWIDTH, ddRVal: HRESULT, GetVideoPortBandwidth: ?LPDDHALVPORTCB_GETBANDWIDTH, }; pub const DDHAL_GETVPORTINPUTFORMATDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_LCL, lpVideoPort: ?*DDRAWI_DDVIDEOPORT_LCL, dwFlags: u32, lpddpfFormat: ?*DDPIXELFORMAT, dwNumFormats: u32, ddRVal: HRESULT, GetVideoPortInputFormats: ?LPDDHALVPORTCB_GETINPUTFORMATS, }; pub const DDHAL_GETVPORTOUTPUTFORMATDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_LCL, lpVideoPort: ?*DDRAWI_DDVIDEOPORT_LCL, dwFlags: u32, lpddpfInputFormat: ?*DDPIXELFORMAT, lpddpfOutputFormats: ?*DDPIXELFORMAT, dwNumFormats: u32, ddRVal: HRESULT, GetVideoPortOutputFormats: ?LPDDHALVPORTCB_GETOUTPUTFORMATS, }; pub const DDHAL_GETVPORTFIELDDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_LCL, lpVideoPort: ?*DDRAWI_DDVIDEOPORT_LCL, bField: BOOL, ddRVal: HRESULT, GetVideoPortField: ?LPDDHALVPORTCB_GETFIELD, }; pub const DDHAL_GETVPORTLINEDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_LCL, lpVideoPort: ?*DDRAWI_DDVIDEOPORT_LCL, dwLine: u32, ddRVal: HRESULT, GetVideoPortLine: ?LPDDHALVPORTCB_GETLINE, }; pub const DDHAL_GETVPORTCONNECTDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_LCL, dwPortId: u32, lpConnect: ?*DDVIDEOPORTCONNECT, dwNumEntries: u32, ddRVal: HRESULT, GetVideoPortConnectInfo: ?LPDDHALVPORTCB_GETVPORTCONNECT, }; pub const DDHAL_DESTROYVPORTDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_LCL, lpVideoPort: ?*DDRAWI_DDVIDEOPORT_LCL, ddRVal: HRESULT, DestroyVideoPort: ?LPDDHALVPORTCB_DESTROYVPORT, }; pub const DDHAL_GETVPORTFLIPSTATUSDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_LCL, fpSurface: usize, ddRVal: HRESULT, GetVideoPortFlipStatus: ?LPDDHALVPORTCB_GETFLIPSTATUS, }; pub const DDHAL_UPDATEVPORTDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_LCL, lpVideoPort: ?*DDRAWI_DDVIDEOPORT_LCL, lplpDDSurface: ?*?*DDRAWI_DDRAWSURFACE_INT, lplpDDVBISurface: ?*?*DDRAWI_DDRAWSURFACE_INT, lpVideoInfo: ?*DDVIDEOPORTINFO, dwFlags: u32, dwNumAutoflip: u32, dwNumVBIAutoflip: u32, ddRVal: HRESULT, UpdateVideoPort: ?LPDDHALVPORTCB_UPDATE, }; pub const DDHAL_WAITFORVPORTSYNCDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_LCL, lpVideoPort: ?*DDRAWI_DDVIDEOPORT_LCL, dwFlags: u32, dwLine: u32, dwTimeOut: u32, ddRVal: HRESULT, WaitForVideoPortSync: ?LPDDHALVPORTCB_WAITFORSYNC, }; pub const DDHAL_GETVPORTSIGNALDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_LCL, lpVideoPort: ?*DDRAWI_DDVIDEOPORT_LCL, dwStatus: u32, ddRVal: HRESULT, GetVideoSignalStatus: ?LPDDHALVPORTCB_GETSIGNALSTATUS, }; pub const DDHAL_VPORTCOLORDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_LCL, lpVideoPort: ?*DDRAWI_DDVIDEOPORT_LCL, dwFlags: u32, lpColorData: ?*DDCOLORCONTROL, ddRVal: HRESULT, ColorControl: ?LPDDHALVPORTCB_COLORCONTROL, }; pub const DDHAL_COLORCONTROLDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, lpDDSurface: ?*DDRAWI_DDRAWSURFACE_LCL, lpColorData: ?*DDCOLORCONTROL, dwFlags: u32, ddRVal: HRESULT, ColorControl: ?LPDDHALCOLORCB_COLORCONTROL, }; pub const DDHAL_GETDRIVERINFODATA = extern struct { dwSize: u32, dwFlags: u32, guidInfo: Guid, dwExpectedSize: u32, lpvData: ?*anyopaque, dwActualSize: u32, ddRVal: HRESULT, dwContext: usize, }; pub const DDHAL_GETAVAILDRIVERMEMORYDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, DDSCaps: DDSCAPS, dwTotal: u32, dwFree: u32, ddRVal: HRESULT, GetAvailDriverMemory: ?LPDDHAL_GETAVAILDRIVERMEMORY, ddsCapsEx: DDSCAPSEX, }; pub const DDHAL_UPDATENONLOCALHEAPDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_GBL, dwHeap: u32, fpGARTLin: usize, fpGARTDev: usize, ulPolicyMaxBytes: usize, ddRVal: HRESULT, UpdateNonLocalHeap: ?LPDDHAL_UPDATENONLOCALHEAP, }; pub const DDHAL_GETHEAPALIGNMENTDATA = extern struct { dwInstance: usize, dwHeap: u32, ddRVal: HRESULT, GetHeapAlignment: ?LPDDHAL_GETHEAPALIGNMENT, Alignment: HEAPALIGNMENT, }; pub const DDHAL_CREATESURFACEEXDATA = extern struct { dwFlags: u32, lpDDLcl: ?*DDRAWI_DIRECTDRAW_LCL, lpDDSLcl: ?*DDRAWI_DDRAWSURFACE_LCL, ddRVal: HRESULT, }; pub const DDHAL_GETDRIVERSTATEDATA = extern struct { dwFlags: u32, Anonymous: extern union { dwhContext: usize, }, lpdwStates: ?*u32, dwLength: u32, ddRVal: HRESULT, }; pub const DDHAL_DESTROYDDLOCALDATA = extern struct { dwFlags: u32, pDDLcl: ?*DDRAWI_DIRECTDRAW_LCL, ddRVal: HRESULT, }; pub const DDHAL_SYNCSURFACEDATA = extern struct { dwSize: u32, lpDD: ?*DDRAWI_DIRECTDRAW_LCL, lpDDSurface: ?*DDRAWI_DDRAWSURFACE_LCL, dwSurfaceOffset: u32, fpLockPtr: usize, lPitch: i32, dwOverlayOffset: u32, dwOverlaySrcWidth: u32, dwOverlaySrcHeight: u32, dwOverlayDestWidth: u32, dwOverlayDestHeight: u32, dwDriverReserved1: usize, dwDriverReserved2: usize, dwDriverReserved3: usize, ddRVal: HRESULT, }; pub const DDHAL_SYNCVIDEOPORTDATA = extern struct { dwSize: u32, lpDD: ?*DDRAWI_DIRECTDRAW_LCL, lpVideoPort: ?*DDRAWI_DDVIDEOPORT_LCL, dwOriginOffset: u32, dwHeight: u32, dwVBIHeight: u32, dwDriverReserved1: usize, dwDriverReserved2: usize, dwDriverReserved3: usize, ddRVal: HRESULT, }; pub const DDHAL_GETMOCOMPGUIDSDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_LCL, dwNumGuids: u32, lpGuids: ?*Guid, ddRVal: HRESULT, GetMoCompGuids: ?LPDDHALMOCOMPCB_GETGUIDS, }; pub const DDHAL_GETMOCOMPFORMATSDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_LCL, lpGuid: ?*Guid, dwNumFormats: u32, lpFormats: ?*DDPIXELFORMAT, ddRVal: HRESULT, GetMoCompFormats: ?LPDDHALMOCOMPCB_GETFORMATS, }; pub const DDHAL_CREATEMOCOMPDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_LCL, lpMoComp: ?*DDRAWI_DDMOTIONCOMP_LCL, lpGuid: ?*Guid, dwUncompWidth: u32, dwUncompHeight: u32, ddUncompPixelFormat: DDPIXELFORMAT, lpData: ?*anyopaque, dwDataSize: u32, ddRVal: HRESULT, CreateMoComp: ?LPDDHALMOCOMPCB_CREATE, }; pub const DDMCCOMPBUFFERINFO = extern struct { dwSize: u32, dwNumCompBuffers: u32, dwWidthToCreate: u32, dwHeightToCreate: u32, dwBytesToAllocate: u32, ddCompCaps: DDSCAPS2, ddPixelFormat: DDPIXELFORMAT, }; pub const DDHAL_GETMOCOMPCOMPBUFFDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_LCL, lpGuid: ?*Guid, dwWidth: u32, dwHeight: u32, ddPixelFormat: DDPIXELFORMAT, dwNumTypesCompBuffs: u32, lpCompBuffInfo: ?*DDMCCOMPBUFFERINFO, ddRVal: HRESULT, GetMoCompBuffInfo: ?LPDDHALMOCOMPCB_GETCOMPBUFFINFO, }; pub const DDHAL_GETINTERNALMOCOMPDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_LCL, lpGuid: ?*Guid, dwWidth: u32, dwHeight: u32, ddPixelFormat: DDPIXELFORMAT, dwScratchMemAlloc: u32, ddRVal: HRESULT, GetInternalMoCompInfo: ?LPDDHALMOCOMPCB_GETINTERNALINFO, }; pub const DDHAL_BEGINMOCOMPFRAMEDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_LCL, lpMoComp: ?*DDRAWI_DDMOTIONCOMP_LCL, lpDestSurface: ?*DDRAWI_DDRAWSURFACE_LCL, dwInputDataSize: u32, lpInputData: ?*anyopaque, dwOutputDataSize: u32, lpOutputData: ?*anyopaque, ddRVal: HRESULT, BeginMoCompFrame: ?LPDDHALMOCOMPCB_BEGINFRAME, }; pub const DDHAL_ENDMOCOMPFRAMEDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_LCL, lpMoComp: ?*DDRAWI_DDMOTIONCOMP_LCL, lpInputData: ?*anyopaque, dwInputDataSize: u32, ddRVal: HRESULT, EndMoCompFrame: ?LPDDHALMOCOMPCB_ENDFRAME, }; pub const DDMCBUFFERINFO = extern struct { dwSize: u32, lpCompSurface: ?*DDRAWI_DDRAWSURFACE_LCL, dwDataOffset: u32, dwDataSize: u32, lpPrivate: ?*anyopaque, }; pub const DDHAL_RENDERMOCOMPDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_LCL, lpMoComp: ?*DDRAWI_DDMOTIONCOMP_LCL, dwNumBuffers: u32, lpBufferInfo: ?*DDMCBUFFERINFO, dwFunction: u32, lpInputData: ?*anyopaque, dwInputDataSize: u32, lpOutputData: ?*anyopaque, dwOutputDataSize: u32, ddRVal: HRESULT, RenderMoComp: ?LPDDHALMOCOMPCB_RENDER, }; pub const DDHAL_QUERYMOCOMPSTATUSDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_LCL, lpMoComp: ?*DDRAWI_DDMOTIONCOMP_LCL, lpSurface: ?*DDRAWI_DDRAWSURFACE_LCL, dwFlags: u32, ddRVal: HRESULT, QueryMoCompStatus: ?LPDDHALMOCOMPCB_QUERYSTATUS, }; pub const DDHAL_DESTROYMOCOMPDATA = extern struct { lpDD: ?*DDRAWI_DIRECTDRAW_LCL, lpMoComp: ?*DDRAWI_DDMOTIONCOMP_LCL, ddRVal: HRESULT, DestroyMoComp: ?LPDDHALMOCOMPCB_DESTROY, }; pub const _DD_DESTROYDRIVERDATA = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const _DD_SETMODEDATA = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const _DD_GETVPORTAUTOFLIPSURFACEDATA = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const VIDEOMEMORY = extern struct { dwFlags: u32, fpStart: usize, Anonymous1: extern union { fpEnd: usize, dwWidth: u32, }, ddsCaps: DDSCAPS, ddsCapsAlt: DDSCAPS, Anonymous2: extern union { lpHeap: ?*VMEMHEAP, dwHeight: u32, }, }; pub const VIDEOMEMORYINFO = extern struct { fpPrimary: usize, dwFlags: u32, dwDisplayWidth: u32, dwDisplayHeight: u32, lDisplayPitch: i32, ddpfDisplay: DDPIXELFORMAT, dwOffscreenAlign: u32, dwOverlayAlign: u32, dwTextureAlign: u32, dwZBufferAlign: u32, dwAlphaAlign: u32, pvPrimary: ?*anyopaque, }; pub const PDD_SETCOLORKEY = fn( param0: ?*DD_DRVSETCOLORKEYDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_CANCREATESURFACE = fn( param0: ?*DD_CANCREATESURFACEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_WAITFORVERTICALBLANK = fn( param0: ?*DD_WAITFORVERTICALBLANKDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_CREATESURFACE = fn( param0: ?*DD_CREATESURFACEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_DESTROYDRIVER = fn( param0: ?*_DD_DESTROYDRIVERDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_SETMODE = fn( param0: ?*_DD_SETMODEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_CREATEPALETTE = fn( param0: ?*DD_CREATEPALETTEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_GETSCANLINE = fn( param0: ?*DD_GETSCANLINEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_MAPMEMORY = fn( param0: ?*DD_MAPMEMORYDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_GETDRIVERINFO = fn( param0: ?*DD_GETDRIVERINFODATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DD_CALLBACKS = extern struct { dwSize: u32, dwFlags: u32, DestroyDriver: ?PDD_DESTROYDRIVER, CreateSurface: ?PDD_CREATESURFACE, SetColorKey: ?PDD_SETCOLORKEY, SetMode: ?PDD_SETMODE, WaitForVerticalBlank: ?PDD_WAITFORVERTICALBLANK, CanCreateSurface: ?PDD_CANCREATESURFACE, CreatePalette: ?PDD_CREATEPALETTE, GetScanLine: ?PDD_GETSCANLINE, MapMemory: ?PDD_MAPMEMORY, }; pub const PDD_GETAVAILDRIVERMEMORY = fn( param0: ?*DD_GETAVAILDRIVERMEMORYDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DD_MISCELLANEOUSCALLBACKS = extern struct { dwSize: u32, dwFlags: u32, GetAvailDriverMemory: ?PDD_GETAVAILDRIVERMEMORY, }; pub const PDD_ALPHABLT = fn( param0: ?*DD_BLTDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_CREATESURFACEEX = fn( param0: ?*DD_CREATESURFACEEXDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_GETDRIVERSTATE = fn( param0: ?*DD_GETDRIVERSTATEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_DESTROYDDLOCAL = fn( param0: ?*DD_DESTROYDDLOCALDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DD_MISCELLANEOUS2CALLBACKS = extern struct { dwSize: u32, dwFlags: u32, AlphaBlt: ?PDD_ALPHABLT, CreateSurfaceEx: ?PDD_CREATESURFACEEX, GetDriverState: ?PDD_GETDRIVERSTATE, DestroyDDLocal: ?PDD_DESTROYDDLOCAL, }; pub const PDD_FREEDRIVERMEMORY = fn( param0: ?*DD_FREEDRIVERMEMORYDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_SETEXCLUSIVEMODE = fn( param0: ?*DD_SETEXCLUSIVEMODEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_FLIPTOGDISURFACE = fn( param0: ?*DD_FLIPTOGDISURFACEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DD_NTCALLBACKS = extern struct { dwSize: u32, dwFlags: u32, FreeDriverMemory: ?PDD_FREEDRIVERMEMORY, SetExclusiveMode: ?PDD_SETEXCLUSIVEMODE, FlipToGDISurface: ?PDD_FLIPTOGDISURFACE, }; pub const PDD_PALCB_DESTROYPALETTE = fn( param0: ?*DD_DESTROYPALETTEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_PALCB_SETENTRIES = fn( param0: ?*DD_SETENTRIESDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DD_PALETTECALLBACKS = extern struct { dwSize: u32, dwFlags: u32, DestroyPalette: ?PDD_PALCB_DESTROYPALETTE, SetEntries: ?PDD_PALCB_SETENTRIES, }; pub const PDD_SURFCB_LOCK = fn( param0: ?*DD_LOCKDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_SURFCB_UNLOCK = fn( param0: ?*DD_UNLOCKDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_SURFCB_BLT = fn( param0: ?*DD_BLTDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_SURFCB_UPDATEOVERLAY = fn( param0: ?*DD_UPDATEOVERLAYDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_SURFCB_SETOVERLAYPOSITION = fn( param0: ?*DD_SETOVERLAYPOSITIONDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_SURFCB_SETPALETTE = fn( param0: ?*DD_SETPALETTEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_SURFCB_FLIP = fn( param0: ?*DD_FLIPDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_SURFCB_DESTROYSURFACE = fn( param0: ?*DD_DESTROYSURFACEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_SURFCB_SETCLIPLIST = fn( param0: ?*DD_SETCLIPLISTDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_SURFCB_ADDATTACHEDSURFACE = fn( param0: ?*DD_ADDATTACHEDSURFACEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_SURFCB_SETCOLORKEY = fn( param0: ?*DD_SETCOLORKEYDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_SURFCB_GETBLTSTATUS = fn( param0: ?*DD_GETBLTSTATUSDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_SURFCB_GETFLIPSTATUS = fn( param0: ?*DD_GETFLIPSTATUSDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DD_SURFACECALLBACKS = extern struct { dwSize: u32, dwFlags: u32, DestroySurface: ?PDD_SURFCB_DESTROYSURFACE, Flip: ?PDD_SURFCB_FLIP, SetClipList: ?PDD_SURFCB_SETCLIPLIST, Lock: ?PDD_SURFCB_LOCK, Unlock: ?PDD_SURFCB_UNLOCK, Blt: ?PDD_SURFCB_BLT, SetColorKey: ?PDD_SURFCB_SETCOLORKEY, AddAttachedSurface: ?PDD_SURFCB_ADDATTACHEDSURFACE, GetBltStatus: ?PDD_SURFCB_GETBLTSTATUS, GetFlipStatus: ?PDD_SURFCB_GETFLIPSTATUS, UpdateOverlay: ?PDD_SURFCB_UPDATEOVERLAY, SetOverlayPosition: ?PDD_SURFCB_SETOVERLAYPOSITION, reserved4: ?*anyopaque, SetPalette: ?PDD_SURFCB_SETPALETTE, }; pub const PDD_VPORTCB_CANCREATEVIDEOPORT = fn( param0: ?*DD_CANCREATEVPORTDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_CREATEVIDEOPORT = fn( param0: ?*DD_CREATEVPORTDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_FLIP = fn( param0: ?*DD_FLIPVPORTDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_GETBANDWIDTH = fn( param0: ?*DD_GETVPORTBANDWIDTHDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_GETINPUTFORMATS = fn( param0: ?*DD_GETVPORTINPUTFORMATDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_GETOUTPUTFORMATS = fn( param0: ?*DD_GETVPORTOUTPUTFORMATDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_GETAUTOFLIPSURF = fn( param0: ?*_DD_GETVPORTAUTOFLIPSURFACEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_GETFIELD = fn( param0: ?*DD_GETVPORTFIELDDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_GETLINE = fn( param0: ?*DD_GETVPORTLINEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_GETVPORTCONNECT = fn( param0: ?*DD_GETVPORTCONNECTDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_DESTROYVPORT = fn( param0: ?*DD_DESTROYVPORTDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_GETFLIPSTATUS = fn( param0: ?*DD_GETVPORTFLIPSTATUSDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_UPDATE = fn( param0: ?*DD_UPDATEVPORTDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_WAITFORSYNC = fn( param0: ?*DD_WAITFORVPORTSYNCDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_GETSIGNALSTATUS = fn( param0: ?*DD_GETVPORTSIGNALDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_VPORTCB_COLORCONTROL = fn( param0: ?*DD_VPORTCOLORDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DD_VIDEOPORTCALLBACKS = extern struct { dwSize: u32, dwFlags: u32, CanCreateVideoPort: ?PDD_VPORTCB_CANCREATEVIDEOPORT, CreateVideoPort: ?PDD_VPORTCB_CREATEVIDEOPORT, FlipVideoPort: ?PDD_VPORTCB_FLIP, GetVideoPortBandwidth: ?PDD_VPORTCB_GETBANDWIDTH, GetVideoPortInputFormats: ?PDD_VPORTCB_GETINPUTFORMATS, GetVideoPortOutputFormats: ?PDD_VPORTCB_GETOUTPUTFORMATS, lpReserved1: ?*anyopaque, GetVideoPortField: ?PDD_VPORTCB_GETFIELD, GetVideoPortLine: ?PDD_VPORTCB_GETLINE, GetVideoPortConnectInfo: ?PDD_VPORTCB_GETVPORTCONNECT, DestroyVideoPort: ?PDD_VPORTCB_DESTROYVPORT, GetVideoPortFlipStatus: ?PDD_VPORTCB_GETFLIPSTATUS, UpdateVideoPort: ?PDD_VPORTCB_UPDATE, WaitForVideoPortSync: ?PDD_VPORTCB_WAITFORSYNC, GetVideoSignalStatus: ?PDD_VPORTCB_GETSIGNALSTATUS, ColorControl: ?PDD_VPORTCB_COLORCONTROL, }; pub const PDD_COLORCB_COLORCONTROL = fn( param0: ?*DD_COLORCONTROLDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DD_COLORCONTROLCALLBACKS = extern struct { dwSize: u32, dwFlags: u32, ColorControl: ?PDD_COLORCB_COLORCONTROL, }; pub const PDD_KERNELCB_SYNCSURFACE = fn( param0: ?*DD_SYNCSURFACEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_KERNELCB_SYNCVIDEOPORT = fn( param0: ?*DD_SYNCVIDEOPORTDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DD_KERNELCALLBACKS = extern struct { dwSize: u32, dwFlags: u32, SyncSurfaceData: ?PDD_KERNELCB_SYNCSURFACE, SyncVideoPortData: ?PDD_KERNELCB_SYNCVIDEOPORT, }; pub const PDD_MOCOMPCB_GETGUIDS = fn( param0: ?*DD_GETMOCOMPGUIDSDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_MOCOMPCB_GETFORMATS = fn( param0: ?*DD_GETMOCOMPFORMATSDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_MOCOMPCB_CREATE = fn( param0: ?*DD_CREATEMOCOMPDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_MOCOMPCB_GETCOMPBUFFINFO = fn( param0: ?*DD_GETMOCOMPCOMPBUFFDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_MOCOMPCB_GETINTERNALINFO = fn( param0: ?*DD_GETINTERNALMOCOMPDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_MOCOMPCB_BEGINFRAME = fn( param0: ?*DD_BEGINMOCOMPFRAMEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_MOCOMPCB_ENDFRAME = fn( param0: ?*DD_ENDMOCOMPFRAMEDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_MOCOMPCB_RENDER = fn( param0: ?*DD_RENDERMOCOMPDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_MOCOMPCB_QUERYSTATUS = fn( param0: ?*DD_QUERYMOCOMPSTATUSDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDD_MOCOMPCB_DESTROY = fn( param0: ?*DD_DESTROYMOCOMPDATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DD_MOTIONCOMPCALLBACKS = extern struct { dwSize: u32, dwFlags: u32, GetMoCompGuids: ?PDD_MOCOMPCB_GETGUIDS, GetMoCompFormats: ?PDD_MOCOMPCB_GETFORMATS, CreateMoComp: ?PDD_MOCOMPCB_CREATE, GetMoCompBuffInfo: ?PDD_MOCOMPCB_GETCOMPBUFFINFO, GetInternalMoCompInfo: ?PDD_MOCOMPCB_GETINTERNALINFO, BeginMoCompFrame: ?PDD_MOCOMPCB_BEGINFRAME, EndMoCompFrame: ?PDD_MOCOMPCB_ENDFRAME, RenderMoComp: ?PDD_MOCOMPCB_RENDER, QueryMoCompStatus: ?PDD_MOCOMPCB_QUERYSTATUS, DestroyMoComp: ?PDD_MOCOMPCB_DESTROY, }; pub const DD_NONLOCALVIDMEMCAPS = extern struct { dwSize: u32, dwNLVBCaps: u32, dwNLVBCaps2: u32, dwNLVBCKeyCaps: u32, dwNLVBFXCaps: u32, dwNLVBRops: [8]u32, }; pub const DD_PALETTE_GLOBAL = extern struct { dwReserved1: usize, }; pub const DD_PALETTE_LOCAL = extern struct { dwReserved0: u32, dwReserved1: usize, }; pub const DD_CLIPPER_GLOBAL = extern struct { dwReserved1: usize, }; pub const DD_CLIPPER_LOCAL = extern struct { dwReserved1: usize, }; pub const DD_ATTACHLIST = extern struct { lpLink: ?*DD_ATTACHLIST, lpAttached: ?*DD_SURFACE_LOCAL, }; pub const DD_SURFACE_INT = extern struct { lpLcl: ?*DD_SURFACE_LOCAL, }; pub const DD_SURFACE_GLOBAL = extern struct { Anonymous1: extern union { dwBlockSizeY: u32, lSlicePitch: i32, }, Anonymous2: extern union { lpVidMemHeap: ?*VIDEOMEMORY, dwBlockSizeX: u32, dwUserMemSize: u32, }, fpVidMem: usize, Anonymous3: extern union { lPitch: i32, dwLinearSize: u32, }, yHint: i32, xHint: i32, wHeight: u32, wWidth: u32, dwReserved1: usize, ddpfSurface: DDPIXELFORMAT, fpHeapOffset: usize, hCreatorProcess: ?HANDLE, }; pub const DD_SURFACE_MORE = extern struct { dwMipMapCount: u32, lpVideoPort: ?*DD_VIDEOPORT_LOCAL, dwOverlayFlags: u32, ddsCapsEx: DDSCAPSEX, dwSurfaceHandle: u32, }; pub const DD_SURFACE_LOCAL = extern struct { lpGbl: ?*DD_SURFACE_GLOBAL, dwFlags: u32, ddsCaps: DDSCAPS, dwReserved1: usize, Anonymous1: extern union { ddckCKSrcOverlay: DDCOLORKEY, ddckCKSrcBlt: DDCOLORKEY, }, Anonymous2: extern union { ddckCKDestOverlay: DDCOLORKEY, ddckCKDestBlt: DDCOLORKEY, }, lpSurfMore: ?*DD_SURFACE_MORE, lpAttachList: ?*DD_ATTACHLIST, lpAttachListFrom: ?*DD_ATTACHLIST, rcOverlaySrc: RECT, }; pub const DD_MORECAPS = extern struct { dwSize: u32, dwAlphaCaps: u32, dwSVBAlphaCaps: u32, dwVSBAlphaCaps: u32, dwSSBAlphaCaps: u32, dwFilterCaps: u32, dwSVBFilterCaps: u32, dwVSBFilterCaps: u32, dwSSBFilterCaps: u32, }; pub const DDNTCORECAPS = extern struct { dwSize: u32, dwCaps: u32, dwCaps2: u32, dwCKeyCaps: u32, dwFXCaps: u32, dwFXAlphaCaps: u32, dwPalCaps: u32, dwSVCaps: u32, dwAlphaBltConstBitDepths: u32, dwAlphaBltPixelBitDepths: u32, dwAlphaBltSurfaceBitDepths: u32, dwAlphaOverlayConstBitDepths: u32, dwAlphaOverlayPixelBitDepths: u32, dwAlphaOverlaySurfaceBitDepths: u32, dwZBufferBitDepths: u32, dwVidMemTotal: u32, dwVidMemFree: u32, dwMaxVisibleOverlays: u32, dwCurrVisibleOverlays: u32, dwNumFourCCCodes: u32, dwAlignBoundarySrc: u32, dwAlignSizeSrc: u32, dwAlignBoundaryDest: u32, dwAlignSizeDest: u32, dwAlignStrideAlign: u32, dwRops: [8]u32, ddsCaps: DDSCAPS, dwMinOverlayStretch: u32, dwMaxOverlayStretch: u32, dwMinLiveVideoStretch: u32, dwMaxLiveVideoStretch: u32, dwMinHwCodecStretch: u32, dwMaxHwCodecStretch: u32, dwReserved1: u32, dwReserved2: u32, dwReserved3: u32, dwSVBCaps: u32, dwSVBCKeyCaps: u32, dwSVBFXCaps: u32, dwSVBRops: [8]u32, dwVSBCaps: u32, dwVSBCKeyCaps: u32, dwVSBFXCaps: u32, dwVSBRops: [8]u32, dwSSBCaps: u32, dwSSBCKeyCaps: u32, dwSSBFXCaps: u32, dwSSBRops: [8]u32, dwMaxVideoPorts: u32, dwCurrVideoPorts: u32, dwSVBCaps2: u32, }; pub const DD_D3DBUFCALLBACKS = extern struct { dwSize: u32, dwFlags: u32, CanCreateD3DBuffer: ?PDD_CANCREATESURFACE, CreateD3DBuffer: ?PDD_CREATESURFACE, DestroyD3DBuffer: ?PDD_SURFCB_DESTROYSURFACE, LockD3DBuffer: ?PDD_SURFCB_LOCK, UnlockD3DBuffer: ?PDD_SURFCB_UNLOCK, }; pub const DD_HALINFO_V4 = extern struct { dwSize: u32, vmiData: VIDEOMEMORYINFO, ddCaps: DDNTCORECAPS, GetDriverInfo: ?PDD_GETDRIVERINFO, dwFlags: u32, }; pub const DD_HALINFO = extern struct { dwSize: u32, vmiData: VIDEOMEMORYINFO, ddCaps: DDNTCORECAPS, GetDriverInfo: ?PDD_GETDRIVERINFO, dwFlags: u32, lpD3DGlobalDriverData: ?*anyopaque, lpD3DHALCallbacks: ?*anyopaque, lpD3DBufCallbacks: ?*DD_D3DBUFCALLBACKS, }; pub const DD_DIRECTDRAW_GLOBAL = extern struct { dhpdev: ?*anyopaque, dwReserved1: usize, dwReserved2: usize, lpDDVideoPortCaps: ?*DDVIDEOPORTCAPS, }; pub const DD_DIRECTDRAW_LOCAL = extern struct { lpGbl: ?*DD_DIRECTDRAW_GLOBAL, }; pub const DD_VIDEOPORT_LOCAL = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, ddvpDesc: DDVIDEOPORTDESC, ddvpInfo: DDVIDEOPORTINFO, lpSurface: ?*DD_SURFACE_INT, lpVBISurface: ?*DD_SURFACE_INT, dwNumAutoflip: u32, dwNumVBIAutoflip: u32, dwReserved1: usize, dwReserved2: usize, dwReserved3: usize, }; pub const DD_MOTIONCOMP_LOCAL = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, guid: Guid, dwUncompWidth: u32, dwUncompHeight: u32, ddUncompPixelFormat: DDPIXELFORMAT, dwDriverReserved1: u32, dwDriverReserved2: u32, dwDriverReserved3: u32, lpDriverReserved1: ?*anyopaque, lpDriverReserved2: ?*anyopaque, lpDriverReserved3: ?*anyopaque, }; pub const DD_MORESURFACECAPS = extern struct { pub const NTExtendedHeapRestrictions = extern struct { ddsCapsEx: DDSCAPSEX, ddsCapsExAlt: DDSCAPSEX, }; dwSize: u32, ddsCapsMore: DDSCAPSEX, ddsExtendedHeapRestrictions: [1]NTExtendedHeapRestrictions, }; pub const DD_STEREOMODE = extern struct { dwSize: u32, dwHeight: u32, dwWidth: u32, dwBpp: u32, dwRefreshRate: u32, bSupported: BOOL, }; pub const DD_UPDATENONLOCALHEAPDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, dwHeap: u32, fpGARTLin: usize, fpGARTDev: usize, ulPolicyMaxBytes: usize, ddRVal: HRESULT, UpdateNonLocalHeap: ?*anyopaque, }; pub const DD_NTPRIVATEDRIVERCAPS = extern struct { dwSize: u32, dwPrivateCaps: u32, }; pub const DD_BLTDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDDestSurface: ?*DD_SURFACE_LOCAL, rDest: RECTL, lpDDSrcSurface: ?*DD_SURFACE_LOCAL, rSrc: RECTL, dwFlags: u32, dwROPFlags: u32, bltFX: DDBLTFX, ddRVal: HRESULT, Blt: ?*anyopaque, IsClipped: BOOL, rOrigDest: RECTL, rOrigSrc: RECTL, dwRectCnt: u32, prDestRects: ?*RECT, dwAFlags: u32, ddargbScaleFactors: DDARGB, }; pub const DD_LOCKDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDSurface: ?*DD_SURFACE_LOCAL, bHasRect: u32, rArea: RECTL, lpSurfData: ?*anyopaque, ddRVal: HRESULT, Lock: ?*anyopaque, dwFlags: u32, fpProcess: usize, }; pub const DD_UNLOCKDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDSurface: ?*DD_SURFACE_LOCAL, ddRVal: HRESULT, Unlock: ?*anyopaque, }; pub const DD_UPDATEOVERLAYDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDDestSurface: ?*DD_SURFACE_LOCAL, rDest: RECTL, lpDDSrcSurface: ?*DD_SURFACE_LOCAL, rSrc: RECTL, dwFlags: u32, overlayFX: DDOVERLAYFX, ddRVal: HRESULT, UpdateOverlay: ?*anyopaque, }; pub const DD_SETOVERLAYPOSITIONDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDSrcSurface: ?*DD_SURFACE_LOCAL, lpDDDestSurface: ?*DD_SURFACE_LOCAL, lXPos: i32, lYPos: i32, ddRVal: HRESULT, SetOverlayPosition: ?*anyopaque, }; pub const DD_SETPALETTEDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDSurface: ?*DD_SURFACE_LOCAL, lpDDPalette: ?*DD_PALETTE_GLOBAL, ddRVal: HRESULT, SetPalette: ?*anyopaque, Attach: BOOL, }; pub const DD_FLIPDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpSurfCurr: ?*DD_SURFACE_LOCAL, lpSurfTarg: ?*DD_SURFACE_LOCAL, dwFlags: u32, ddRVal: HRESULT, Flip: ?*anyopaque, lpSurfCurrLeft: ?*DD_SURFACE_LOCAL, lpSurfTargLeft: ?*DD_SURFACE_LOCAL, }; pub const DD_DESTROYSURFACEDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDSurface: ?*DD_SURFACE_LOCAL, ddRVal: HRESULT, DestroySurface: ?*anyopaque, }; pub const DD_SETCLIPLISTDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDSurface: ?*DD_SURFACE_LOCAL, ddRVal: HRESULT, SetClipList: ?*anyopaque, }; pub const DD_ADDATTACHEDSURFACEDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDSurface: ?*DD_SURFACE_LOCAL, lpSurfAttached: ?*DD_SURFACE_LOCAL, ddRVal: HRESULT, AddAttachedSurface: ?*anyopaque, }; pub const DD_SETCOLORKEYDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDSurface: ?*DD_SURFACE_LOCAL, dwFlags: u32, ckNew: DDCOLORKEY, ddRVal: HRESULT, SetColorKey: ?*anyopaque, }; pub const DD_GETBLTSTATUSDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDSurface: ?*DD_SURFACE_LOCAL, dwFlags: u32, ddRVal: HRESULT, GetBltStatus: ?*anyopaque, }; pub const DD_GETFLIPSTATUSDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDSurface: ?*DD_SURFACE_LOCAL, dwFlags: u32, ddRVal: HRESULT, GetFlipStatus: ?*anyopaque, }; pub const DD_DESTROYPALETTEDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDPalette: ?*DD_PALETTE_GLOBAL, ddRVal: HRESULT, DestroyPalette: ?*anyopaque, }; pub const DD_SETENTRIESDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDPalette: ?*DD_PALETTE_GLOBAL, dwBase: u32, dwNumEntries: u32, lpEntries: ?*PALETTEENTRY, ddRVal: HRESULT, SetEntries: ?*anyopaque, }; pub const DD_CREATESURFACEDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDSurfaceDesc: ?*DDSURFACEDESC, lplpSList: ?*?*DD_SURFACE_LOCAL, dwSCnt: u32, ddRVal: HRESULT, CreateSurface: ?*anyopaque, }; pub const DD_CANCREATESURFACEDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDSurfaceDesc: ?*DDSURFACEDESC, bIsDifferentPixelFormat: u32, ddRVal: HRESULT, CanCreateSurface: ?*anyopaque, }; pub const DD_CREATEPALETTEDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDPalette: ?*DD_PALETTE_GLOBAL, lpColorTable: ?*PALETTEENTRY, ddRVal: HRESULT, CreatePalette: ?*anyopaque, is_excl: BOOL, }; pub const DD_WAITFORVERTICALBLANKDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, dwFlags: u32, bIsInVB: u32, hEvent: usize, ddRVal: HRESULT, WaitForVerticalBlank: ?*anyopaque, }; pub const DD_DRVSETCOLORKEYDATA = extern struct { lpDDSurface: ?*DD_SURFACE_LOCAL, dwFlags: u32, ckNew: DDCOLORKEY, ddRVal: HRESULT, SetColorKey: ?*anyopaque, }; pub const DD_GETSCANLINEDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, dwScanLine: u32, ddRVal: HRESULT, GetScanLine: ?*anyopaque, }; pub const DD_MAPMEMORYDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, bMap: BOOL, hProcess: ?HANDLE, fpProcess: usize, ddRVal: HRESULT, }; pub const DD_CANCREATEVPORTDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpDDVideoPortDesc: ?*DDVIDEOPORTDESC, ddRVal: HRESULT, CanCreateVideoPort: ?*anyopaque, }; pub const DD_CREATEVPORTDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpDDVideoPortDesc: ?*DDVIDEOPORTDESC, lpVideoPort: ?*DD_VIDEOPORT_LOCAL, ddRVal: HRESULT, CreateVideoPort: ?*anyopaque, }; pub const DD_FLIPVPORTDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpVideoPort: ?*DD_VIDEOPORT_LOCAL, lpSurfCurr: ?*DD_SURFACE_LOCAL, lpSurfTarg: ?*DD_SURFACE_LOCAL, ddRVal: HRESULT, FlipVideoPort: ?*anyopaque, }; pub const DD_GETVPORTBANDWIDTHDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpVideoPort: ?*DD_VIDEOPORT_LOCAL, lpddpfFormat: ?*DDPIXELFORMAT, dwWidth: u32, dwHeight: u32, dwFlags: u32, lpBandwidth: ?*DDVIDEOPORTBANDWIDTH, ddRVal: HRESULT, GetVideoPortBandwidth: ?*anyopaque, }; pub const DD_GETVPORTINPUTFORMATDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpVideoPort: ?*DD_VIDEOPORT_LOCAL, dwFlags: u32, lpddpfFormat: ?*DDPIXELFORMAT, dwNumFormats: u32, ddRVal: HRESULT, GetVideoPortInputFormats: ?*anyopaque, }; pub const DD_GETVPORTOUTPUTFORMATDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpVideoPort: ?*DD_VIDEOPORT_LOCAL, dwFlags: u32, lpddpfInputFormat: ?*DDPIXELFORMAT, lpddpfOutputFormats: ?*DDPIXELFORMAT, dwNumFormats: u32, ddRVal: HRESULT, GetVideoPortInputFormats: ?*anyopaque, }; pub const DD_GETVPORTFIELDDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpVideoPort: ?*DD_VIDEOPORT_LOCAL, bField: BOOL, ddRVal: HRESULT, GetVideoPortField: ?*anyopaque, }; pub const DD_GETVPORTLINEDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpVideoPort: ?*DD_VIDEOPORT_LOCAL, dwLine: u32, ddRVal: HRESULT, GetVideoPortLine: ?*anyopaque, }; pub const DD_GETVPORTCONNECTDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, dwPortId: u32, lpConnect: ?*DDVIDEOPORTCONNECT, dwNumEntries: u32, ddRVal: HRESULT, GetVideoPortConnectInfo: ?*anyopaque, }; pub const DD_DESTROYVPORTDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpVideoPort: ?*DD_VIDEOPORT_LOCAL, ddRVal: HRESULT, DestroyVideoPort: ?*anyopaque, }; pub const DD_GETVPORTFLIPSTATUSDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, fpSurface: usize, ddRVal: HRESULT, GetVideoPortFlipStatus: ?*anyopaque, }; pub const DD_UPDATEVPORTDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpVideoPort: ?*DD_VIDEOPORT_LOCAL, lplpDDSurface: ?*?*DD_SURFACE_INT, lplpDDVBISurface: ?*?*DD_SURFACE_INT, lpVideoInfo: ?*DDVIDEOPORTINFO, dwFlags: u32, dwNumAutoflip: u32, dwNumVBIAutoflip: u32, ddRVal: HRESULT, UpdateVideoPort: ?*anyopaque, }; pub const DD_WAITFORVPORTSYNCDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpVideoPort: ?*DD_VIDEOPORT_LOCAL, dwFlags: u32, dwLine: u32, dwTimeOut: u32, ddRVal: HRESULT, UpdateVideoPort: ?*anyopaque, }; pub const DD_GETVPORTSIGNALDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpVideoPort: ?*DD_VIDEOPORT_LOCAL, dwStatus: u32, ddRVal: HRESULT, GetVideoSignalStatus: ?*anyopaque, }; pub const DD_VPORTCOLORDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpVideoPort: ?*DD_VIDEOPORT_LOCAL, dwFlags: u32, lpColorData: ?*DDCOLORCONTROL, ddRVal: HRESULT, ColorControl: ?*anyopaque, }; pub const DD_COLORCONTROLDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDSurface: ?*DD_SURFACE_LOCAL, lpColorData: ?*DDCOLORCONTROL, dwFlags: u32, ddRVal: HRESULT, ColorControl: ?*anyopaque, }; pub const DD_GETDRIVERINFODATA = extern struct { dhpdev: ?*anyopaque, dwSize: u32, dwFlags: u32, guidInfo: Guid, dwExpectedSize: u32, lpvData: ?*anyopaque, dwActualSize: u32, ddRVal: HRESULT, }; pub const DD_GETAVAILDRIVERMEMORYDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, DDSCaps: DDSCAPS, dwTotal: u32, dwFree: u32, ddRVal: HRESULT, GetAvailDriverMemory: ?*anyopaque, }; pub const DD_FREEDRIVERMEMORYDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, lpDDSurface: ?*DD_SURFACE_LOCAL, ddRVal: HRESULT, FreeDriverMemory: ?*anyopaque, }; pub const DD_SETEXCLUSIVEMODEDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, dwEnterExcl: u32, dwReserved: u32, ddRVal: HRESULT, SetExclusiveMode: ?*anyopaque, }; pub const DD_FLIPTOGDISURFACEDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_GLOBAL, dwToGDI: u32, dwReserved: u32, ddRVal: HRESULT, FlipToGDISurface: ?*anyopaque, }; pub const DD_SYNCSURFACEDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpDDSurface: ?*DD_SURFACE_LOCAL, dwSurfaceOffset: u32, fpLockPtr: usize, lPitch: i32, dwOverlayOffset: u32, dwDriverReserved1: u32, dwDriverReserved2: u32, dwDriverReserved3: u32, dwDriverReserved4: u32, ddRVal: HRESULT, }; pub const DD_SYNCVIDEOPORTDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpVideoPort: ?*DD_VIDEOPORT_LOCAL, dwOriginOffset: u32, dwHeight: u32, dwVBIHeight: u32, dwDriverReserved1: u32, dwDriverReserved2: u32, dwDriverReserved3: u32, ddRVal: HRESULT, }; pub const DD_GETMOCOMPGUIDSDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, dwNumGuids: u32, lpGuids: ?*Guid, ddRVal: HRESULT, }; pub const DD_GETMOCOMPFORMATSDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpGuid: ?*Guid, dwNumFormats: u32, lpFormats: ?*DDPIXELFORMAT, ddRVal: HRESULT, }; pub const DD_CREATEMOCOMPDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpMoComp: ?*DD_MOTIONCOMP_LOCAL, lpGuid: ?*Guid, dwUncompWidth: u32, dwUncompHeight: u32, ddUncompPixelFormat: DDPIXELFORMAT, lpData: ?*anyopaque, dwDataSize: u32, ddRVal: HRESULT, }; pub const DDCOMPBUFFERINFO = extern struct { dwSize: u32, dwNumCompBuffers: u32, dwWidthToCreate: u32, dwHeightToCreate: u32, dwBytesToAllocate: u32, ddCompCaps: DDSCAPS2, ddPixelFormat: DDPIXELFORMAT, }; pub const DD_GETMOCOMPCOMPBUFFDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpGuid: ?*Guid, dwWidth: u32, dwHeight: u32, ddPixelFormat: DDPIXELFORMAT, dwNumTypesCompBuffs: u32, lpCompBuffInfo: ?*DDCOMPBUFFERINFO, ddRVal: HRESULT, }; pub const DD_GETINTERNALMOCOMPDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpGuid: ?*Guid, dwWidth: u32, dwHeight: u32, ddPixelFormat: DDPIXELFORMAT, dwScratchMemAlloc: u32, ddRVal: HRESULT, }; pub const DD_BEGINMOCOMPFRAMEDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpMoComp: ?*DD_MOTIONCOMP_LOCAL, lpDestSurface: ?*DD_SURFACE_LOCAL, dwInputDataSize: u32, lpInputData: ?*anyopaque, dwOutputDataSize: u32, lpOutputData: ?*anyopaque, ddRVal: HRESULT, }; pub const DD_ENDMOCOMPFRAMEDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpMoComp: ?*DD_MOTIONCOMP_LOCAL, lpInputData: ?*anyopaque, dwInputDataSize: u32, ddRVal: HRESULT, }; pub const DDMOCOMPBUFFERINFO = extern struct { dwSize: u32, lpCompSurface: ?*DD_SURFACE_LOCAL, dwDataOffset: u32, dwDataSize: u32, lpPrivate: ?*anyopaque, }; pub const DD_RENDERMOCOMPDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpMoComp: ?*DD_MOTIONCOMP_LOCAL, dwNumBuffers: u32, lpBufferInfo: ?*DDMOCOMPBUFFERINFO, dwFunction: u32, lpInputData: ?*anyopaque, dwInputDataSize: u32, lpOutputData: ?*anyopaque, dwOutputDataSize: u32, ddRVal: HRESULT, }; pub const DD_QUERYMOCOMPSTATUSDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpMoComp: ?*DD_MOTIONCOMP_LOCAL, lpSurface: ?*DD_SURFACE_LOCAL, dwFlags: u32, ddRVal: HRESULT, }; pub const DD_DESTROYMOCOMPDATA = extern struct { lpDD: ?*DD_DIRECTDRAW_LOCAL, lpMoComp: ?*DD_MOTIONCOMP_LOCAL, ddRVal: HRESULT, }; pub const DD_CREATESURFACEEXDATA = extern struct { dwFlags: u32, lpDDLcl: ?*DD_DIRECTDRAW_LOCAL, lpDDSLcl: ?*DD_SURFACE_LOCAL, ddRVal: HRESULT, }; pub const DD_GETDRIVERSTATEDATA = extern struct { dwFlags: u32, Anonymous: extern union { lpDD: ?*DD_DIRECTDRAW_GLOBAL, dwhContext: usize, }, lpdwStates: ?*u32, dwLength: u32, ddRVal: HRESULT, }; pub const DD_DESTROYDDLOCALDATA = extern struct { dwFlags: u32, pDDLcl: ?*DD_DIRECTDRAW_LOCAL, ddRVal: HRESULT, }; pub const MDL = extern struct { pub const _EPROCESS = extern struct { placeholder: usize, // TODO: why is this type empty? }; MdlNext: ?*MDL, MdlSize: i16, MdlFlags: i16, Process: ?*_EPROCESS, lpMappedSystemVa: ?*u32, lpStartVa: ?*u32, ByteCount: u32, ByteOffset: u32, }; pub const DDSURFACEDATA = extern struct { ddsCaps: u32, dwSurfaceOffset: u32, fpLockPtr: usize, dwWidth: u32, dwHeight: u32, lPitch: i32, dwOverlayFlags: u32, dwOverlayOffset: u32, dwOverlaySrcWidth: u32, dwOverlaySrcHeight: u32, dwOverlayDestWidth: u32, dwOverlayDestHeight: u32, dwVideoPortId: u32, dwFormatFlags: u32, dwFormatFourCC: u32, dwFormatBitCount: u32, dwRBitMask: u32, dwGBitMask: u32, dwBBitMask: u32, dwDriverReserved1: u32, dwDriverReserved2: u32, dwDriverReserved3: u32, dwDriverReserved4: u32, }; pub const DDVIDEOPORTDATA = extern struct { dwVideoPortId: u32, dwVPFlags: u32, dwOriginOffset: u32, dwHeight: u32, dwVBIHeight: u32, dwDriverReserved1: u32, dwDriverReserved2: u32, dwDriverReserved3: u32, }; pub const DX_IRQDATA = extern struct { dwIrqFlags: u32, }; pub const PDX_IRQCALLBACK = fn( pIrqData: ?*DX_IRQDATA, ) callconv(@import("std").os.windows.WINAPI) void; pub const DDGETIRQINFO = extern struct { dwFlags: u32, }; pub const DDENABLEIRQINFO = extern struct { dwIRQSources: u32, dwLine: u32, IRQCallback: ?PDX_IRQCALLBACK, lpIRQData: ?*DX_IRQDATA, }; pub const DDSKIPNEXTFIELDINFO = extern struct { lpVideoPortData: ?*DDVIDEOPORTDATA, dwSkipFlags: u32, }; pub const DDBOBNEXTFIELDINFO = extern struct { lpSurface: ?*DDSURFACEDATA, }; pub const DDSETSTATEININFO = extern struct { lpSurfaceData: ?*DDSURFACEDATA, lpVideoPortData: ?*DDVIDEOPORTDATA, }; pub const DDSETSTATEOUTINFO = extern struct { bSoftwareAutoflip: BOOL, dwSurfaceIndex: u32, dwVBISurfaceIndex: u32, }; pub const DDLOCKININFO = extern struct { lpSurfaceData: ?*DDSURFACEDATA, }; pub const DDLOCKOUTINFO = extern struct { dwSurfacePtr: usize, }; pub const DDFLIPOVERLAYINFO = extern struct { lpCurrentSurface: ?*DDSURFACEDATA, lpTargetSurface: ?*DDSURFACEDATA, dwFlags: u32, }; pub const DDFLIPVIDEOPORTINFO = extern struct { lpVideoPortData: ?*DDVIDEOPORTDATA, lpCurrentSurface: ?*DDSURFACEDATA, lpTargetSurface: ?*DDSURFACEDATA, dwFlipVPFlags: u32, }; pub const DDGETPOLARITYININFO = extern struct { lpVideoPortData: ?*DDVIDEOPORTDATA, }; pub const DDGETPOLARITYOUTINFO = extern struct { bPolarity: u32, }; pub const DDGETCURRENTAUTOFLIPININFO = extern struct { lpVideoPortData: ?*DDVIDEOPORTDATA, }; pub const DDGETCURRENTAUTOFLIPOUTINFO = extern struct { dwSurfaceIndex: u32, dwVBISurfaceIndex: u32, }; pub const DDGETPREVIOUSAUTOFLIPININFO = extern struct { lpVideoPortData: ?*DDVIDEOPORTDATA, }; pub const DDGETPREVIOUSAUTOFLIPOUTINFO = extern struct { dwSurfaceIndex: u32, dwVBISurfaceIndex: u32, }; pub const DDTRANSFERININFO = extern struct { lpSurfaceData: ?*DDSURFACEDATA, dwStartLine: u32, dwEndLine: u32, dwTransferID: usize, dwTransferFlags: u32, lpDestMDL: ?*MDL, }; pub const DDTRANSFEROUTINFO = extern struct { dwBufferPolarity: u32, }; pub const DDGETTRANSFERSTATUSOUTINFO = extern struct { dwTransferID: usize, }; pub const PDX_GETIRQINFO = fn( param0: ?*anyopaque, param1: ?*anyopaque, param2: ?*DDGETIRQINFO, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDX_ENABLEIRQ = fn( param0: ?*anyopaque, param1: ?*DDENABLEIRQINFO, param2: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDX_SKIPNEXTFIELD = fn( param0: ?*anyopaque, param1: ?*DDSKIPNEXTFIELDINFO, param2: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDX_BOBNEXTFIELD = fn( param0: ?*anyopaque, param1: ?*DDBOBNEXTFIELDINFO, param2: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDX_SETSTATE = fn( param0: ?*anyopaque, param1: ?*DDSETSTATEININFO, param2: ?*DDSETSTATEOUTINFO, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDX_LOCK = fn( param0: ?*anyopaque, param1: ?*DDLOCKININFO, param2: ?*DDLOCKOUTINFO, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDX_FLIPOVERLAY = fn( param0: ?*anyopaque, param1: ?*DDFLIPOVERLAYINFO, param2: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDX_FLIPVIDEOPORT = fn( param0: ?*anyopaque, param1: ?*DDFLIPVIDEOPORTINFO, param2: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDX_GETPOLARITY = fn( param0: ?*anyopaque, param1: ?*DDGETPOLARITYININFO, param2: ?*DDGETPOLARITYOUTINFO, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDX_GETCURRENTAUTOFLIP = fn( param0: ?*anyopaque, param1: ?*DDGETCURRENTAUTOFLIPININFO, param2: ?*DDGETCURRENTAUTOFLIPOUTINFO, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDX_GETPREVIOUSAUTOFLIP = fn( param0: ?*anyopaque, param1: ?*DDGETPREVIOUSAUTOFLIPININFO, param2: ?*DDGETPREVIOUSAUTOFLIPOUTINFO, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDX_TRANSFER = fn( param0: ?*anyopaque, param1: ?*DDTRANSFERININFO, param2: ?*DDTRANSFEROUTINFO, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PDX_GETTRANSFERSTATUS = fn( param0: ?*anyopaque, param1: ?*anyopaque, param2: ?*DDGETTRANSFERSTATUSOUTINFO, ) callconv(@import("std").os.windows.WINAPI) u32; pub const DXAPI_INTERFACE = extern struct { Size: u16, Version: u16, Context: ?*anyopaque, InterfaceReference: ?*anyopaque, InterfaceDereference: ?*anyopaque, DxGetIrqInfo: ?PDX_GETIRQINFO, DxEnableIrq: ?PDX_ENABLEIRQ, DxSkipNextField: ?PDX_SKIPNEXTFIELD, DxBobNextField: ?PDX_BOBNEXTFIELD, DxSetState: ?PDX_SETSTATE, DxLock: ?PDX_LOCK, DxFlipOverlay: ?PDX_FLIPOVERLAY, DxFlipVideoPort: ?PDX_FLIPVIDEOPORT, DxGetPolarity: ?PDX_GETPOLARITY, DxGetCurrentAutoflip: ?PDX_GETCURRENTAUTOFLIP, DxGetPreviousAutoflip: ?PDX_GETPREVIOUSAUTOFLIP, DxTransfer: ?PDX_TRANSFER, DxGetTransferStatus: ?PDX_GETTRANSFERSTATUS, }; //-------------------------------------------------------------------------------- // Section: Functions (7) //-------------------------------------------------------------------------------- pub extern "DDRAW" fn DirectDrawEnumerateW( lpCallback: ?LPDDENUMCALLBACKW, lpContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "DDRAW" fn DirectDrawEnumerateA( lpCallback: ?LPDDENUMCALLBACKA, lpContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "DDRAW" fn DirectDrawEnumerateExW( lpCallback: ?LPDDENUMCALLBACKEXW, lpContext: ?*anyopaque, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "DDRAW" fn DirectDrawEnumerateExA( lpCallback: ?LPDDENUMCALLBACKEXA, lpContext: ?*anyopaque, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "DDRAW" fn DirectDrawCreate( lpGUID: ?*Guid, lplpDD: ?*?*IDirectDraw, pUnkOuter: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "DDRAW" fn DirectDrawCreateEx( lpGuid: ?*Guid, lplpDD: ?*?*anyopaque, iid: ?*const Guid, pUnkOuter: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "DDRAW" fn DirectDrawCreateClipper( dwFlags: u32, lplpDDClipper: ?*?*IDirectDrawClipper, pUnkOuter: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (5) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { pub const LPDDENUMCALLBACK = thismodule.LPDDENUMCALLBACKA; pub const LPDDENUMCALLBACKEX = thismodule.LPDDENUMCALLBACKEXA; pub const LPDIRECTDRAWENUMERATEEX = thismodule.LPDIRECTDRAWENUMERATEEXA; pub const DirectDrawEnumerate = thismodule.DirectDrawEnumerateA; pub const DirectDrawEnumerateEx = thismodule.DirectDrawEnumerateExA; }, .wide => struct { pub const LPDDENUMCALLBACK = thismodule.LPDDENUMCALLBACKW; pub const LPDDENUMCALLBACKEX = thismodule.LPDDENUMCALLBACKEXW; pub const LPDIRECTDRAWENUMERATEEX = thismodule.LPDIRECTDRAWENUMERATEEXW; pub const DirectDrawEnumerate = thismodule.DirectDrawEnumerateW; pub const DirectDrawEnumerateEx = thismodule.DirectDrawEnumerateExW; }, .unspecified => if (@import("builtin").is_test) struct { pub const LPDDENUMCALLBACK = *opaque{}; pub const LPDDENUMCALLBACKEX = *opaque{}; pub const LPDIRECTDRAWENUMERATEEX = *opaque{}; pub const DirectDrawEnumerate = *opaque{}; pub const DirectDrawEnumerateEx = *opaque{}; } else struct { pub const LPDDENUMCALLBACK = @compileError("'LPDDENUMCALLBACK' requires that UNICODE be set to true or false in the root module"); pub const LPDDENUMCALLBACKEX = @compileError("'LPDDENUMCALLBACKEX' requires that UNICODE be set to true or false in the root module"); pub const LPDIRECTDRAWENUMERATEEX = @compileError("'LPDIRECTDRAWENUMERATEEX' requires that UNICODE be set to true or false in the root module"); pub const DirectDrawEnumerate = @compileError("'DirectDrawEnumerate' requires that UNICODE be set to true or false in the root module"); pub const DirectDrawEnumerateEx = @compileError("'DirectDrawEnumerateEx' requires that UNICODE be set to true or false in the root module"); }, }; //-------------------------------------------------------------------------------- // Section: Imports (19) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const CHAR = @import("../foundation.zig").CHAR; const HANDLE = @import("../foundation.zig").HANDLE; const HDC = @import("../graphics/gdi.zig").HDC; const HINSTANCE = @import("../foundation.zig").HINSTANCE; const HMONITOR = @import("../graphics/gdi.zig").HMONITOR; const HPALETTE = @import("../graphics/gdi.zig").HPALETTE; const HRESULT = @import("../foundation.zig").HRESULT; const HWND = @import("../foundation.zig").HWND; const IUnknown = @import("../system/com.zig").IUnknown; const LARGE_INTEGER = @import("../foundation.zig").LARGE_INTEGER; const PALETTEENTRY = @import("../graphics/gdi.zig").PALETTEENTRY; const PSTR = @import("../foundation.zig").PSTR; const PWSTR = @import("../foundation.zig").PWSTR; const RECT = @import("../foundation.zig").RECT; const RECTL = @import("../foundation.zig").RECTL; const RGNDATA = @import("../graphics/gdi.zig").RGNDATA; const SIZE = @import("../foundation.zig").SIZE; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "LPDDENUMCALLBACKA")) { _ = LPDDENUMCALLBACKA; } if (@hasDecl(@This(), "LPDDENUMCALLBACKW")) { _ = LPDDENUMCALLBACKW; } if (@hasDecl(@This(), "LPDDENUMCALLBACKEXA")) { _ = LPDDENUMCALLBACKEXA; } if (@hasDecl(@This(), "LPDDENUMCALLBACKEXW")) { _ = LPDDENUMCALLBACKEXW; } if (@hasDecl(@This(), "LPDIRECTDRAWENUMERATEEXA")) { _ = LPDIRECTDRAWENUMERATEEXA; } if (@hasDecl(@This(), "LPDIRECTDRAWENUMERATEEXW")) { _ = LPDIRECTDRAWENUMERATEEXW; } if (@hasDecl(@This(), "LPDDENUMMODESCALLBACK")) { _ = LPDDENUMMODESCALLBACK; } if (@hasDecl(@This(), "LPDDENUMMODESCALLBACK2")) { _ = LPDDENUMMODESCALLBACK2; } if (@hasDecl(@This(), "LPDDENUMSURFACESCALLBACK")) { _ = LPDDENUMSURFACESCALLBACK; } if (@hasDecl(@This(), "LPDDENUMSURFACESCALLBACK2")) { _ = LPDDENUMSURFACESCALLBACK2; } if (@hasDecl(@This(), "LPDDENUMSURFACESCALLBACK7")) { _ = LPDDENUMSURFACESCALLBACK7; } if (@hasDecl(@This(), "LPCLIPPERCALLBACK")) { _ = LPCLIPPERCALLBACK; } if (@hasDecl(@This(), "LPDDENUMVIDEOCALLBACK")) { _ = LPDDENUMVIDEOCALLBACK; } if (@hasDecl(@This(), "LPDD32BITDRIVERINIT")) { _ = LPDD32BITDRIVERINIT; } if (@hasDecl(@This(), "LPDDHEL_INIT")) { _ = LPDDHEL_INIT; } if (@hasDecl(@This(), "LPDDHAL_SETCOLORKEY")) { _ = LPDDHAL_SETCOLORKEY; } if (@hasDecl(@This(), "LPDDHAL_CANCREATESURFACE")) { _ = LPDDHAL_CANCREATESURFACE; } if (@hasDecl(@This(), "LPDDHAL_CREATESURFACE")) { _ = LPDDHAL_CREATESURFACE; } if (@hasDecl(@This(), "LPDDHAL_DESTROYDRIVER")) { _ = LPDDHAL_DESTROYDRIVER; } if (@hasDecl(@This(), "LPDDHAL_SETMODE")) { _ = LPDDHAL_SETMODE; } if (@hasDecl(@This(), "LPDDHAL_CREATEPALETTE")) { _ = LPDDHAL_CREATEPALETTE; } if (@hasDecl(@This(), "LPDDHAL_GETSCANLINE")) { _ = LPDDHAL_GETSCANLINE; } if (@hasDecl(@This(), "LPDDHAL_SETEXCLUSIVEMODE")) { _ = LPDDHAL_SETEXCLUSIVEMODE; } if (@hasDecl(@This(), "LPDDHAL_FLIPTOGDISURFACE")) { _ = LPDDHAL_FLIPTOGDISURFACE; } if (@hasDecl(@This(), "LPDDHAL_GETDRIVERINFO")) { _ = LPDDHAL_GETDRIVERINFO; } if (@hasDecl(@This(), "LPDDHALPALCB_DESTROYPALETTE")) { _ = LPDDHALPALCB_DESTROYPALETTE; } if (@hasDecl(@This(), "LPDDHALPALCB_SETENTRIES")) { _ = LPDDHALPALCB_SETENTRIES; } if (@hasDecl(@This(), "LPDDHALSURFCB_LOCK")) { _ = LPDDHALSURFCB_LOCK; } if (@hasDecl(@This(), "LPDDHALSURFCB_UNLOCK")) { _ = LPDDHALSURFCB_UNLOCK; } if (@hasDecl(@This(), "LPDDHALSURFCB_BLT")) { _ = LPDDHALSURFCB_BLT; } if (@hasDecl(@This(), "LPDDHALSURFCB_UPDATEOVERLAY")) { _ = LPDDHALSURFCB_UPDATEOVERLAY; } if (@hasDecl(@This(), "LPDDHALSURFCB_SETOVERLAYPOSITION")) { _ = LPDDHALSURFCB_SETOVERLAYPOSITION; } if (@hasDecl(@This(), "LPDDHALSURFCB_SETPALETTE")) { _ = LPDDHALSURFCB_SETPALETTE; } if (@hasDecl(@This(), "LPDDHALSURFCB_FLIP")) { _ = LPDDHALSURFCB_FLIP; } if (@hasDecl(@This(), "LPDDHALSURFCB_DESTROYSURFACE")) { _ = LPDDHALSURFCB_DESTROYSURFACE; } if (@hasDecl(@This(), "LPDDHALSURFCB_SETCLIPLIST")) { _ = LPDDHALSURFCB_SETCLIPLIST; } if (@hasDecl(@This(), "LPDDHALSURFCB_ADDATTACHEDSURFACE")) { _ = LPDDHALSURFCB_ADDATTACHEDSURFACE; } if (@hasDecl(@This(), "LPDDHALSURFCB_SETCOLORKEY")) { _ = LPDDHALSURFCB_SETCOLORKEY; } if (@hasDecl(@This(), "LPDDHALSURFCB_GETBLTSTATUS")) { _ = LPDDHALSURFCB_GETBLTSTATUS; } if (@hasDecl(@This(), "LPDDHALSURFCB_GETFLIPSTATUS")) { _ = LPDDHALSURFCB_GETFLIPSTATUS; } if (@hasDecl(@This(), "LPDDHAL_GETAVAILDRIVERMEMORY")) { _ = LPDDHAL_GETAVAILDRIVERMEMORY; } if (@hasDecl(@This(), "LPDDHAL_UPDATENONLOCALHEAP")) { _ = LPDDHAL_UPDATENONLOCALHEAP; } if (@hasDecl(@This(), "LPDDHAL_GETHEAPALIGNMENT")) { _ = LPDDHAL_GETHEAPALIGNMENT; } if (@hasDecl(@This(), "LPDDHAL_CREATESURFACEEX")) { _ = LPDDHAL_CREATESURFACEEX; } if (@hasDecl(@This(), "LPDDHAL_GETDRIVERSTATE")) { _ = LPDDHAL_GETDRIVERSTATE; } if (@hasDecl(@This(), "LPDDHAL_DESTROYDDLOCAL")) { _ = LPDDHAL_DESTROYDDLOCAL; } if (@hasDecl(@This(), "LPDDHALEXEBUFCB_CANCREATEEXEBUF")) { _ = LPDDHALEXEBUFCB_CANCREATEEXEBUF; } if (@hasDecl(@This(), "LPDDHALEXEBUFCB_CREATEEXEBUF")) { _ = LPDDHALEXEBUFCB_CREATEEXEBUF; } if (@hasDecl(@This(), "LPDDHALEXEBUFCB_DESTROYEXEBUF")) { _ = LPDDHALEXEBUFCB_DESTROYEXEBUF; } if (@hasDecl(@This(), "LPDDHALEXEBUFCB_LOCKEXEBUF")) { _ = LPDDHALEXEBUFCB_LOCKEXEBUF; } if (@hasDecl(@This(), "LPDDHALEXEBUFCB_UNLOCKEXEBUF")) { _ = LPDDHALEXEBUFCB_UNLOCKEXEBUF; } if (@hasDecl(@This(), "LPDDHALVPORTCB_CANCREATEVIDEOPORT")) { _ = LPDDHALVPORTCB_CANCREATEVIDEOPORT; } if (@hasDecl(@This(), "LPDDHALVPORTCB_CREATEVIDEOPORT")) { _ = LPDDHALVPORTCB_CREATEVIDEOPORT; } if (@hasDecl(@This(), "LPDDHALVPORTCB_FLIP")) { _ = LPDDHALVPORTCB_FLIP; } if (@hasDecl(@This(), "LPDDHALVPORTCB_GETBANDWIDTH")) { _ = LPDDHALVPORTCB_GETBANDWIDTH; } if (@hasDecl(@This(), "LPDDHALVPORTCB_GETINPUTFORMATS")) { _ = LPDDHALVPORTCB_GETINPUTFORMATS; } if (@hasDecl(@This(), "LPDDHALVPORTCB_GETOUTPUTFORMATS")) { _ = LPDDHALVPORTCB_GETOUTPUTFORMATS; } if (@hasDecl(@This(), "LPDDHALVPORTCB_GETFIELD")) { _ = LPDDHALVPORTCB_GETFIELD; } if (@hasDecl(@This(), "LPDDHALVPORTCB_GETLINE")) { _ = LPDDHALVPORTCB_GETLINE; } if (@hasDecl(@This(), "LPDDHALVPORTCB_GETVPORTCONNECT")) { _ = LPDDHALVPORTCB_GETVPORTCONNECT; } if (@hasDecl(@This(), "LPDDHALVPORTCB_DESTROYVPORT")) { _ = LPDDHALVPORTCB_DESTROYVPORT; } if (@hasDecl(@This(), "LPDDHALVPORTCB_GETFLIPSTATUS")) { _ = LPDDHALVPORTCB_GETFLIPSTATUS; } if (@hasDecl(@This(), "LPDDHALVPORTCB_UPDATE")) { _ = LPDDHALVPORTCB_UPDATE; } if (@hasDecl(@This(), "LPDDHALVPORTCB_WAITFORSYNC")) { _ = LPDDHALVPORTCB_WAITFORSYNC; } if (@hasDecl(@This(), "LPDDHALVPORTCB_GETSIGNALSTATUS")) { _ = LPDDHALVPORTCB_GETSIGNALSTATUS; } if (@hasDecl(@This(), "LPDDHALVPORTCB_COLORCONTROL")) { _ = LPDDHALVPORTCB_COLORCONTROL; } if (@hasDecl(@This(), "LPDDHALCOLORCB_COLORCONTROL")) { _ = LPDDHALCOLORCB_COLORCONTROL; } if (@hasDecl(@This(), "LPDDHALKERNELCB_SYNCSURFACE")) { _ = LPDDHALKERNELCB_SYNCSURFACE; } if (@hasDecl(@This(), "LPDDHALKERNELCB_SYNCVIDEOPORT")) { _ = LPDDHALKERNELCB_SYNCVIDEOPORT; } if (@hasDecl(@This(), "LPDDGAMMACALIBRATORPROC")) { _ = LPDDGAMMACALIBRATORPROC; } if (@hasDecl(@This(), "LPDDHALMOCOMPCB_GETGUIDS")) { _ = LPDDHALMOCOMPCB_GETGUIDS; } if (@hasDecl(@This(), "LPDDHALMOCOMPCB_GETFORMATS")) { _ = LPDDHALMOCOMPCB_GETFORMATS; } if (@hasDecl(@This(), "LPDDHALMOCOMPCB_CREATE")) { _ = LPDDHALMOCOMPCB_CREATE; } if (@hasDecl(@This(), "LPDDHALMOCOMPCB_GETCOMPBUFFINFO")) { _ = LPDDHALMOCOMPCB_GETCOMPBUFFINFO; } if (@hasDecl(@This(), "LPDDHALMOCOMPCB_GETINTERNALINFO")) { _ = LPDDHALMOCOMPCB_GETINTERNALINFO; } if (@hasDecl(@This(), "LPDDHALMOCOMPCB_BEGINFRAME")) { _ = LPDDHALMOCOMPCB_BEGINFRAME; } if (@hasDecl(@This(), "LPDDHALMOCOMPCB_ENDFRAME")) { _ = LPDDHALMOCOMPCB_ENDFRAME; } if (@hasDecl(@This(), "LPDDHALMOCOMPCB_RENDER")) { _ = LPDDHALMOCOMPCB_RENDER; } if (@hasDecl(@This(), "LPDDHALMOCOMPCB_QUERYSTATUS")) { _ = LPDDHALMOCOMPCB_QUERYSTATUS; } if (@hasDecl(@This(), "LPDDHALMOCOMPCB_DESTROY")) { _ = LPDDHALMOCOMPCB_DESTROY; } if (@hasDecl(@This(), "LPDDHAL_SETINFO")) { _ = LPDDHAL_SETINFO; } if (@hasDecl(@This(), "LPDDHAL_VIDMEMALLOC")) { _ = LPDDHAL_VIDMEMALLOC; } if (@hasDecl(@This(), "LPDDHAL_VIDMEMFREE")) { _ = LPDDHAL_VIDMEMFREE; } if (@hasDecl(@This(), "PDD_SETCOLORKEY")) { _ = PDD_SETCOLORKEY; } if (@hasDecl(@This(), "PDD_CANCREATESURFACE")) { _ = PDD_CANCREATESURFACE; } if (@hasDecl(@This(), "PDD_WAITFORVERTICALBLANK")) { _ = PDD_WAITFORVERTICALBLANK; } if (@hasDecl(@This(), "PDD_CREATESURFACE")) { _ = PDD_CREATESURFACE; } if (@hasDecl(@This(), "PDD_DESTROYDRIVER")) { _ = PDD_DESTROYDRIVER; } if (@hasDecl(@This(), "PDD_SETMODE")) { _ = PDD_SETMODE; } if (@hasDecl(@This(), "PDD_CREATEPALETTE")) { _ = PDD_CREATEPALETTE; } if (@hasDecl(@This(), "PDD_GETSCANLINE")) { _ = PDD_GETSCANLINE; } if (@hasDecl(@This(), "PDD_MAPMEMORY")) { _ = PDD_MAPMEMORY; } if (@hasDecl(@This(), "PDD_GETDRIVERINFO")) { _ = PDD_GETDRIVERINFO; } if (@hasDecl(@This(), "PDD_GETAVAILDRIVERMEMORY")) { _ = PDD_GETAVAILDRIVERMEMORY; } if (@hasDecl(@This(), "PDD_ALPHABLT")) { _ = PDD_ALPHABLT; } if (@hasDecl(@This(), "PDD_CREATESURFACEEX")) { _ = PDD_CREATESURFACEEX; } if (@hasDecl(@This(), "PDD_GETDRIVERSTATE")) { _ = PDD_GETDRIVERSTATE; } if (@hasDecl(@This(), "PDD_DESTROYDDLOCAL")) { _ = PDD_DESTROYDDLOCAL; } if (@hasDecl(@This(), "PDD_FREEDRIVERMEMORY")) { _ = PDD_FREEDRIVERMEMORY; } if (@hasDecl(@This(), "PDD_SETEXCLUSIVEMODE")) { _ = PDD_SETEXCLUSIVEMODE; } if (@hasDecl(@This(), "PDD_FLIPTOGDISURFACE")) { _ = PDD_FLIPTOGDISURFACE; } if (@hasDecl(@This(), "PDD_PALCB_DESTROYPALETTE")) { _ = PDD_PALCB_DESTROYPALETTE; } if (@hasDecl(@This(), "PDD_PALCB_SETENTRIES")) { _ = PDD_PALCB_SETENTRIES; } if (@hasDecl(@This(), "PDD_SURFCB_LOCK")) { _ = PDD_SURFCB_LOCK; } if (@hasDecl(@This(), "PDD_SURFCB_UNLOCK")) { _ = PDD_SURFCB_UNLOCK; } if (@hasDecl(@This(), "PDD_SURFCB_BLT")) { _ = PDD_SURFCB_BLT; } if (@hasDecl(@This(), "PDD_SURFCB_UPDATEOVERLAY")) { _ = PDD_SURFCB_UPDATEOVERLAY; } if (@hasDecl(@This(), "PDD_SURFCB_SETOVERLAYPOSITION")) { _ = PDD_SURFCB_SETOVERLAYPOSITION; } if (@hasDecl(@This(), "PDD_SURFCB_SETPALETTE")) { _ = PDD_SURFCB_SETPALETTE; } if (@hasDecl(@This(), "PDD_SURFCB_FLIP")) { _ = PDD_SURFCB_FLIP; } if (@hasDecl(@This(), "PDD_SURFCB_DESTROYSURFACE")) { _ = PDD_SURFCB_DESTROYSURFACE; } if (@hasDecl(@This(), "PDD_SURFCB_SETCLIPLIST")) { _ = PDD_SURFCB_SETCLIPLIST; } if (@hasDecl(@This(), "PDD_SURFCB_ADDATTACHEDSURFACE")) { _ = PDD_SURFCB_ADDATTACHEDSURFACE; } if (@hasDecl(@This(), "PDD_SURFCB_SETCOLORKEY")) { _ = PDD_SURFCB_SETCOLORKEY; } if (@hasDecl(@This(), "PDD_SURFCB_GETBLTSTATUS")) { _ = PDD_SURFCB_GETBLTSTATUS; } if (@hasDecl(@This(), "PDD_SURFCB_GETFLIPSTATUS")) { _ = PDD_SURFCB_GETFLIPSTATUS; } if (@hasDecl(@This(), "PDD_VPORTCB_CANCREATEVIDEOPORT")) { _ = PDD_VPORTCB_CANCREATEVIDEOPORT; } if (@hasDecl(@This(), "PDD_VPORTCB_CREATEVIDEOPORT")) { _ = PDD_VPORTCB_CREATEVIDEOPORT; } if (@hasDecl(@This(), "PDD_VPORTCB_FLIP")) { _ = PDD_VPORTCB_FLIP; } if (@hasDecl(@This(), "PDD_VPORTCB_GETBANDWIDTH")) { _ = PDD_VPORTCB_GETBANDWIDTH; } if (@hasDecl(@This(), "PDD_VPORTCB_GETINPUTFORMATS")) { _ = PDD_VPORTCB_GETINPUTFORMATS; } if (@hasDecl(@This(), "PDD_VPORTCB_GETOUTPUTFORMATS")) { _ = PDD_VPORTCB_GETOUTPUTFORMATS; } if (@hasDecl(@This(), "PDD_VPORTCB_GETAUTOFLIPSURF")) { _ = PDD_VPORTCB_GETAUTOFLIPSURF; } if (@hasDecl(@This(), "PDD_VPORTCB_GETFIELD")) { _ = PDD_VPORTCB_GETFIELD; } if (@hasDecl(@This(), "PDD_VPORTCB_GETLINE")) { _ = PDD_VPORTCB_GETLINE; } if (@hasDecl(@This(), "PDD_VPORTCB_GETVPORTCONNECT")) { _ = PDD_VPORTCB_GETVPORTCONNECT; } if (@hasDecl(@This(), "PDD_VPORTCB_DESTROYVPORT")) { _ = PDD_VPORTCB_DESTROYVPORT; } if (@hasDecl(@This(), "PDD_VPORTCB_GETFLIPSTATUS")) { _ = PDD_VPORTCB_GETFLIPSTATUS; } if (@hasDecl(@This(), "PDD_VPORTCB_UPDATE")) { _ = PDD_VPORTCB_UPDATE; } if (@hasDecl(@This(), "PDD_VPORTCB_WAITFORSYNC")) { _ = PDD_VPORTCB_WAITFORSYNC; } if (@hasDecl(@This(), "PDD_VPORTCB_GETSIGNALSTATUS")) { _ = PDD_VPORTCB_GETSIGNALSTATUS; } if (@hasDecl(@This(), "PDD_VPORTCB_COLORCONTROL")) { _ = PDD_VPORTCB_COLORCONTROL; } if (@hasDecl(@This(), "PDD_COLORCB_COLORCONTROL")) { _ = PDD_COLORCB_COLORCONTROL; } if (@hasDecl(@This(), "PDD_KERNELCB_SYNCSURFACE")) { _ = PDD_KERNELCB_SYNCSURFACE; } if (@hasDecl(@This(), "PDD_KERNELCB_SYNCVIDEOPORT")) { _ = PDD_KERNELCB_SYNCVIDEOPORT; } if (@hasDecl(@This(), "PDD_MOCOMPCB_GETGUIDS")) { _ = PDD_MOCOMPCB_GETGUIDS; } if (@hasDecl(@This(), "PDD_MOCOMPCB_GETFORMATS")) { _ = PDD_MOCOMPCB_GETFORMATS; } if (@hasDecl(@This(), "PDD_MOCOMPCB_CREATE")) { _ = PDD_MOCOMPCB_CREATE; } if (@hasDecl(@This(), "PDD_MOCOMPCB_GETCOMPBUFFINFO")) { _ = PDD_MOCOMPCB_GETCOMPBUFFINFO; } if (@hasDecl(@This(), "PDD_MOCOMPCB_GETINTERNALINFO")) { _ = PDD_MOCOMPCB_GETINTERNALINFO; } if (@hasDecl(@This(), "PDD_MOCOMPCB_BEGINFRAME")) { _ = PDD_MOCOMPCB_BEGINFRAME; } if (@hasDecl(@This(), "PDD_MOCOMPCB_ENDFRAME")) { _ = PDD_MOCOMPCB_ENDFRAME; } if (@hasDecl(@This(), "PDD_MOCOMPCB_RENDER")) { _ = PDD_MOCOMPCB_RENDER; } if (@hasDecl(@This(), "PDD_MOCOMPCB_QUERYSTATUS")) { _ = PDD_MOCOMPCB_QUERYSTATUS; } if (@hasDecl(@This(), "PDD_MOCOMPCB_DESTROY")) { _ = PDD_MOCOMPCB_DESTROY; } if (@hasDecl(@This(), "PDX_IRQCALLBACK")) { _ = PDX_IRQCALLBACK; } if (@hasDecl(@This(), "PDX_GETIRQINFO")) { _ = PDX_GETIRQINFO; } if (@hasDecl(@This(), "PDX_ENABLEIRQ")) { _ = PDX_ENABLEIRQ; } if (@hasDecl(@This(), "PDX_SKIPNEXTFIELD")) { _ = PDX_SKIPNEXTFIELD; } if (@hasDecl(@This(), "PDX_BOBNEXTFIELD")) { _ = PDX_BOBNEXTFIELD; } if (@hasDecl(@This(), "PDX_SETSTATE")) { _ = PDX_SETSTATE; } if (@hasDecl(@This(), "PDX_LOCK")) { _ = PDX_LOCK; } if (@hasDecl(@This(), "PDX_FLIPOVERLAY")) { _ = PDX_FLIPOVERLAY; } if (@hasDecl(@This(), "PDX_FLIPVIDEOPORT")) { _ = PDX_FLIPVIDEOPORT; } if (@hasDecl(@This(), "PDX_GETPOLARITY")) { _ = PDX_GETPOLARITY; } if (@hasDecl(@This(), "PDX_GETCURRENTAUTOFLIP")) { _ = PDX_GETCURRENTAUTOFLIP; } if (@hasDecl(@This(), "PDX_GETPREVIOUSAUTOFLIP")) { _ = PDX_GETPREVIOUSAUTOFLIP; } if (@hasDecl(@This(), "PDX_TRANSFER")) { _ = PDX_TRANSFER; } if (@hasDecl(@This(), "PDX_GETTRANSFERSTATUS")) { _ = PDX_GETTRANSFERSTATUS; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
win32/graphics/direct_draw.zig
const std = @import("std"); const assert = std.debug.assert; const mem = std.mem; const config = @import("../config.zig"); const vsr = @import("../vsr.zig"); const Header = vsr.Header; const RingBuffer = @import("../ring_buffer.zig").RingBuffer; const Message = @import("../message_pool.zig").MessagePool.Message; const log = std.log.scoped(.client); pub fn Client(comptime StateMachine: type, comptime MessageBus: type) type { return struct { const Self = @This(); pub const Error = error{ TooManyOutstandingRequests, }; const Request = struct { const Callback = fn ( user_data: u128, operation: StateMachine.Operation, results: Error![]const u8, ) void; user_data: u128, callback: Callback, message: *Message, }; allocator: *mem.Allocator, message_bus: *MessageBus, /// A universally unique identifier for the client (must not be zero). /// Used for routing replies back to the client via any network path (multi-path routing). /// The client ID must be ephemeral and random per process, and never persisted, so that /// lingering or zombie deployment processes cannot break correctness and/or liveness. /// A cryptographic random number generator must be used to ensure these properties. id: u128, /// The identifier for the cluster that this client intends to communicate with. cluster: u32, /// The number of replicas in the cluster. replica_count: u8, /// The total number of ticks elapsed since the client was initialized. ticks: u64 = 0, /// We hash-chain request/reply checksums to verify linearizability within a client session: /// * so that the parent of the next request is the checksum of the latest reply, and /// * so that the parent of the next reply is the checksum of the latest request. parent: u128 = 0, /// The session number for the client, zero when registering a session, non-zero thereafter. session: u64 = 0, /// The request number of the next request. request_number: u32 = 0, /// The highest view number seen by the client in messages exchanged with the cluster. /// Used to locate the current leader, and provide more information to a partitioned leader. view: u32 = 0, /// A client is allowed at most one inflight request at a time at the protocol layer. /// We therefore queue any further concurrent requests made by the application layer. /// We must leave one message free to receive with. request_queue: RingBuffer(Request, config.message_bus_messages_max - 1) = .{}, /// The number of ticks without a reply before the client resends the inflight request. /// Dynamically adjusted as a function of recent request round-trip time. request_timeout: vsr.Timeout, /// The number of ticks before the client broadcasts a ping to the cluster. /// Used for end-to-end keepalive, and to discover a new leader between requests. ping_timeout: vsr.Timeout, /// Used to calculate exponential backoff with random jitter. /// Seeded with the client's ID. prng: std.rand.DefaultPrng, pub fn init( allocator: *mem.Allocator, id: u128, cluster: u32, replica_count: u8, message_bus: *MessageBus, ) !Self { assert(id > 0); assert(replica_count > 0); var self = Self{ .allocator = allocator, .message_bus = message_bus, .id = id, .cluster = cluster, .replica_count = replica_count, .request_timeout = .{ .name = "request_timeout", .id = id, .after = config.rtt_ticks * config.rtt_multiple, }, .ping_timeout = .{ .name = "ping_timeout", .id = id, .after = 30000 / config.tick_ms, }, .prng = std.rand.DefaultPrng.init(@truncate(u64, id)), }; self.ping_timeout.start(); return self; } pub fn deinit(self: *Self) void {} pub fn on_message(self: *Self, message: *Message) void { log.debug("{}: on_message: {}", .{ self.id, message.header }); if (message.header.invalid()) |reason| { log.debug("{}: on_message: invalid ({s})", .{ self.id, reason }); return; } if (message.header.cluster != self.cluster) { log.warn("{}: on_message: wrong cluster (cluster should be {}, not {})", .{ self.id, self.cluster, message.header.cluster, }); return; } switch (message.header.command) { .pong => self.on_pong(message), .reply => self.on_reply(message), .eviction => self.on_eviction(message), else => { log.warn("{}: on_message: ignoring misdirected {s} message", .{ self.id, @tagName(message.header.command), }); return; }, } } pub fn tick(self: *Self) void { self.ticks += 1; self.message_bus.tick(); self.ping_timeout.tick(); self.request_timeout.tick(); if (self.ping_timeout.fired()) self.on_ping_timeout(); if (self.request_timeout.fired()) self.on_request_timeout(); } pub fn request( self: *Self, user_data: u128, callback: Request.Callback, operation: StateMachine.Operation, message: *Message, message_body_size: usize, ) void { self.register(); // We will set parent, context, view and checksums only when sending for the first time: message.header.* = .{ .client = self.id, .request = self.request_number, .cluster = self.cluster, .command = .request, .operation = vsr.Operation.from(StateMachine, operation), .size = @intCast(u32, @sizeOf(Header) + message_body_size), }; assert(self.request_number > 0); self.request_number += 1; log.debug("{}: request: user_data={} request={} size={} {s}", .{ self.id, user_data, message.header.request, message.header.size, @tagName(operation), }); const was_empty = self.request_queue.empty(); self.request_queue.push(.{ .user_data = user_data, .callback = callback, .message = message.ref(), }) catch |err| switch (err) { error.NoSpaceLeft => { callback(user_data, operation, error.TooManyOutstandingRequests); return; }, }; // If the queue was empty, then there is no request inflight and we must send this one: if (was_empty) self.send_request_for_the_first_time(message); } /// Acquires a message from the message bus if one is available. pub fn get_message(self: *Self) ?*Message { return self.message_bus.get_message(); } /// Releases a message back to the message bus. pub fn unref(self: *Self, message: *Message) void { self.message_bus.unref(message); } fn on_eviction(self: *Self, eviction: *const Message) void { assert(eviction.header.command == .eviction); assert(eviction.header.cluster == self.cluster); if (eviction.header.client != self.id) { log.warn("{}: on_eviction: ignoring (wrong client={})", .{ self.id, eviction.header.client, }); return; } if (eviction.header.view < self.view) { log.debug("{}: on_eviction: ignoring (older view={})", .{ self.id, eviction.header.view, }); return; } assert(eviction.header.client == self.id); assert(eviction.header.view >= self.view); log.emerg("{}: session evicted: too many concurrent client sessions", .{self.id}); @panic("session evicted: too many concurrent client sessions"); } fn on_pong(self: *Self, pong: *const Message) void { assert(pong.header.command == .pong); assert(pong.header.cluster == self.cluster); if (pong.header.client != 0) { log.debug("{}: on_pong: ignoring (client != 0)", .{self.id}); return; } if (pong.header.view > self.view) { log.debug("{}: on_pong: newer view={}..{}", .{ self.id, self.view, pong.header.view, }); self.view = pong.header.view; } // Now that we know the view number, it's a good time to register if we haven't already: self.register(); } fn on_reply(self: *Self, reply: *Message) void { // We check these checksums again here because this is the last time we get to downgrade // a correctness bug into a liveness bug, before we return data back to the application. assert(reply.header.valid_checksum()); assert(reply.header.valid_checksum_body(reply.body())); assert(reply.header.command == .reply); if (reply.header.client != self.id) { log.debug("{}: on_reply: ignoring (wrong client={})", .{ self.id, reply.header.client, }); return; } if (self.request_queue.head_ptr()) |inflight| { if (reply.header.request < inflight.message.header.request) { log.debug("{}: on_reply: ignoring (request {} < {})", .{ self.id, reply.header.request, inflight.message.header.request, }); return; } } else { log.debug("{}: on_reply: ignoring (no inflight request)", .{self.id}); return; } const inflight = self.request_queue.pop().?; defer self.message_bus.unref(inflight.message); log.debug("{}: on_reply: user_data={} request={} size={} {s}", .{ self.id, inflight.user_data, reply.header.request, reply.header.size, @tagName(reply.header.operation.cast(StateMachine)), }); assert(reply.header.parent == self.parent); assert(reply.header.client == self.id); assert(reply.header.context == 0); assert(reply.header.request == inflight.message.header.request); assert(reply.header.cluster == self.cluster); assert(reply.header.op == reply.header.commit); assert(reply.header.operation == inflight.message.header.operation); // The checksum of this reply becomes the parent of our next request: self.parent = reply.header.checksum; if (reply.header.view > self.view) { log.debug("{}: on_reply: newer view={}..{}", .{ self.id, self.view, reply.header.view, }); self.view = reply.header.view; } self.request_timeout.stop(); if (inflight.message.header.operation == .register) { assert(self.session == 0); assert(reply.header.commit > 0); self.session = reply.header.commit; // The commit number becomes the session number. } // We must process the next request before releasing control back to the callback. // Otherwise, requests may run through send_request_for_the_first_time() more than once. if (self.request_queue.head_ptr()) |next_request| { self.send_request_for_the_first_time(next_request.message); } if (inflight.message.header.operation != .register) { inflight.callback( inflight.user_data, inflight.message.header.operation.cast(StateMachine), reply.body(), ); } } fn on_ping_timeout(self: *Self) void { self.ping_timeout.reset(); const ping = Header{ .command = .ping, .cluster = self.cluster, .client = self.id, }; // TODO If we haven't received a pong from a replica since our last ping, then back off. self.send_header_to_replicas(ping); } fn on_request_timeout(self: *Self) void { self.request_timeout.backoff(&self.prng); const message = self.request_queue.head_ptr().?.message; assert(message.header.command == .request); assert(message.header.request < self.request_number); assert(message.header.checksum == self.parent); assert(message.header.context == self.session); log.debug("{}: on_request_timeout: resending request={} checksum={}", .{ self.id, message.header.request, message.header.checksum, }); // We assume the leader is down and round-robin through the cluster: self.send_message_to_replica( @intCast(u8, (self.view + self.request_timeout.attempts) % self.replica_count), message, ); } /// The caller owns the returned message, if any, which has exactly 1 reference. fn create_message_from_header(self: *Self, header: Header) ?*Message { assert(header.client == self.id); assert(header.cluster == self.cluster); assert(header.size == @sizeOf(Header)); const message = self.message_bus.pool.get_header_only_message() orelse return null; defer self.message_bus.unref(message); message.header.* = header; message.header.set_checksum_body(message.body()); message.header.set_checksum(); return message.ref(); } /// Registers a session with the cluster for the client, if this has not yet been done. fn register(self: *Self) void { if (self.request_number > 0) return; var message = self.message_bus.get_message() orelse @panic("register: no message available to register a session with the cluster"); defer self.message_bus.unref(message); // We will set parent, context, view and checksums only when sending for the first time: message.header.* = .{ .client = self.id, .request = self.request_number, .cluster = self.cluster, .command = .request, .operation = .register, }; assert(self.request_number == 0); self.request_number += 1; log.debug("{}: register: registering a session with the cluster", .{self.id}); assert(self.request_queue.empty()); self.request_queue.push(.{ .user_data = 0, .callback = undefined, .message = message.ref(), }) catch |err| switch (err) { error.NoSpaceLeft => unreachable, // This is the first request. }; self.send_request_for_the_first_time(message); } fn send_header_to_replica(self: *Self, replica: u8, header: Header) void { const message = self.create_message_from_header(header) orelse { log.alert("{}: no header-only message available, dropping message to replica {}", .{ self.id, replica, }); return; }; defer self.message_bus.unref(message); self.send_message_to_replica(replica, message); } fn send_header_to_replicas(self: *Self, header: Header) void { const message = self.create_message_from_header(header) orelse { log.alert("{}: no header-only message available, dropping message to replicas", .{ self.id, }); return; }; defer self.message_bus.unref(message); var replica: u8 = 0; while (replica < self.replica_count) : (replica += 1) { self.send_message_to_replica(replica, message); } } fn send_message_to_replica(self: *Self, replica: u8, message: *Message) void { log.debug("{}: sending {s} to replica {}: {}", .{ self.id, @tagName(message.header.command), replica, message.header, }); assert(replica < self.replica_count); assert(message.header.valid_checksum()); assert(message.header.client == self.id); assert(message.header.cluster == self.cluster); self.message_bus.send_message_to_replica(replica, message); } fn send_request_for_the_first_time(self: *Self, message: *Message) void { assert(self.request_queue.head_ptr().?.message == message); assert(message.header.command == .request); assert(message.header.parent == 0); assert(message.header.context == 0); assert(message.header.request < self.request_number); assert(message.header.view == 0); assert(message.header.size <= config.message_size_max); // We set the message checksums only when sending the request for the first time, // which is when we have the checksum of the latest reply available to set as `parent`, // and similarly also the session number if requests were queued while registering: message.header.parent = self.parent; message.header.context = self.session; // We also try to include our highest view number, so we wait until the request is ready // to be sent for the first time. However, beyond that, it is not necessary to update // the view number again, for example if it should change between now and resending. message.header.view = self.view; message.header.set_checksum_body(message.body()); message.header.set_checksum(); // The checksum of this request becomes the parent of our next reply: self.parent = message.header.checksum; log.debug("{}: send_request_for_the_first_time: request={} checksum={}", .{ self.id, message.header.request, message.header.checksum, }); assert(!self.request_timeout.ticking); self.request_timeout.start(); // If our view number is out of date, then the old leader will forward our request. // If the leader is offline, then our request timeout will fire and we will round-robin. self.send_message_to_replica(@intCast(u8, self.view % self.replica_count), message); } }; }
src/vsr/client.zig
const std = @import("std"); const c = @cImport({ @cInclude("termios.h"); @cInclude("unistd.h"); @cInclude("stdlib.h"); @cInclude("ctype.h"); @cInclude("sys/ioctl.h"); }); var orig_termios: c.struct_termios = undefined; fn disableRawMode() void { if (c.tcsetattr(c.STDIN_FILENO, c.TCSAFLUSH, &orig_termios) != 0 ) { std.debug.warn("Couldn't reset terminal settings. Restart the terminal \n", .{}); std.os.exit(1); } } fn enableRawMode() void { if (c.tcgetattr(c.STDIN_FILENO, &orig_termios) != 0) { std.debug.warn("This terminal doesn't support ANSI raw mode\n", .{}); std.os.exit(1); } var raw: c.struct_termios = orig_termios; const ICRNL: c_uint = c.ICRNL; const IXON: c_uint = c.IXON; const OPOST: c_uint = c.OPOST; const ECHO: c_uint = c.ECHO; const ICANON: c_uint = c.ICANON; const IEXTEN: c_uint = c.IEXTEN; raw.c_iflag &= ~(ICRNL | IXON); raw.c_oflag &= ~(OPOST); raw.c_lflag &= ~(ECHO | ICANON | IEXTEN); // uncomment if you want ctrl+c and ctrl+z be ignored const ISIG: c_uint = c.ISIG; raw.c_lflag &= ~(ISIG); // non-blocking reads raw.c_cc[c.VMIN] = 0; raw.c_cc[c.VTIME] = 0; if ( c.tcsetattr(c.STDIN_FILENO, c.TCSAFLUSH, &raw) != 0) { std.debug.warn("This terminal doesn't support ANSI raw mode\n", .{}); std.os.exit(1); } } // about 1 mb buffer var buffer: [1000 * 1000]u8 = undefined; var bufferLen: u32 = 0; pub fn addToBuffer( chars: [:0]const u8 ) void { for (chars) |char| { buffer[bufferLen] = char; bufferLen+=1; } } pub fn flushBuffer( ) void { if (bufferLen == 0) return; _ = c.write(c.STDOUT_FILENO, &buffer[0], @intCast(c_ulong, bufferLen)); bufferLen = 0; } pub const Color = enum(u8) { default = 9, black = 0, red, green, yellow, blue, purple, lightblue, white }; pub const Style = enum(u8) { default, bold, faint, italic, underlined, blinking }; pub fn setTextColor( color: Color ) void { var cmd = "\x1b[3.m".*; cmd[3] = @enumToInt(color)+'0'; addToBuffer(&cmd); } pub fn setBackgroundColor( color: Color ) void { var cmd = "\x1b[4.m".*; cmd[3] = @enumToInt(color)+'0'; addToBuffer(&cmd); } pub fn setTextStyle( style: Style ) void { var cmd = "\x1b[.m".*; cmd[2] = @enumToInt(style)+'0'; addToBuffer(&cmd); } pub fn makeCursorVisible() void { addToBuffer("\x1b[?25h"); } pub fn makeCursorInvisible() void { addToBuffer("\x1b[?25l"); } pub fn setCursorPosition(x: u8, y: u8) void { var cmd = "\x1b[...;...H".*; cmd[2] = y/100 + '0'; cmd[3] = y%100/10 + '0'; cmd[4] = y%10 + '0'; cmd[6] = x/100 + '0'; cmd[7] = x%100/10 + '0'; cmd[8] = x%10 + '0'; addToBuffer(&cmd); } pub fn init () void { // save cursor position std.debug.print("\x1b7", .{} ); // enter altern screen std.debug.print("\x1b[?47h", .{}); // clear screen std.debug.print("\x1b[2J\x1b[3J", .{}); // move to 1,1 std.debug.print("\x1b[1;1H", .{}); enableRawMode(); } pub fn deinit() void { // clear screen std.debug.print("\x1b[2J\x1b[3J", .{}); // leave altern screen std.debug.print("\x1b[?47l", .{}); // restore cursor position std.debug.print("\x1b8", .{}); // make cursor visible std.debug.print("\x1b[?25h", .{}); disableRawMode(); } pub fn clearScreen() void { addToBuffer("\x1b[2J\x1b[3J"); } pub const Event = packed enum(u8) { UP=251, DOWN, RIGHT, LEFT, BACKSPACE=8, TAB, ENTER, CTRL_C=3, DELETE=127, SPACE=32, ESC=27, _, }; // event queue. implemented as an array ring buffer var evQu: [1000 * 1000]Event = undefined; var evQuLen: u32 = 0; var evQuCur: u32 = 0; const evQuError = error { Full, Empty }; fn pushEvent(ev: Event) !void { if (evQuLen >= evQu.len) return evQuError.Full; var indToPush: usize = evQuCur + evQuLen; if (indToPush >= evQu.len ) { indToPush %= evQu.len; } evQu[ indToPush ] = ev; evQuLen += 1; } pub fn popEvent( ) !Event { if (evQuLen == 0) return evQuError.Empty; var evToReturn = evQu[ evQuCur ]; evQuCur += 1; if ( evQuCur == evQu.len ) { evQuCur = 0; } evQuLen -= 1; return evToReturn; } pub fn populateEvents() !void { const r = std.io.getStdIn().reader(); var ch: u8 = undefined; outer: while( true) { ch = r.readByte() catch { return; }; while(true) { if (ch != 27) { // 'escape' try pushEvent(@intToEnum(Event, ch)); continue :outer; } ch = r.readByte() catch { try pushEvent(Event.ESC); return; }; if (ch != '[') { try pushEvent(Event.ESC); continue; } break; } ch = r.readByte() catch { try pushEvent(@intToEnum(Event, '[')); return; }; if (ch == 65) { try pushEvent(Event.UP); } else if (ch == 66) { try pushEvent(Event.DOWN); } else if (ch == 67) { try pushEvent(Event.RIGHT); } else if (ch == 68) { try pushEvent(Event.LEFT); } else { try pushEvent(Event.ESC); try pushEvent(@intToEnum(Event, '[')); try pushEvent(@intToEnum(Event, ch)); } } }
libterm.zig
const uefi = @import("std").os.uefi; const Guid = uefi.Guid; /// Character output devices pub const SimpleTextOutputProtocol = extern struct { _reset: extern fn (*const SimpleTextOutputProtocol, bool) usize, _output_string: extern fn (*const SimpleTextOutputProtocol, [*:0]const u16) usize, _test_string: extern fn (*const SimpleTextOutputProtocol, [*:0]const u16) usize, _query_mode: extern fn (*const SimpleTextOutputProtocol, usize, *usize, *usize) usize, _set_mode: extern fn (*const SimpleTextOutputProtocol, usize) usize, _set_attribute: extern fn (*const SimpleTextOutputProtocol, usize) usize, _clear_screen: extern fn (*const SimpleTextOutputProtocol) usize, _set_cursor_position: extern fn (*const SimpleTextOutputProtocol, usize, usize) usize, _enable_cursor: extern fn (*const SimpleTextOutputProtocol, bool) usize, mode: *SimpleTextOutputMode, /// Resets the text output device hardware. pub fn reset(self: *const SimpleTextOutputProtocol, verify: bool) usize { return self._reset(self, verify); } /// Writes a string to the output device. pub fn outputString(self: *const SimpleTextOutputProtocol, msg: [*:0]const u16) usize { return self._output_string(self, msg); } /// Verifies that all characters in a string can be output to the target device. pub fn testString(self: *const SimpleTextOutputProtocol, msg: [*:0]const u16) usize { return self._test_string(self, msg); } /// Returns information for an available text mode that the output device(s) supports. pub fn queryMode(self: *const SimpleTextOutputProtocol, mode_number: usize, columns: *usize, rows: *usize) usize { return self._query_mode(self, mode_number, columns, rows); } /// Sets the output device(s) to a specified mode. pub fn setMode(self: *const SimpleTextOutputProtocol, mode_number: usize) usize { return self._set_mode(self, mode_number); } /// Sets the background and foreground colors for the outputString() and clearScreen() functions. pub fn setAttribute(self: *const SimpleTextOutputProtocol, attribute: usize) usize { return self._set_attribute(self, attribute); } /// Clears the output device(s) display to the currently selected background color. pub fn clearScreen(self: *const SimpleTextOutputProtocol) usize { return self._clear_screen(self); } /// Sets the current coordinates of the cursor position. pub fn setCursorPosition(self: *const SimpleTextOutputProtocol, column: usize, row: usize) usize { return self._set_cursor_position(self, column, row); } /// Makes the cursor visible or invisible. pub fn enableCursor(self: *const SimpleTextOutputProtocol, visible: bool) usize { return self._enable_cursor(self, visible); } pub const guid align(8) = Guid{ .time_low = 0x387477c2, .time_mid = 0x69c7, .time_high_and_version = 0x11d2, .clock_seq_high_and_reserved = 0x8e, .clock_seq_low = 0x39, .node = [_]u8{ 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b }, }; pub const boxdraw_horizontal: u16 = 0x2500; pub const boxdraw_vertical: u16 = 0x2502; pub const boxdraw_down_right: u16 = 0x250c; pub const boxdraw_down_left: u16 = 0x2510; pub const boxdraw_up_right: u16 = 0x2514; pub const boxdraw_up_left: u16 = 0x2518; pub const boxdraw_vertical_right: u16 = 0x251c; pub const boxdraw_vertical_left: u16 = 0x2524; pub const boxdraw_down_horizontal: u16 = 0x252c; pub const boxdraw_up_horizontal: u16 = 0x2534; pub const boxdraw_vertical_horizontal: u16 = 0x253c; pub const boxdraw_double_horizontal: u16 = 0x2550; pub const boxdraw_double_vertical: u16 = 0x2551; pub const boxdraw_down_right_double: u16 = 0x2552; pub const boxdraw_down_double_right: u16 = 0x2553; pub const boxdraw_double_down_right: u16 = 0x2554; pub const boxdraw_down_left_double: u16 = 0x2555; pub const boxdraw_down_double_left: u16 = 0x2556; pub const boxdraw_double_down_left: u16 = 0x2557; pub const boxdraw_up_right_double: u16 = 0x2558; pub const boxdraw_up_double_right: u16 = 0x2559; pub const boxdraw_double_up_right: u16 = 0x255a; pub const boxdraw_up_left_double: u16 = 0x255b; pub const boxdraw_up_double_left: u16 = 0x255c; pub const boxdraw_double_up_left: u16 = 0x255d; pub const boxdraw_vertical_right_double: u16 = 0x255e; pub const boxdraw_vertical_double_right: u16 = 0x255f; pub const boxdraw_double_vertical_right: u16 = 0x2560; pub const boxdraw_vertical_left_double: u16 = 0x2561; pub const boxdraw_vertical_double_left: u16 = 0x2562; pub const boxdraw_double_vertical_left: u16 = 0x2563; pub const boxdraw_down_horizontal_double: u16 = 0x2564; pub const boxdraw_down_double_horizontal: u16 = 0x2565; pub const boxdraw_double_down_horizontal: u16 = 0x2566; pub const boxdraw_up_horizontal_double: u16 = 0x2567; pub const boxdraw_up_double_horizontal: u16 = 0x2568; pub const boxdraw_double_up_horizontal: u16 = 0x2569; pub const boxdraw_vertical_horizontal_double: u16 = 0x256a; pub const boxdraw_vertical_double_horizontal: u16 = 0x256b; pub const boxdraw_double_vertical_horizontal: u16 = 0x256c; pub const blockelement_full_block: u16 = 0x2588; pub const blockelement_light_shade: u16 = 0x2591; pub const geometricshape_up_triangle: u16 = 0x25b2; pub const geometricshape_right_triangle: u16 = 0x25ba; pub const geometricshape_down_triangle: u16 = 0x25bc; pub const geometricshape_left_triangle: u16 = 0x25c4; pub const arrow_up: u16 = 0x2591; pub const arrow_down: u16 = 0x2593; pub const black: u8 = 0x00; pub const blue: u8 = 0x01; pub const green: u8 = 0x02; pub const cyan: u8 = 0x03; pub const red: u8 = 0x04; pub const magenta: u8 = 0x05; pub const brown: u8 = 0x06; pub const lightgray: u8 = 0x07; pub const bright: u8 = 0x08; pub const darkgray: u8 = 0x08; pub const lightblue: u8 = 0x09; pub const lightgreen: u8 = 0x0a; pub const lightcyan: u8 = 0x0b; pub const lightred: u8 = 0x0c; pub const lightmagenta: u8 = 0x0d; pub const yellow: u8 = 0x0e; pub const white: u8 = 0x0f; pub const background_black: u8 = 0x00; pub const background_blue: u8 = 0x10; pub const background_green: u8 = 0x20; pub const background_cyan: u8 = 0x30; pub const background_red: u8 = 0x40; pub const background_magenta: u8 = 0x50; pub const background_brown: u8 = 0x60; pub const background_lightgray: u8 = 0x70; }; pub const SimpleTextOutputMode = extern struct { max_mode: u32, // specified as signed mode: u32, // specified as signed attribute: i32, cursor_column: i32, cursor_row: i32, cursor_visible: bool, };
lib/std/os/uefi/protocols/simple_text_output_protocol.zig
const std = @import("std"); const StringHashMap = std.StringHashMap; const Allocator = std.mem.Allocator; const FnMeta = std.builtin.TypeInfo.Fn; const FnDecl = std.builtin.TypeInfo.Declaration.Data.FnDecl; const StructMeta = std.builtin.TypeInfo.Struct; const EnumMeta = std.builtin.TypeInfo.Enum; const UnionMeta = std.builtin.TypeInfo.Union; const Dir = std.fs.Dir; const DepsGraph = @import("../deps_graph.zig").DepsGraph; const rt = @import("../runtime.zig"); const SymbolDeclaration = union(enum) { Struct: rt.TypeInfo.Struct, Union: rt.TypeInfo.Union, Enum: rt.TypeInfo.Enum, Fn: rt.TypeInfo.Fn, pub fn deinit(self: SymbolDeclaration, allocator: *Allocator) void { switch (self) { .Struct => |s| s.deinit(allocator), .Union => |u| u.deinit(allocator), .Enum => |e| e.deinit(allocator), .Fn => |f| f.deinit(allocator), } } }; fn isSymbolDependency(comptime symbol_type: type) bool { const info = @typeInfo(symbol_type); return switch (info) { .Struct, .Union, .Enum => true, .Pointer => |p| isSymbolDependency(p.child), .Array => |a| isSymbolDependency(a.child), else => false, }; } fn getTypeName(comptime T: type) []const u8 { comptime const type_info = @typeInfo(T); return switch (type_info) { .Pointer => |p| getTypeName(p.child), .Array => |p| getTypeName(p.child), else => @typeName(T), }; } pub const SymbolPhase = enum { Signature, Body, Full }; pub fn Ordered_Generator(comptime Generator: type) type { return struct { inner_gen: Generator, allocator: *Allocator, symbols: DepsGraph(SymbolDeclaration), emitted_phase: StringHashMap(SymbolPhase), const Self = @This(); pub fn init(comptime src_file: []const u8, dst_dir: *Dir) Self { var allocator = std.heap.page_allocator; return Self{ .inner_gen = Generator.init(src_file, dst_dir), .allocator = allocator, .symbols = DepsGraph(SymbolDeclaration).init(allocator), .emitted_phase = StringHashMap(SymbolPhase).init(allocator), }; } pub fn deinit(self: *Self) void { self.flush(); self.symbols.deinit(); self.inner_gen.deinit(); self.emitted_phase.deinit(); } fn getNextPhaseFor(self: *Self, symbol_name: []const u8, partial: bool) !?SymbolPhase { var result = try self.emitted_phase.getOrPut(symbol_name); if (!result.found_existing) { result.entry.value = if (partial) .Signature else .Full; return result.entry.value; } else if (result.entry.value == .Signature) { if (partial) { return null; } else { result.entry.value = .Full; return .Body; } } return null; } fn flush(self: *Self) void { while (self.symbols.readEmitted()) |emitted| { const partial = if (emitted.symbol.payload == .Fn) false else emitted.partial; var phase = self.getNextPhaseFor(emitted.symbol.name, emitted.partial) catch unreachable orelse continue; switch (emitted.symbol.payload) { .Struct => |meta| self.inner_gen.gen_struct(emitted.symbol.name, meta, phase), .Union => |meta| self.inner_gen.gen_union(emitted.symbol.name, meta, phase), .Enum => |meta| self.inner_gen.gen_enum(emitted.symbol.name, meta, phase), .Fn => |meta| self.inner_gen.gen_func(emitted.symbol.name, meta), } } } pub fn gen_func(self: *Self, comptime name: []const u8, comptime meta: FnMeta) void { comptime const decl: SymbolDeclaration = SymbolDeclaration{ .Fn = rt.TypeInfo.Fn.init(meta), }; self.symbols.beginSymbol(name, decl) catch |err| @panic(@errorName(err)); inline for (meta.args) |f| { if (f.arg_type != null and comptime isSymbolDependency(f.arg_type.?)) { self.symbols.addDependency(getTypeName(f.arg_type.?)) catch |err| @panic(@errorName(err)); } } if (meta.return_type) |t| { if (comptime isSymbolDependency(t)) { self.symbols.addDependency(getTypeName(t)) catch |err| @panic(@errorName(err)); } } self.symbols.endSymbol() catch |err| @panic(@errorName(err)); self.flush(); } pub fn gen_struct(self: *Self, comptime name: []const u8, comptime meta: StructMeta) void { comptime const decl: SymbolDeclaration = SymbolDeclaration{ .Struct = rt.TypeInfo.Struct.init(meta, name), }; self.symbols.beginSymbol(name, decl) catch |err| @panic(@errorName(err)); inline for (meta.fields) |f| { if (comptime isSymbolDependency(f.field_type)) { self.symbols.addDependency(getTypeName(f.field_type)) catch |err| @panic(@errorName(err)); } } self.symbols.endSymbol() catch |err| @panic(@errorName(err)); self.flush(); } pub fn gen_enum(self: *Self, comptime name: []const u8, comptime meta: EnumMeta) void { comptime const decl: SymbolDeclaration = SymbolDeclaration{ .Enum = rt.TypeInfo.Enum.init(meta, name), }; self.symbols.beginSymbol(name, decl) catch |err| @panic(@errorName(err)); // Enums have no type dependencies I think, yay self.symbols.endSymbol() catch |err| @panic(@errorName(err)); self.flush(); } pub fn gen_union(self: *Self, comptime name: []const u8, comptime meta: UnionMeta) void { comptime const decl: SymbolDeclaration = SymbolDeclaration{ .Union = rt.TypeInfo.Union.init(meta, name), }; self.symbols.beginSymbol(name, decl) catch |err| @panic(@errorName(err)); inline for (meta.fields) |f| { if (comptime isSymbolDependency(f.field_type)) { self.symbols.addDependency(getTypeName(f.field_type)) catch |err| @panic(@errorName(err)); } } self.symbols.endSymbol() catch |err| @panic(@errorName(err)); self.flush(); } }; }
src/generators/ordered.zig
usingnamespace @import("bits.zig"); pub extern "NtDll" fn RtlGetVersion( lpVersionInformation: PRTL_OSVERSIONINFOW, ) callconv(WINAPI) NTSTATUS; pub extern "NtDll" fn RtlCaptureStackBackTrace( FramesToSkip: DWORD, FramesToCapture: DWORD, BackTrace: **c_void, BackTraceHash: ?*DWORD, ) callconv(WINAPI) WORD; pub extern "NtDll" fn NtQueryInformationFile( FileHandle: HANDLE, IoStatusBlock: *IO_STATUS_BLOCK, FileInformation: *c_void, Length: ULONG, FileInformationClass: FILE_INFORMATION_CLASS, ) callconv(WINAPI) NTSTATUS; pub extern "NtDll" fn NtSetInformationFile( FileHandle: HANDLE, IoStatusBlock: *IO_STATUS_BLOCK, FileInformation: PVOID, Length: ULONG, FileInformationClass: FILE_INFORMATION_CLASS, ) callconv(WINAPI) NTSTATUS; pub extern "NtDll" fn NtQueryAttributesFile( ObjectAttributes: *OBJECT_ATTRIBUTES, FileAttributes: *FILE_BASIC_INFORMATION, ) callconv(WINAPI) NTSTATUS; pub extern "NtDll" fn NtCreateFile( FileHandle: *HANDLE, DesiredAccess: ACCESS_MASK, ObjectAttributes: *OBJECT_ATTRIBUTES, IoStatusBlock: *IO_STATUS_BLOCK, AllocationSize: ?*LARGE_INTEGER, FileAttributes: ULONG, ShareAccess: ULONG, CreateDisposition: ULONG, CreateOptions: ULONG, EaBuffer: ?*c_void, EaLength: ULONG, ) callconv(WINAPI) NTSTATUS; pub extern "NtDll" fn NtDeviceIoControlFile( FileHandle: HANDLE, Event: ?HANDLE, ApcRoutine: ?IO_APC_ROUTINE, ApcContext: ?*c_void, IoStatusBlock: *IO_STATUS_BLOCK, IoControlCode: ULONG, InputBuffer: ?*const c_void, InputBufferLength: ULONG, OutputBuffer: ?PVOID, OutputBufferLength: ULONG, ) callconv(WINAPI) NTSTATUS; pub extern "NtDll" fn NtFsControlFile( FileHandle: HANDLE, Event: ?HANDLE, ApcRoutine: ?IO_APC_ROUTINE, ApcContext: ?*c_void, IoStatusBlock: *IO_STATUS_BLOCK, FsControlCode: ULONG, InputBuffer: ?*const c_void, InputBufferLength: ULONG, OutputBuffer: ?PVOID, OutputBufferLength: ULONG, ) callconv(WINAPI) NTSTATUS; pub extern "NtDll" fn NtClose(Handle: HANDLE) callconv(WINAPI) NTSTATUS; pub extern "NtDll" fn RtlDosPathNameToNtPathName_U( DosPathName: [*:0]const u16, NtPathName: *UNICODE_STRING, NtFileNamePart: ?*?[*:0]const u16, DirectoryInfo: ?*CURDIR, ) callconv(WINAPI) BOOL; pub extern "NtDll" fn RtlFreeUnicodeString(UnicodeString: *UNICODE_STRING) callconv(WINAPI) void; pub extern "NtDll" fn NtQueryDirectoryFile( FileHandle: HANDLE, Event: ?HANDLE, ApcRoutine: ?IO_APC_ROUTINE, ApcContext: ?*c_void, IoStatusBlock: *IO_STATUS_BLOCK, FileInformation: *c_void, Length: ULONG, FileInformationClass: FILE_INFORMATION_CLASS, ReturnSingleEntry: BOOLEAN, FileName: ?*UNICODE_STRING, RestartScan: BOOLEAN, ) callconv(WINAPI) NTSTATUS; pub extern "NtDll" fn NtCreateKeyedEvent( KeyedEventHandle: *HANDLE, DesiredAccess: ACCESS_MASK, ObjectAttributes: ?PVOID, Flags: ULONG, ) callconv(WINAPI) NTSTATUS; pub extern "NtDll" fn NtReleaseKeyedEvent( EventHandle: HANDLE, Key: *const c_void, Alertable: BOOLEAN, Timeout: ?*LARGE_INTEGER, ) callconv(WINAPI) NTSTATUS; pub extern "NtDll" fn NtWaitForKeyedEvent( EventHandle: HANDLE, Key: *const c_void, Alertable: BOOLEAN, Timeout: ?*LARGE_INTEGER, ) callconv(WINAPI) NTSTATUS; pub extern "NtDll" fn RtlSetCurrentDirectory_U(PathName: *UNICODE_STRING) callconv(WINAPI) NTSTATUS; pub extern "NtDll" fn NtQueryObject( Handle: HANDLE, ObjectInformationClass: OBJECT_INFORMATION_CLASS, ObjectInformation: PVOID, ObjectInformationLength: ULONG, ReturnLength: ?*ULONG, ) callconv(WINAPI) NTSTATUS;
lib/std/os/windows/ntdll.zig
const std = @import("std"); const super = @import("../index.zig"); const native = @import("../native.zig"); const HGLRC = HANDLE; const PROC = *@OpaqueType(); const GLenum = u32; const GLboolean = bool; const GLbitfield = u32; const GLbyte = i8; const GLshort = i16; const GLint = i32; const GLsizei = i32; const GLubyte = u8; const GLushort = u16; const GLuint = u32; const GLfloat = f32; const GLclampf = f32; const GLdouble = f64; const GLclampd = f64; const GLvoid = *c_void; // opengl function pointers const PFNGLARRAYELEMENTEXTPROC = ?stdcallcc fn (GLint) void; const PFNGLDRAWARRAYSEXTPROC = ?stdcallcc fn (GLenum, GLint, GLsizei) void; const PFNGLVERTEXPOINTEREXTPROC = ?stdcallcc fn (GLint, GLenum, GLsizei, GLsizei, ?*const GLvoid) void; const PFNGLNORMALPOINTEREXTPROC = ?stdcallcc fn (GLenum, GLsizei, GLsizei, ?*const GLvoid) void; const PFNGLCOLORPOINTEREXTPROC = ?stdcallcc fn (GLint, GLenum, GLsizei, GLsizei, ?*const GLvoid) void; const PFNGLINDEXPOINTEREXTPROC = ?stdcallcc fn (GLenum, GLsizei, GLsizei, ?*const GLvoid) void; const PFNGLTEXCOORDPOINTEREXTPROC = ?stdcallcc fn (GLint, GLenum, GLsizei, GLsizei, ?*const GLvoid) void; const PFNGLEDGEFLAGPOINTEREXTPROC = ?stdcallcc fn (GLsizei, GLsizei, ?*const GLboolean) void; const PFNGLGETPOINTERVEXTPROC = ?stdcallcc fn (GLenum, ?*(?*GLvoid)) void; const PFNGLARRAYELEMENTARRAYEXTPROC = ?stdcallcc fn (GLenum, GLsizei, ?*const GLvoid) void; const PFNGLDRAWRANGEELEMENTSWINPROC = ?stdcallcc fn (GLenum, GLuint, GLuint, GLsizei, GLenum, ?*const GLvoid) void; const PFNGLADDSWAPHINTRECTWINPROC = ?stdcallcc fn (GLint, GLint, GLsizei, GLsizei) void; const PFNGLCOLORTABLEEXTPROC = ?stdcallcc fn (GLenum, GLenum, GLsizei, GLenum, GLenum, ?*const GLvoid) void; const PFNGLCOLORSUBTABLEEXTPROC = ?stdcallcc fn (GLenum, GLsizei, GLsizei, GLenum, GLenum, ?*const GLvoid) void; const PFNGLGETCOLORTABLEEXTPROC = ?stdcallcc fn (GLenum, GLenum, GLenum, ?*GLvoid) void; const PFNGLGETCOLORTABLEPARAMETERIVEXTPROC = ?stdcallcc fn (GLenum, GLenum, ?*GLint) void; const PFNGLGETCOLORTABLEPARAMETERFVEXTPROC = ?stdcallcc fn (GLenum, GLenum, ?*GLfloat) void; // wgl extentions const PFNWGLCREATECONTEXTATTRIBSARBPROC = ?stdcallcc fn (HDC, HGLRC, ?*const c_int) HGLRC; const PFNWGLCHOOSEPIXELFORMATARBPROC = ?stdcallcc fn (HDC, ?*const c_int, ?*const FLOAT, UINT, ?*c_int, ?*UINT) BOOL; const PIXELFORMATDESCRIPTOR = extern struct { nSize: WORD, nVersion: WORD, dwFlags: DWORD, iPixelType: BYTE, cColorBits: BYTE, cRedBits: BYTE, cRedShift: BYTE, cGreenBits: BYTE, cGreenShift: BYTE, cBlueBits: BYTE, cBlueShift: BYTE, cAlphaBits: BYTE, cAlphaShift: BYTE, cAccumBits: BYTE, cAccumRedBits: BYTE, cAccumGreenBits: BYTE, cAccumBlueBits: BYTE, cAccumAlphaBits: BYTE, cDepthBits: BYTE, cStencilBits: BYTE, cAuxBuffers: BYTE, iLayerType: BYTE, bReserved: BYTE, dwLayerMask: DWORD, dwVisibleMask: DWORD, dwDamageMask: DWORD, }; extern "gdi32" stdcallcc fn StretchDIBits(hdc: HDC, xDest: c_int, yDest: c_int, DestWidth: c_int, DestHeight: c_int, xSrc: c_int, ySrc: c_int, SrcWidth: c_int, SrcHeight: c_int, lpBits: ?*const c_void, lpbmi: ?*const BITMAPINFO, iUsage: UINT, rop: DWORD) c_int; extern "gdi32" stdcallcc fn ChoosePixelFormat(hdc: HDC, ppfd: ?*const PIXELFORMATDESCRIPTOR) c_int; extern "gdi32" stdcallcc fn SetPixelFormat(hdc: HDC, format: c_int, ppfd: ?*const PIXELFORMATDESCRIPTOR) BOOL; extern "opengl32" stdcallcc fn wglCreateContext(arg0: HDC) ?HGLRC; extern "opengl32" stdcallcc fn wglMakeCurrent(arg0: HDC, arg1: HGLRC) BOOL; extern "opengl32" stdcallcc fn wglDeleteContext(arg0: HGLRC) BOOL; extern "opengl32" stdcallcc fn wglGetProcAddress(LPCSTR) ?PROC; pub const OpenGLError = error{ InitError, ShutdownError, }; pub const Context = struct { dummy_hRC: native.HGLRC, dummy_hDc: native.HDC, dummy_pfd: PIXELFORMATDESCRIPTOR, dummy_pfdid: c_int, dummy_hWnd: native.HWND, hRC: HGLRC, hDc: native.HDC, hWnd: native.HWND, stdcallcc fn wnd_proc(hWnd: native.HWND, msg: native.UINT, wParam: native.WPARAM, lParam: native.LPARAM) native.LRESULT { return native.DefWindowProcW(hWnd, msg, wParam, lParam); } pub fn dummy_init(window: *const super.Window) !Context { var result: Context = undefined; result.dummy_hWnd = CreateWindowExW(CLASS_NAME.ptr, CLASS_NAME.ptr, WS_CLIPCHILDREN | WS_CLIPSIBLINGS, 0, 0, 1, 1, null, null, native.GetModuleHandleW(null), null) orelse return error.InitError; result.dummy_hDc = GetDC(dummy_wnd); result.dummy_pfd = PIXELFORMATDESCRIPTOR{ .nSize = @sizeOf(PIXELFORMATDESCRIPTOR), .nVersion = 1, .dwFlags = PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL, .iPixelType = PFD_TYPE_RGBA, .cColorBits = 32, .cRedBits = 0, .cRedShift = 0, .cGreenBits = 0, .cGreenShift = 0, .cBlueBits = 0, .cBlueShift = 0, .cAlphaBits = 0, .cAlphaShift = 0, .cAccumBits = 0, .cAccumRedBits = 0, .cAccumGreenBits = 0, .cAccumBlueBits = 0, .cAccumAlphaBits = 0, .cDepthBits = 0, .cStencilBits = 0, .cAuxBuffers = 0, .iLayerType = PFD_MAIN_PLANE, .bReserved = 0, .dwLayerMask = 0, .dwVisibleMask = 0, .dwDamageMask = 0, }; result.dummy_pfdid = ChoosePixelFormat(result.dummy_hDc, &result.dummy_pfd); if (result.dummy_pfdid == 0) { return error.InitError; } if (SetPixelFormat(result.dummy_hDc, result.dummy_hDc, &result.dummy_pfd) == FALSE) { return error.InitError; } if (wglCreateContext(result.dummy_hDc)) |hRc| { result.dummy_hRc = hRc; } else return error.InitError; if (wglMakeCurrent(result.dummy_hDc, result.dummy_hRc) == FALSE) { return error.InitError; } return result; } fn dummy_deinit(self: Context) !void { if (wglMakeCurrent(null, null) == FALSE) { return error.InitError; } if (wglDeleteContext(self.dummy_hRC)) { return error.InitError; } if (ReleaseDC(self.dummy_hWnd, self.dummy_hDc) == FALSE) { return error.InitError; } if (DestroyWindow(self.dummy_hWnd) == FALSE) { return error.InitError; } } pub fn init(self: *Context, window: *const super.Window) !void { self.hWnd = window.hWnd; self.dummy_init(window); self.dummy_deinit(); if (wglMakeCurrent(self.hDc, self.hRc) == FALSE) { return error.InitError; } } pub fn deinit(self: Context) !void { if (wglMakeCurrent(null, null) == FALSE) { return error.ShutdownError; } if (wglDeleteContext(self.hRC)) { return error.ShutdownError; } if (ReleaseDC(self.hWnd, self.hDc) == FALSE) { return error.ShutdownError; } if (DestroyWindow(self.hWnd) == FALSE) { return error.ShutdownError; } if (UnregisterClassW(CLASS_NAME.ptr, self.hInstace)) { return error.ShutdownError; } } };
src/app/windows/backend/opengl.zig
const std = @import("std"); const io = std.io; const testing = std.testing; // This matches std.io.bufferedReader's buffer size pub const default_buffer_size = 4096; pub const DefaultBufferedStreamSource = BufferedStreamSource(default_buffer_size); /// A reader-only version of std.io.StreamSource that provides a seekable /// std.io.BufferedReader for files. /// Necessary because normally if a buffered reader is seeked, then the buffer /// will give incorrect data on the next read. pub fn BufferedStreamSource(comptime buffer_size: usize) type { return struct { stream_source: *io.StreamSource, buffered_reader: ?BufferedReaderType, const BufferedReaderType = io.BufferedReader(buffer_size, io.StreamSource.Reader); const Self = @This(); pub fn init(stream_source: *io.StreamSource) Self { return Self{ .stream_source = stream_source, .buffered_reader = switch (stream_source.*) { .buffer, .const_buffer => null, .file => BufferedReaderType{ .unbuffered_reader = stream_source.reader() }, }, }; } pub const ReadError = io.StreamSource.ReadError; pub const SeekError = io.StreamSource.SeekError; pub const GetSeekPosError = io.StreamSource.GetSeekPosError; pub const Reader = io.Reader(*Self, ReadError, read); pub const SeekableStream = io.SeekableStream(*Self, SeekError, GetSeekPosError, seekTo, seekBy, getPos, getEndPos); pub fn read(self: *Self, dest: []u8) ReadError!usize { if (self.buffered_reader) |*buffered_reader| { return buffered_reader.read(dest); } else { return self.stream_source.read(dest); } } pub fn seekTo(self: *Self, pos: u64) SeekError!void { if (self.stream_source.seekTo(pos)) { if (self.buffered_reader) |*buffered_reader| { // just discard the buffer completely buffered_reader.fifo.discard(buffered_reader.fifo.count); } } else |err| { return err; } } pub fn seekBy(self: *Self, amt: i64) SeekError!void { if (self.buffered_reader) |*buffered_reader| { const amount_buffered = buffered_reader.fifo.count; // If we can just skip ahead in the buffer, then do that instead of // actually seeking if (amt > 0 and amt <= amount_buffered) { buffered_reader.fifo.discard(@intCast(usize, amt)); } // Otherwise, we need to seek (adjusted by the amount buffered) // and then discard the buffer if the seek succeeds else if (amt != 0) { if (self.stream_source.seekBy(amt - @intCast(i64, amount_buffered))) { buffered_reader.fifo.discard(amount_buffered); } else |err| { return err; } } } else { return self.stream_source.seekBy(amt); } } pub fn getEndPos(self: *Self) GetSeekPosError!u64 { return self.stream_source.getEndPos(); } pub fn getPos(self: *Self) GetSeekPosError!u64 { if (self.stream_source.getPos()) |pos| { // the 'real' pos is offset by the current buffer count if (self.buffered_reader) |*buffered_reader| { return pos - buffered_reader.fifo.count; } return pos; } else |err| { return err; } } pub fn reader(self: *Self) Reader { return .{ .context = self }; } pub fn seekableStream(self: *Self) SeekableStream { return .{ .context = self }; } }; } pub fn bufferedStreamSource(stream_source: *io.StreamSource) DefaultBufferedStreamSource { return DefaultBufferedStreamSource.init(stream_source); } test "BufferedStreamSource with file" { const full_contents = "123456789" ** 2; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile("testfile", full_contents); var file = try tmp.dir.openFile("testfile", .{}); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; // small buffer to test all seekBy branches var buffered_stream_source = BufferedStreamSource(4).init(&stream_source); const reader = buffered_stream_source.reader(); const seekable_stream = buffered_stream_source.seekableStream(); const first_few_bytes = try reader.readBytesNoEof(3); try testing.expectEqual(@as(u64, 3), try seekable_stream.getPos()); try seekable_stream.seekTo(0); try testing.expectEqual(@as(u64, 0), try seekable_stream.getPos()); const first_few_bytes_again = try reader.readBytesNoEof(3); try testing.expectEqual(@as(u64, 3), try seekable_stream.getPos()); try testing.expectEqualSlices(u8, first_few_bytes[0..], first_few_bytes_again[0..]); try seekable_stream.seekBy(-3); try testing.expectEqual(@as(u64, 0), try seekable_stream.getPos()); const first_few_bytes_yet_again = try reader.readBytesNoEof(3); try testing.expectEqual(@as(u64, 3), try seekable_stream.getPos()); try testing.expectEqualSlices(u8, first_few_bytes[0..], first_few_bytes_yet_again[0..]); try seekable_stream.seekBy(1); try testing.expectEqual(@as(u64, 4), try seekable_stream.getPos()); try seekable_stream.seekBy(4); try testing.expectEqual(@as(u64, 8), try seekable_stream.getPos()); const four_bytes = try reader.readBytesNoEof(4); try testing.expectEqual(@as(u64, 12), try seekable_stream.getPos()); try testing.expectEqualSlices(u8, full_contents[8..12], four_bytes[0..]); }
src/buffered_stream_source.zig
const std = @import("std"); const logger = @import("logger.zig"); const metadata = @import("metadata.zig"); const install = @import("install.zig"); const MetaStruct = metadata.MetaStruct; pub fn do_maint(args: [][]u8, install_dir: []const u8) !void { if (args.len < 1) { logger.warn("No sub-command provided!", .{}); } else { if (std.mem.eql(u8, args[0], "uninstall")) { try do_uninstall(install_dir); } } logger.info("Quitting.", .{}); } fn confirm() !bool { var stdin = std.io.getStdIn().reader(); logger.query("Please confirm this action [y/n]: ", .{}); var buf: [8]u8 = undefined; if (try stdin.readUntilDelimiterOrEof(buf[0..], '\n')) |user_input| { if (std.mem.eql(u8, user_input[0..1], "y") or std.mem.eql(u8, user_input[0..1], "Y")) { return true; } return false; } else { return false; } } fn do_uninstall(install_dir: []const u8) !void { logger.warn("This will uninstall the application runtime for this Burrito binary!", .{}); if ((try confirm()) == false) { logger.warn("Uninstall was aborted!", .{}); return; } logger.info("Deleting directory: {s}", .{install_dir}); try std.fs.deleteTreeAbsolute(install_dir); logger.info("Uninstall complete!", .{}); } pub fn do_clean_old_versions(install_prefix_path: []const u8, current_install_path: []const u8) !void { std.log.debug("Going to clean up older versions of this application...", .{}); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const allocator = &arena.allocator; const prefix_dir = try std.fs.openDirAbsolute(install_prefix_path, .{ .iterate = true, .access_sub_paths = true }); const current_install = try install.load_install_from_path(allocator, current_install_path); var itr = prefix_dir.iterate(); while (try itr.next()) |dir| { if (dir.kind == .Directory) { const possible_app_path = try std.fs.path.join(allocator, &[_][]const u8{ install_prefix_path, dir.name }); const other_install = try install.load_install_from_path(allocator, possible_app_path); // If can can't figure out if this is an install dir, just ignore it if (other_install == null) { continue; } // If this isn't the same installed app as us ignore it if (!std.mem.eql(u8, current_install.?.metadata.app_name, other_install.?.metadata.app_name)) { continue; } // Compare the version, if it's older, delete the directory if (std.SemanticVersion.order(current_install.?.version, other_install.?.version) == .gt) { try prefix_dir.deleteTree(other_install.?.install_dir_path); logger.info("Uninstalled older version (v{s})", .{other_install.?.metadata.app_version}); } } } arena.deinit(); }
src/maintenance.zig
const std = @import("std"); const os = @import("windows.zig"); pub const SAMPLE_DESC = extern struct { Count: u32 = 1, Quality: u32 = 0, }; pub const FORMAT = extern enum { UNKNOWN = 0, R32G32B32A32_TYPELESS = 1, R32G32B32A32_FLOAT = 2, R32G32B32A32_UINT = 3, R32G32B32A32_SINT = 4, R32G32B32_TYPELESS = 5, R32G32B32_FLOAT = 6, R32G32B32_UINT = 7, R32G32B32_SINT = 8, R16G16B16A16_TYPELESS = 9, R16G16B16A16_FLOAT = 10, R16G16B16A16_UNORM = 11, R16G16B16A16_UINT = 12, R16G16B16A16_SNORM = 13, R16G16B16A16_SINT = 14, R32G32_TYPELESS = 15, R32G32_FLOAT = 16, R32G32_UINT = 17, R32G32_SINT = 18, R32G8X24_TYPELESS = 19, D32_FLOAT_S8X24_UINT = 20, R32_FLOAT_X8X24_TYPELESS = 21, X32_TYPELESS_G8X24_UINT = 22, R10G10B10A2_TYPELESS = 23, R10G10B10A2_UNORM = 24, R10G10B10A2_UINT = 25, R11G11B10_FLOAT = 26, R8G8B8A8_TYPELESS = 27, R8G8B8A8_UNORM = 28, R8G8B8A8_UNORM_SRGB = 29, R8G8B8A8_UINT = 30, R8G8B8A8_SNORM = 31, R8G8B8A8_SINT = 32, R16G16_TYPELESS = 33, R16G16_FLOAT = 34, R16G16_UNORM = 35, R16G16_UINT = 36, R16G16_SNORM = 37, R16G16_SINT = 38, R32_TYPELESS = 39, D32_FLOAT = 40, R32_FLOAT = 41, R32_UINT = 42, R32_SINT = 43, R24G8_TYPELESS = 44, D24_UNORM_S8_UINT = 45, R24_UNORM_X8_TYPELESS = 46, X24_TYPELESS_G8_UINT = 47, R8G8_TYPELESS = 48, R8G8_UNORM = 49, R8G8_UINT = 50, R8G8_SNORM = 51, R8G8_SINT = 52, R16_TYPELESS = 53, R16_FLOAT = 54, D16_UNORM = 55, R16_UNORM = 56, R16_UINT = 57, R16_SNORM = 58, R16_SINT = 59, R8_TYPELESS = 60, R8_UNORM = 61, R8_UINT = 62, R8_SNORM = 63, R8_SINT = 64, A8_UNORM = 65, R1_UNORM = 66, R9G9B9E5_SHAREDEXP = 67, R8G8_B8G8_UNORM = 68, G8R8_G8B8_UNORM = 69, BC1_TYPELESS = 70, BC1_UNORM = 71, BC1_UNORM_SRGB = 72, BC2_TYPELESS = 73, BC2_UNORM = 74, BC2_UNORM_SRGB = 75, BC3_TYPELESS = 76, BC3_UNORM = 77, BC3_UNORM_SRGB = 78, BC4_TYPELESS = 79, BC4_UNORM = 80, BC4_SNORM = 81, BC5_TYPELESS = 82, BC5_UNORM = 83, BC5_SNORM = 84, B5G6R5_UNORM = 85, B5G5R5A1_UNORM = 86, B8G8R8A8_UNORM = 87, B8G8R8X8_UNORM = 88, R10G10B10_XR_BIAS_A2_UNORM = 89, B8G8R8A8_TYPELESS = 90, B8G8R8A8_UNORM_SRGB = 91, B8G8R8X8_TYPELESS = 92, B8G8R8X8_UNORM_SRGB = 93, BC6H_TYPELESS = 94, BC6H_UF16 = 95, BC6H_SF16 = 96, BC7_TYPELESS = 97, BC7_UNORM = 98, BC7_UNORM_SRGB = 99, AYUV = 100, Y410 = 101, Y416 = 102, NV12 = 103, P010 = 104, P016 = 105, _420_OPAQUE = 106, YUY2 = 107, Y210 = 108, Y216 = 109, NV11 = 110, AI44 = 111, IA44 = 112, P8 = 113, A8P8 = 114, B4G4R4A4_UNORM = 115, P208 = 130, V208 = 131, V408 = 132, }; pub const USAGE = u32; pub const SWAP_EFFECT = extern enum { DISCARD = 0, SEQUENTIAL = 1, FLIP_SEQUENTIAL = 3, FLIP_DISCARD = 4, }; pub const SWAP_CHAIN_DESC = extern struct { BufferDesc: MODE_DESC, SampleDesc: SAMPLE_DESC, BufferUsage: USAGE, BufferCount: u32, OutputWindow: os.HWND, Windowed: os.BOOL, SwapEffect: SWAP_EFFECT, Flags: u32, }; pub const MODE_DESC = extern struct { Width: u32, Height: u32, RefreshRate: RATIONAL, Format: FORMAT, ScanlineOrdering: MODE_SCANLINE_ORDER, Scaling: MODE_SCALING, }; pub const RATIONAL = extern struct { Numerator: u32, Denominator: u32, }; pub const MODE_SCANLINE_ORDER = extern enum { UNSPECIFIED = 0, PROGRESSIVE = 1, UPPER_FIELD_FIRST = 2, LOWER_FIELD_FIRST = 3, }; pub const MODE_SCALING = extern enum { UNSPECIFIED = 0, CENTERED = 1, STRETCHED = 2, }; pub const CREATE_FACTORY_DEBUG = 0x01; pub const USAGE_RENDER_TARGET_OUTPUT = 0x00000020; const HRESULT = os.HRESULT; pub const IObject = extern struct { const Self = @This(); vtbl: *const extern struct { // IUnknown QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT, AddRef: fn (*Self) callconv(.C) u32, Release: fn (*Self) callconv(.C) u32, // IDXGIObject SetPrivateData: fn (*Self, *const os.GUID, u32, ?*const c_void) callconv(.C) HRESULT, SetPrivateDataInterface: fn ( *Self, *const os.GUID, ?*const os.IUnknown, ) callconv(.C) HRESULT, GetPrivateData: fn (*Self, *const os.GUID, *u32, ?*c_void) callconv(.C) HRESULT, GetParent: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT, }, usingnamespace os.IUnknown.Methods(Self); usingnamespace IObject.Methods(Self); fn Methods(comptime T: type) type { return extern struct { pub inline fn SetPrivateData( self: *T, guid: *const os.GUID, data_size: u32, data: ?*const c_void, ) HRESULT { return self.vtbl.SetPrivateData(self, guid, data_size, data); } pub inline fn SetPrivateDataInterface( self: *T, guid: *const os.GUID, data: ?*const os.IUnknown, ) HRESULT { return self.vtbl.SetPrivateDataInterface(self, guid, data); } pub inline fn GetPrivateData( self: *T, guid: *const os.GUID, data_size: *u32, data: ?*c_void, ) HRESULT { return self.vtbl.GetPrivateData(self, guid, data_size, data); } pub inline fn GetParent(self: *T, guid: *const os.GUID, parent: **c_void) HRESULT { return self.vtbl.GetParent(self, guid, parent); } }; } }; pub const IDevice = extern struct { const Self = @This(); vtbl: *const extern struct { // IUnknown QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT, AddRef: fn (*Self) callconv(.C) u32, Release: fn (*Self) callconv(.C) u32, // IDXGIObject SetPrivateData: fn (*Self, *const os.GUID, u32, ?*const c_void) callconv(.C) HRESULT, SetPrivateDataInterface: fn ( *Self, *const os.GUID, ?*const os.IUnknown, ) callconv(.C) HRESULT, GetPrivateData: fn (*Self, *const os.GUID, *u32, ?*c_void) callconv(.C) HRESULT, GetParent: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT, // IDXGIDevice GetAdapter: *c_void, CreateSurface: *c_void, QueryResourceResidency: *c_void, SetGPUThreadPriority: *c_void, GetGPUThreadPriority: *c_void, }, usingnamespace os.IUnknown.Methods(Self); usingnamespace IObject.Methods(Self); }; pub const IDeviceSubObject = extern struct { const Self = @This(); vtbl: *const extern struct { // IUnknown QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT, AddRef: fn (*Self) callconv(.C) u32, Release: fn (*Self) callconv(.C) u32, // IDXGIObject SetPrivateData: fn (*Self, *const os.GUID, u32, ?*const c_void) callconv(.C) HRESULT, SetPrivateDataInterface: fn ( *Self, *const os.GUID, ?*const os.IUnknown, ) callconv(.C) HRESULT, GetPrivateData: fn (*Self, *const os.GUID, *u32, ?*c_void) callconv(.C) HRESULT, GetParent: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT, // IDXGIDeviceSubObject GetDevice: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT, }, usingnamespace os.IUnknown.Methods(Self); usingnamespace IObject.Methods(Self); usingnamespace IDeviceSubObject.Methods(Self); fn Methods(comptime T: type) type { return extern struct { pub inline fn GetDevice(self: *T, guid: *const os.GUID, device: **c_void) HRESULT { return self.vtbl.GetDevice(self, guid, device); } }; } }; pub const ISurface = extern struct { const Self = @This(); vtbl: *const extern struct { // IUnknown QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT, AddRef: fn (*Self) callconv(.C) u32, Release: fn (*Self) callconv(.C) u32, // IDXGIObject SetPrivateData: fn (*Self, *const os.GUID, u32, ?*const c_void) callconv(.C) HRESULT, SetPrivateDataInterface: fn ( *Self, *const os.GUID, ?*const os.IUnknown, ) callconv(.C) HRESULT, GetPrivateData: fn (*Self, *const os.GUID, *u32, ?*c_void) callconv(.C) HRESULT, GetParent: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT, // IDXGIDeviceSubObject GetDevice: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT, // IDXGISurface GetDesc: *c_void, Map: *c_void, Unmap: *c_void, }, usingnamespace os.IUnknown.Methods(Self); usingnamespace IObject.Methods(Self); usingnamespace IDeviceSubObject.Methods(Self); }; pub const IFactory4 = extern struct { const Self = @This(); vtbl: *const extern struct { // IUnknown QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT, AddRef: fn (*Self) callconv(.C) u32, Release: fn (*Self) callconv(.C) u32, // IDXGIObject SetPrivateData: fn (*Self, *const os.GUID, u32, ?*const c_void) callconv(.C) HRESULT, SetPrivateDataInterface: fn ( *Self, *const os.GUID, ?*const os.IUnknown, ) callconv(.C) HRESULT, GetPrivateData: fn (*Self, *const os.GUID, *u32, ?*c_void) callconv(.C) HRESULT, GetParent: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT, // IDXGIFactory EnumAdapters: *c_void, MakeWindowAssociation: *c_void, GetWindowAssociation: *c_void, CreateSwapChain: fn ( *Self, *os.IUnknown, *SWAP_CHAIN_DESC, **os.IUnknown, ) callconv(.C) HRESULT, CreateSoftwareAdapter: *c_void, // IDXGIFactory1 EnumAdapters1: *c_void, IsCurrent: *c_void, // IDXGIFactory2 IsWindowedStereoEnabled: *c_void, CreateSwapChainForHwnd: *c_void, CreateSwapChainForCoreWindow: *c_void, GetSharedResourceAdapterLuid: *c_void, RegisterOcclusionStatusWindow: *c_void, RegisterStereoStatusEvent: *c_void, UnregisterStereoStatus: *c_void, RegisterStereoStatusWindow: *c_void, RegisterOcclusionStatusEvent: *c_void, UnregisterOcclusionStatus: *c_void, CreateSwapChainForComposition: *c_void, // IDXGIFactory3 GetCreationFlags: *c_void, // IDXGIFactory4 EnumAdapterByLuid: *c_void, EnumWarpAdapter: *c_void, }, usingnamespace os.IUnknown.Methods(Self); usingnamespace IObject.Methods(Self); usingnamespace IFactory4.Methods(Self); fn Methods(comptime T: type) type { return extern struct { pub inline fn CreateSwapChain( self: *T, device: *os.IUnknown, desc: *SWAP_CHAIN_DESC, swapchain: **os.IUnknown, ) HRESULT { return self.vtbl.CreateSwapChain(self, device, desc, swapchain); } }; } }; pub const ISwapChain3 = extern struct { const Self = @This(); vtbl: *const extern struct { // IUnknown QueryInterface: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT, AddRef: fn (*Self) callconv(.C) u32, Release: fn (*Self) callconv(.C) u32, // IDXGIObject SetPrivateData: fn (*Self, *const os.GUID, u32, ?*const c_void) callconv(.C) HRESULT, SetPrivateDataInterface: fn ( *Self, *const os.GUID, ?*const os.IUnknown, ) callconv(.C) HRESULT, GetPrivateData: fn (*Self, *const os.GUID, *u32, ?*c_void) callconv(.C) HRESULT, GetParent: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT, // IDXGIDeviceSubObject GetDevice: fn (*Self, *const os.GUID, **c_void) callconv(.C) HRESULT, // IDXGISwapChain Present: fn (*Self, u32, u32) callconv(.C) HRESULT, GetBuffer: fn (*Self, u32, *const os.GUID, **c_void) callconv(.C) HRESULT, SetFullscreenState: *c_void, GetFullscreenState: *c_void, GetDesc: *c_void, ResizeBuffers: *c_void, ResizeTarget: *c_void, GetContainingOutput: *c_void, GetFrameStatistics: *c_void, GetLastPresentCount: *c_void, // IDXGISwapChain1 GetDesc1: *c_void, GetFullscreenDesc: *c_void, GetHwnd: *c_void, GetCoreWindow: *c_void, Present1: *c_void, IsTemporaryMonoSupported: *c_void, GetRestrictToOutput: *c_void, SetBackgroundColor: *c_void, GetBackgroundColor: *c_void, SetRotation: *c_void, GetRotation: *c_void, // IDXGISwapChain2 SetSourceSize: *c_void, GetSourceSize: *c_void, SetMaximumFrameLatency: *c_void, GetMaximumFrameLatency: *c_void, GetFrameLatencyWaitableObject: *c_void, SetMatrixTransform: *c_void, GetMatrixTransform: *c_void, // IDXGISwapChain3 GetCurrentBackBufferIndex: fn (*Self) callconv(.C) u32, CheckColorSpaceSupport: *c_void, SetColorSpace1: *c_void, ResizeBuffers1: *c_void, }, usingnamespace os.IUnknown.Methods(Self); usingnamespace IObject.Methods(Self); usingnamespace IDeviceSubObject.Methods(Self); usingnamespace ISwapChain3.Methods(Self); fn Methods(comptime T: type) type { return extern struct { pub inline fn Present(self: *T, interval: u32, flags: u32) HRESULT { return self.vtbl.Present(self, interval, flags); } pub inline fn GetBuffer( self: *T, buffer: u32, guid: *const os.GUID, surface: **c_void, ) HRESULT { return self.vtbl.GetBuffer(self, buffer, guid, surface); } pub inline fn GetCurrentBackBufferIndex(self: *T) u32 { return self.vtbl.GetCurrentBackBufferIndex(self); } }; } }; pub const IID_ISwapChain = os.GUID{ .Data1 = 0x310d36a0, .Data2 = 0xd2e7, .Data3 = 0x4c0a, .Data4 = .{ 0xaa, 0x04, 0x6a, 0x9d, 0x23, 0xb8, 0x88, 0x6a }, }; pub const IID_ISwapChain3 = os.GUID{ .Data1 = 0x94d99bdb, .Data2 = 0xf1f8, .Data3 = 0x4ab0, .Data4 = .{ 0xb2, 0x36, 0x7d, 0xa0, 0x17, 0x0e, 0xda, 0xb1 }, }; pub const IID_IFactory4 = os.GUID{ .Data1 = 0x1bc6ea02, .Data2 = 0xef36, .Data3 = 0x464f, .Data4 = .{ 0xbf, 0x0c, 0x21, 0xca, 0x39, 0xe5, 0x16, 0x8a }, }; pub const IID_IDevice = os.GUID{ .Data1 = 0x54ec77fa, .Data2 = 0x1377, .Data3 = 0x44e6, .Data4 = .{ 0x8c, 0x32, 0x88, 0xfd, 0x5f, 0x44, 0xc8, 0x4c }, }; pub const IID_ISurface = os.GUID{ .Data1 = 0xcafcb56c, .Data2 = 0x6ac3, .Data3 = 0x4889, .Data4 = .{ 0xbf, 0x47, 0x9e, 0x23, 0xbb, 0xd2, 0x60, 0xec }, }; pub var CreateFactory2: fn (u32, *const os.GUID, **c_void) callconv(.C) HRESULT = undefined; pub fn init() void { // TODO: Handle error. var dxgi_dll = os.LoadLibraryA("dxgi.dll").?; CreateFactory2 = @ptrCast( @TypeOf(CreateFactory2), os.kernel32.GetProcAddress(dxgi_dll, "CreateDXGIFactory2").?, ); }
src/windows/dxgi.zig
const uefi = @import("std").os.uefi; const Guid = uefi.Guid; const Event = uefi.Event; const Status = uefi.Status; const MacAddress = uefi.protocols.MacAddress; const ManagedNetworkConfigData = uefi.protocols.ManagedNetworkConfigData; const SimpleNetworkMode = uefi.protocols.SimpleNetworkMode; pub const Ip6Protocol = extern struct { _get_mode_data: fn (*const Ip6Protocol, ?*Ip6ModeData, ?*ManagedNetworkConfigData, ?*SimpleNetworkMode) callconv(.C) Status, _configure: fn (*const Ip6Protocol, ?*const Ip6ConfigData) callconv(.C) Status, _groups: fn (*const Ip6Protocol, bool, ?*const Ip6Address) callconv(.C) Status, _routes: fn (*const Ip6Protocol, bool, ?*const Ip6Address, u8, ?*const Ip6Address) callconv(.C) Status, _neighbors: fn (*const Ip6Protocol, bool, *const Ip6Address, ?*const MacAddress, u32, bool) callconv(.C) Status, _transmit: fn (*const Ip6Protocol, *Ip6CompletionToken) callconv(.C) Status, _receive: fn (*const Ip6Protocol, *Ip6CompletionToken) callconv(.C) Status, _cancel: fn (*const Ip6Protocol, ?*Ip6CompletionToken) callconv(.C) Status, _poll: fn (*const Ip6Protocol) callconv(.C) Status, /// Gets the current operational settings for this instance of the EFI IPv6 Protocol driver. pub fn getModeData(self: *const Ip6Protocol, ip6_mode_data: ?*Ip6ModeData, mnp_config_data: ?*ManagedNetworkConfigData, snp_mode_data: ?*SimpleNetworkMode) Status { return self._get_mode_data(self, ip6_mode_data, mnp_config_data, snp_mode_data); } /// Assign IPv6 address and other configuration parameter to this EFI IPv6 Protocol driver instance. pub fn configure(self: *const Ip6Protocol, ip6_config_data: ?*const Ip6ConfigData) Status { return self._configure(self, ip6_config_data); } /// Joins and leaves multicast groups. pub fn groups(self: *const Ip6Protocol, join_flag: bool, group_address: ?*const Ip6Address) Status { return self._groups(self, join_flag, group_address); } /// Adds and deletes routing table entries. pub fn routes(self: *const Ip6Protocol, delete_route: bool, destination: ?*const Ip6Address, prefix_length: u8, gateway_address: ?*const Ip6Address) Status { return self._routes(self, delete_route, destination, prefix_length, gateway_address); } /// Add or delete Neighbor cache entries. pub fn neighbors(self: *const Ip6Protocol, delete_flag: bool, target_ip6_address: *const Ip6Address, target_link_address: ?*const MacAddress, timeout: u32, override: bool) Status { return self._neighbors(self, delete_flag, target_ip6_address, target_link_address, timeout, override); } /// Places outgoing data packets into the transmit queue. pub fn transmit(self: *const Ip6Protocol, token: *Ip6CompletionToken) Status { return self._transmit(self, token); } /// Places a receiving request into the receiving queue. pub fn receive(self: *const Ip6Protocol, token: *Ip6CompletionToken) Status { return self._receive(self, token); } /// Abort an asynchronous transmits or receive request. pub fn cancel(self: *const Ip6Protocol, token: ?*Ip6CompletionToken) Status { return self._cancel(self, token); } /// Polls for incoming data packets and processes outgoing data packets. pub fn poll(self: *const Ip6Protocol) Status { return self._poll(self); } pub const guid align(8) = Guid{ .time_low = 0x2c8759d5, .time_mid = 0x5c2d, .time_high_and_version = 0x66ef, .clock_seq_high_and_reserved = 0x92, .clock_seq_low = 0x5f, .node = [_]u8{ 0xb6, 0x6c, 0x10, 0x19, 0x57, 0xe2 }, }; }; pub const Ip6ModeData = extern struct { is_started: bool, max_packet_size: u32, config_data: Ip6ConfigData, is_configured: bool, address_count: u32, address_list: [*]Ip6AddressInfo, group_count: u32, group_table: [*]Ip6Address, route_count: u32, route_table: [*]Ip6RouteTable, neighbor_count: u32, neighbor_cache: [*]Ip6NeighborCache, prefix_count: u32, prefix_table: [*]Ip6AddressInfo, icmp_type_count: u32, icmp_type_list: [*]Ip6IcmpType, }; pub const Ip6ConfigData = extern struct { default_protocol: u8, accept_any_protocol: bool, accept_icmp_errors: bool, accept_promiscuous: bool, destination_address: Ip6Address, station_address: Ip6Address, traffic_class: u8, hop_limit: u8, flow_label: u32, receive_timeout: u32, transmit_timeout: u32, }; pub const Ip6Address = [16]u8; pub const Ip6AddressInfo = extern struct { address: Ip6Address, prefix_length: u8, }; pub const Ip6RouteTable = extern struct { gateway: Ip6Address, destination: Ip6Address, prefix_length: u8, }; pub const Ip6NeighborState = enum(u32) { Incomplete, Reachable, Stale, Delay, Probe, }; pub const Ip6NeighborCache = extern struct { neighbor: Ip6Address, link_address: MacAddress, state: Ip6NeighborState, }; pub const Ip6IcmpType = extern struct { type: u8, code: u8, }; pub const Ip6CompletionToken = extern struct { event: Event, status: Status, packet: *c_void, // union TODO };
lib/std/os/uefi/protocols/ip6_protocol.zig
const std = @import("std"); const assert = std.debug.assert; const Token = @import("zig_grammar.tokens.zig").Token; pub const TokenIndex = *Token; pub const NodeList = std.ArrayList(*Node); pub const TokenList = std.ArrayList(*Token); pub const Node = struct { id: Id, pub const Id = enum { // Top level Root, Use, TestDecl, // Statements VarDecl, Defer, // Operators InfixOp, PrefixOp, SuffixOp, // Control flow Switch, While, For, If, ControlFlowExpression, Suspend, // Type expressions VarType, ErrorType, FnProto, PromiseType, // Primary expressions IntegerLiteral, FloatLiteral, EnumLiteral, StringLiteral, MultilineStringLiteral, CharLiteral, BoolLiteral, NullLiteral, UndefinedLiteral, Unreachable, Identifier, GroupedExpression, BuiltinCall, ErrorSetDecl, ContainerDecl, Asm, Comptime, Block, // Misc DocComment, SwitchCase, SwitchElse, Else, Payload, PointerPayload, PointerIndexPayload, ContainerField, ErrorTag, AsmInput, AsmOutput, ParamDecl, FieldInitializer, // Recovery Recovery, }; pub fn cast(base: *Node, comptime T: type) ?*T { if (base.id == comptime typeToId(T)) { return @fieldParentPtr(T, "base", base); } return null; } pub fn unsafe_cast(base: *Node, comptime T: type) *T { return @fieldParentPtr(T, "base", base); } pub fn iterate(base: *Node, index: usize) ?*Node { comptime var i = 0; inline while (i < @memberCount(Id)) : (i += 1) { if (base.id == @field(Id, @memberName(Id, i))) { const T = @field(Node, @memberName(Id, i)); return @fieldParentPtr(T, "base", base).iterate(index); } } unreachable; } pub fn firstToken(base: *const Node) TokenIndex { comptime var i = 0; inline while (i < @memberCount(Id)) : (i += 1) { if (base.id == @field(Id, @memberName(Id, i))) { const T = @field(Node, @memberName(Id, i)); return @fieldParentPtr(T, "base", base).firstToken(); } } unreachable; } pub fn lastToken(base: *const Node) TokenIndex { comptime var i = 0; inline while (i < @memberCount(Id)) : (i += 1) { if (base.id == @field(Id, @memberName(Id, i))) { const T = @field(Node, @memberName(Id, i)); return @fieldParentPtr(T, "base", base).lastToken(); } } unreachable; } pub fn typeToId(comptime T: type) Id { comptime var i = 0; inline while (i < @memberCount(Id)) : (i += 1) { if (T == @field(Node, @memberName(Id, i))) { return @field(Id, @memberName(Id, i)); } } unreachable; } pub fn dump(self: *Node, indent: usize) void { { var i: usize = 0; while (i < indent) : (i += 1) { std.debug.warn(" "); } } const first = self.firstToken(); const last = self.lastToken(); const first_nl = first.line.?; const last_nl = last.line.?; const first_col = first.start - first_nl.end + 1; const last_col = last.end - last_nl.end; const first_line = first_nl.start; const last_line = last_nl.start; if(self.cast(Node.PrefixOp)) |op| { std.debug.warn("{} ({}:{}-{}:{})\n", @tagName(op.op), first_line, first_col, last_line, last_col); } else if(self.cast(Node.InfixOp)) |op| { std.debug.warn("{} ({}:{}-{}:{})\n", @tagName(op.op), first_line, first_col, last_line, last_col); } else if(self.cast(Node.SuffixOp)) |op| { std.debug.warn("{} ({}:{}-{}:{})\n", @tagName(op.op), first_line, first_col, last_line, last_col); } else { std.debug.warn("{} ({}:{}-{}:{})\n", @tagName(self.id), first_line, first_col, last_line, last_col); } var child_i: usize = 0; while (self.iterate(child_i)) |child| : (child_i += 1) { child.dump(indent + 2); } } pub const Root = struct { base: Node, shebang_token: ?TokenIndex, doc_comments: ?*DocComment, decls: DeclList, eof_token: TokenIndex, pub const DeclList = NodeList; pub fn iterate(self: *Root, index: usize) ?*Node { if (index < self.decls.len) { return self.decls.at(index); } return null; } pub fn firstToken(self: *const Root) TokenIndex { return if (self.decls.len == 0) self.eof_token else (self.decls.at(0)).firstToken(); } pub fn lastToken(self: *const Root) TokenIndex { return if (self.decls.len == 0) self.eof_token else (self.decls.at(self.decls.len - 1)).lastToken(); } }; pub const VarDecl = struct { base: Node, doc_comments: ?*DocComment, visib_token: ?TokenIndex, thread_local_token: ?TokenIndex, name_token: TokenIndex, // eq_token: TokenIndex, mut_token: TokenIndex, comptime_token: ?TokenIndex, extern_export_token: ?TokenIndex, lib_name: ?*Node, type_node: ?*Node, align_node: ?*Node, section_node: ?*Node, init_node: ?*Node, semicolon_token: TokenIndex, pub fn iterate(self: *VarDecl, index: usize) ?*Node { var i = index; if (self.type_node) |type_node| { if (i < 1) return type_node; i -= 1; } if (self.align_node) |align_node| { if (i < 1) return align_node; i -= 1; } if (self.section_node) |section_node| { if (i < 1) return section_node; i -= 1; } if (self.init_node) |init_node| { if (i < 1) return init_node; i -= 1; } return null; } pub fn firstToken(self: *const VarDecl) TokenIndex { if (self.visib_token) |visib_token| return visib_token; if (self.thread_local_token) |thread_local_token| return thread_local_token; if (self.comptime_token) |comptime_token| return comptime_token; if (self.extern_export_token) |extern_export_token| return extern_export_token; assert(self.lib_name == null); return self.mut_token; } pub fn lastToken(self: *const VarDecl) TokenIndex { return self.semicolon_token; } }; pub const Use = struct { base: Node, doc_comments: ?*DocComment, visib_token: ?TokenIndex, use_token: TokenIndex, expr: *Node, semicolon_token: TokenIndex, pub fn iterate(self: *Use, index: usize) ?*Node { var i = index; if (i < 1) return self.expr; i -= 1; return null; } pub fn firstToken(self: *const Use) TokenIndex { if (self.visib_token) |visib_token| return visib_token; return self.use_token; } pub fn lastToken(self: *const Use) TokenIndex { return self.semicolon_token; } }; pub const ErrorSetDecl = struct { base: Node, error_token: TokenIndex, decls: DeclList, rbrace_token: TokenIndex, pub const DeclList = NodeList; pub fn iterate(self: *ErrorSetDecl, index: usize) ?*Node { var i = index; if (i < self.decls.len) return self.decls.at(i); i -= self.decls.len; return null; } pub fn firstToken(self: *const ErrorSetDecl) TokenIndex { return self.error_token; } pub fn lastToken(self: *const ErrorSetDecl) TokenIndex { return self.rbrace_token; } }; pub const ContainerDecl = struct { base: Node, layout_token: ?TokenIndex, kind_token: TokenIndex, init_arg_expr: InitArg, fields_and_decls: DeclList, lbrace_token: TokenIndex, rbrace_token: TokenIndex, pub const DeclList = Root.DeclList; pub const InitArg = union(enum) { None, Enum: ?*Node, Type: *Node, }; pub fn iterate(self: *ContainerDecl, index: usize) ?*Node { var i = index; switch (self.init_arg_expr) { InitArg.Type => |t| { if (i < 1) return t; i -= 1; }, InitArg.None, InitArg.Enum => {}, } if (i < self.fields_and_decls.len) return self.fields_and_decls.at(i); i -= self.fields_and_decls.len; return null; } pub fn firstToken(self: *const ContainerDecl) TokenIndex { if (self.layout_token) |layout_token| { return layout_token; } return self.kind_token; } pub fn lastToken(self: *const ContainerDecl) TokenIndex { return self.rbrace_token; } }; pub const ContainerField = struct { base: Node, doc_comments: ?*DocComment, visib_token: ?TokenIndex, name_token: TokenIndex, type_expr: ?*Node, value_expr: ?*Node, pub fn iterate(self: *ContainerField, index: usize) ?*Node { var i = index; if (self.type_expr) |type_expr| { if (i < 1) return type_expr; i -= 1; } if (self.value_expr) |value_expr| { if (i < 1) return value_expr; i -= 1; } return null; } pub fn firstToken(self: *const ContainerField) TokenIndex { if (self.visib_token) |visib_token| return visib_token; return self.name_token; } pub fn lastToken(self: *const ContainerField) TokenIndex { if (self.value_expr) |value_expr| { return value_expr.lastToken(); } if (self.type_expr) |type_expr| { return type_expr.lastToken(); } return self.name_token; } }; pub const ErrorTag = struct { base: Node, doc_comments: ?*DocComment, name_token: TokenIndex, pub fn iterate(self: *ErrorTag, index: usize) ?*Node { var i = index; if (self.doc_comments) |comments| { if (i < 1) return &comments.base; i -= 1; } return null; } pub fn firstToken(self: *const ErrorTag) TokenIndex { return self.name_token; } pub fn lastToken(self: *const ErrorTag) TokenIndex { return self.name_token; } }; pub const Identifier = struct { base: Node, token: TokenIndex, pub fn iterate(self: *Identifier, index: usize) ?*Node { return null; } pub fn firstToken(self: *const Identifier) TokenIndex { return self.token; } pub fn lastToken(self: *const Identifier) TokenIndex { return self.token; } }; pub const FnProto = struct { base: Node, doc_comments: ?*DocComment, visib_token: ?TokenIndex, fn_token: TokenIndex, name_token: ?TokenIndex, params: ParamList, return_type: ReturnType, var_args_token: ?TokenIndex, extern_export_inline_token: ?TokenIndex, cc_token: ?TokenIndex, body_node: ?*Node, lib_name: ?*Node, // populated if this is an extern declaration align_expr: ?*Node, // populated if align(A) is present section_expr: ?*Node, // populated if linksection(A) is present pub const ParamList = NodeList; pub const ReturnType = union(enum) { Explicit: *Node, InferErrorSet: *Node, }; pub fn iterate(self: *FnProto, index: usize) ?*Node { var i = index; if (self.lib_name) |lib_name| { if (i < 1) return lib_name; i -= 1; } if (i < self.params.len) return self.params.at(self.params.len - i - 1); i -= self.params.len; if (self.align_expr) |align_expr| { if (i < 1) return align_expr; i -= 1; } if (self.section_expr) |section_expr| { if (i < 1) return section_expr; i -= 1; } switch (self.return_type) { // TODO allow this and next prong to share bodies since the types are the same ReturnType.Explicit => |node| { if (i < 1) return node; i -= 1; }, ReturnType.InferErrorSet => |node| { if (i < 1) return node; i -= 1; }, } if (self.body_node) |body_node| { if (i < 1) return body_node; i -= 1; } return null; } pub fn firstToken(self: *const FnProto) TokenIndex { if (self.visib_token) |visib_token| return visib_token; if (self.extern_export_inline_token) |extern_export_inline_token| return extern_export_inline_token; assert(self.lib_name == null); if (self.cc_token) |cc_token| return cc_token; return self.fn_token; } pub fn lastToken(self: *const FnProto) TokenIndex { if (self.body_node) |body_node| return body_node.lastToken(); switch (self.return_type) { // TODO allow this and next prong to share bodies since the types are the same ReturnType.Explicit => |node| return node.lastToken(), ReturnType.InferErrorSet => |node| return node.lastToken(), } } }; pub const PromiseType = struct { base: Node, promise_token: TokenIndex, result: ?Result, pub const Result = struct { arrow_token: TokenIndex, return_type: *Node, }; pub fn iterate(self: *PromiseType, index: usize) ?*Node { var i = index; if (self.result) |result| { if (i < 1) return result.return_type; i -= 1; } return null; } pub fn firstToken(self: *const PromiseType) TokenIndex { return self.promise_token; } pub fn lastToken(self: *const PromiseType) TokenIndex { if (self.result) |result| return result.return_type.lastToken(); return self.promise_token; } }; pub const ParamDecl = struct { base: Node, doc_comments: ?*DocComment, comptime_token: ?TokenIndex, noalias_token: ?TokenIndex, name_token: ?TokenIndex, type_node: *Node, var_args_token: ?TokenIndex, pub fn iterate(self: *ParamDecl, index: usize) ?*Node { var i = index; if (i < 1) return self.type_node; i -= 1; return null; } pub fn firstToken(self: *const ParamDecl) TokenIndex { if (self.comptime_token) |comptime_token| return comptime_token; if (self.noalias_token) |noalias_token| return noalias_token; if (self.name_token) |name_token| return name_token; return self.type_node.firstToken(); } pub fn lastToken(self: *const ParamDecl) TokenIndex { if (self.var_args_token) |var_args_token| return var_args_token; return self.type_node.lastToken(); } }; pub const Block = struct { base: Node, label: ?TokenIndex, lbrace: TokenIndex, statements: StatementList, rbrace: TokenIndex, pub const StatementList = Root.DeclList; pub fn iterate(self: *Block, index: usize) ?*Node { var i = index; if (i < self.statements.len) return self.statements.at(i); i -= self.statements.len; return null; } pub fn firstToken(self: *const Block) TokenIndex { if (self.label) |label| { return label; } return self.lbrace; } pub fn lastToken(self: *const Block) TokenIndex { return self.rbrace; } }; pub const Defer = struct { base: Node, defer_token: TokenIndex, expr: *Node, pub fn iterate(self: *Defer, index: usize) ?*Node { var i = index; if (i < 1) return self.expr; i -= 1; return null; } pub fn firstToken(self: *const Defer) TokenIndex { return self.defer_token; } pub fn lastToken(self: *const Defer) TokenIndex { return self.expr.lastToken(); } }; pub const Comptime = struct { base: Node, doc_comments: ?*DocComment, comptime_token: TokenIndex, expr: *Node, pub fn iterate(self: *Comptime, index: usize) ?*Node { var i = index; if (i < 1) return self.expr; i -= 1; return null; } pub fn firstToken(self: *const Comptime) TokenIndex { return self.comptime_token; } pub fn lastToken(self: *const Comptime) TokenIndex { return self.expr.lastToken(); } }; pub const Payload = struct { base: Node, lpipe: TokenIndex, error_symbol: *Node, rpipe: TokenIndex, pub fn iterate(self: *Payload, index: usize) ?*Node { var i = index; if (i < 1) return self.error_symbol; i -= 1; return null; } pub fn firstToken(self: *const Payload) TokenIndex { return self.lpipe; } pub fn lastToken(self: *const Payload) TokenIndex { return self.rpipe; } }; pub const PointerPayload = struct { base: Node, lpipe: TokenIndex, ptr_token: ?TokenIndex, value_symbol: *Node, rpipe: TokenIndex, pub fn iterate(self: *PointerPayload, index: usize) ?*Node { var i = index; if (i < 1) return self.value_symbol; i -= 1; return null; } pub fn firstToken(self: *const PointerPayload) TokenIndex { return self.lpipe; } pub fn lastToken(self: *const PointerPayload) TokenIndex { return self.rpipe; } }; pub const PointerIndexPayload = struct { base: Node, lpipe: TokenIndex, ptr_token: ?TokenIndex, value_symbol: *Node, index_symbol: ?*Node, rpipe: TokenIndex, pub fn iterate(self: *PointerIndexPayload, index: usize) ?*Node { var i = index; if (i < 1) return self.value_symbol; i -= 1; if (self.index_symbol) |index_symbol| { if (i < 1) return index_symbol; i -= 1; } return null; } pub fn firstToken(self: *const PointerIndexPayload) TokenIndex { return self.lpipe; } pub fn lastToken(self: *const PointerIndexPayload) TokenIndex { return self.rpipe; } }; pub const Else = struct { base: Node, else_token: TokenIndex, payload: ?*Node, body: *Node, pub fn iterate(self: *Else, index: usize) ?*Node { var i = index; if (self.payload) |payload| { if (i < 1) return payload; i -= 1; } if (i < 1) return self.body; i -= 1; return null; } pub fn firstToken(self: *const Else) TokenIndex { return self.else_token; } pub fn lastToken(self: *const Else) TokenIndex { return self.body.lastToken(); } }; pub const Switch = struct { base: Node, switch_token: TokenIndex, expr: *Node, /// these must be SwitchCase nodes cases: CaseList, rbrace: TokenIndex, pub const CaseList = NodeList; pub fn iterate(self: *Switch, index: usize) ?*Node { var i = index; if (i < 1) return self.expr; i -= 1; if (i < self.cases.len) return self.cases.at(i); i -= self.cases.len; return null; } pub fn firstToken(self: *const Switch) TokenIndex { return self.switch_token; } pub fn lastToken(self: *const Switch) TokenIndex { return self.rbrace; } }; pub const SwitchCase = struct { base: Node, items: ItemList, arrow_token: TokenIndex, payload: ?*Node, expr: *Node, pub const ItemList = NodeList; pub fn iterate(self: *SwitchCase, index: usize) ?*Node { var i = index; if (i < self.items.len) return self.items.at(i); i -= self.items.len; if (self.payload) |payload| { if (i < 1) return payload; i -= 1; } if (i < 1) return self.expr; i -= 1; return null; } pub fn firstToken(self: *const SwitchCase) TokenIndex { return (self.items.at(0)).firstToken(); } pub fn lastToken(self: *const SwitchCase) TokenIndex { return self.expr.lastToken(); } }; pub const SwitchElse = struct { base: Node, token: TokenIndex, pub fn iterate(self: *SwitchElse, index: usize) ?*Node { return null; } pub fn firstToken(self: *const SwitchElse) TokenIndex { return self.token; } pub fn lastToken(self: *const SwitchElse) TokenIndex { return self.token; } }; pub const While = struct { base: Node, label: ?TokenIndex, inline_token: ?TokenIndex, while_token: TokenIndex, condition: *Node, payload: ?*Node, continue_expr: ?*Node, body: *Node, @"else": ?*Else, pub fn iterate(self: *While, index: usize) ?*Node { var i = index; if (i < 1) return self.condition; i -= 1; if (self.payload) |payload| { if (i < 1) return payload; i -= 1; } if (self.continue_expr) |continue_expr| { if (i < 1) return continue_expr; i -= 1; } if (i < 1) return self.body; i -= 1; if (self.@"else") |@"else"| { if (i < 1) return &@"else".base; i -= 1; } return null; } pub fn firstToken(self: *const While) TokenIndex { if (self.label) |label| { return label; } if (self.inline_token) |inline_token| { return inline_token; } return self.while_token; } pub fn lastToken(self: *const While) TokenIndex { if (self.@"else") |@"else"| { return @"else".body.lastToken(); } return self.body.lastToken(); } }; pub const For = struct { base: Node, label: ?TokenIndex, inline_token: ?TokenIndex, for_token: TokenIndex, array_expr: *Node, payload: *Node, body: *Node, @"else": ?*Else, pub fn iterate(self: *For, index: usize) ?*Node { var i = index; if (i < 1) return self.array_expr; i -= 1; if (i < 1) return self.payload; i -= 1; if (i < 1) return self.body; i -= 1; if (self.@"else") |@"else"| { if (i < 1) return &@"else".base; i -= 1; } return null; } pub fn firstToken(self: *const For) TokenIndex { if (self.label) |label| { return label; } if (self.inline_token) |inline_token| { return inline_token; } return self.for_token; } pub fn lastToken(self: *const For) TokenIndex { if (self.@"else") |@"else"| { return @"else".body.lastToken(); } return self.body.lastToken(); } }; pub const If = struct { base: Node, if_token: TokenIndex, condition: *Node, payload: ?*Node, body: *Node, @"else": ?*Else, pub fn iterate(self: *If, index: usize) ?*Node { var i = index; if (i < 1) return self.condition; i -= 1; if (self.payload) |payload| { if (i < 1) return payload; i -= 1; } if (i < 1) return self.body; i -= 1; if (self.@"else") |@"else"| { if (i < 1) return &@"else".base; i -= 1; } return null; } pub fn firstToken(self: *const If) TokenIndex { return self.if_token; } pub fn lastToken(self: *const If) TokenIndex { if (self.@"else") |@"else"| { return @"else".body.lastToken(); } return self.body.lastToken(); } }; pub const InfixOp = struct { base: Node, op_token: TokenIndex, lhs: *Node, op: Op, rhs: *Node, pub const Op = union(enum) { Add, AddWrap, ArrayCat, ArrayMult, Assign, AssignBitAnd, AssignBitOr, AssignBitShiftLeft, AssignBitShiftRight, AssignBitXor, AssignDiv, AssignMinus, AssignMinusWrap, AssignMod, AssignPlus, AssignPlusWrap, AssignTimes, AssignTimesWrap, BangEqual, BitAnd, BitOr, BitShiftLeft, BitShiftRight, BitXor, BoolAnd, BoolOr, Catch: ?*Node, Div, EqualEqual, ErrorUnion, GreaterOrEqual, GreaterThan, LessOrEqual, LessThan, MergeErrorSets, Mod, Mult, MultWrap, Period, Range, Sub, SubWrap, UnwrapOptional, }; pub fn iterate(self: *InfixOp, index: usize) ?*Node { var i = index; if (i < 1) return self.lhs; i -= 1; switch (self.op) { Op.Catch => |maybe_payload| { if (maybe_payload) |payload| { if (i < 1) return payload; i -= 1; } }, Op.Add, Op.AddWrap, Op.ArrayCat, Op.ArrayMult, Op.Assign, Op.AssignBitAnd, Op.AssignBitOr, Op.AssignBitShiftLeft, Op.AssignBitShiftRight, Op.AssignBitXor, Op.AssignDiv, Op.AssignMinus, Op.AssignMinusWrap, Op.AssignMod, Op.AssignPlus, Op.AssignPlusWrap, Op.AssignTimes, Op.AssignTimesWrap, Op.BangEqual, Op.BitAnd, Op.BitOr, Op.BitShiftLeft, Op.BitShiftRight, Op.BitXor, Op.BoolAnd, Op.BoolOr, Op.Div, Op.EqualEqual, Op.ErrorUnion, Op.GreaterOrEqual, Op.GreaterThan, Op.LessOrEqual, Op.LessThan, Op.MergeErrorSets, Op.Mod, Op.Mult, Op.MultWrap, Op.Period, Op.Range, Op.Sub, Op.SubWrap, Op.UnwrapOptional, => {}, } if (i < 1) return self.rhs; i -= 1; return null; } pub fn firstToken(self: *const InfixOp) TokenIndex { return self.lhs.firstToken(); } pub fn lastToken(self: *const InfixOp) TokenIndex { return self.rhs.lastToken(); } }; pub const PrefixOp = struct { base: Node, op_token: TokenIndex, op: Op, rhs: *Node, pub const Op = union(enum) { AddressOf, ArrayType: *Node, Async, Await, BitNot, BoolNot, Cancel, OptionalType, Negation, NegationWrap, Resume, PtrType: PtrInfo, SliceType: PtrInfo, Try, }; pub const PtrInfo = struct { allowzero_token: ?TokenIndex, align_info: ?Align, const_token: ?TokenIndex, volatile_token: ?TokenIndex, pub const Align = struct { node: *Node, bit_range: ?BitRange, pub const BitRange = struct { start: *Node, end: *Node, }; }; }; pub fn iterate(self: *PrefixOp, index: usize) ?*Node { var i = index; switch (self.op) { // TODO https://github.com/ziglang/zig/issues/1107 Op.SliceType => |addr_of_info| { if (addr_of_info.align_info) |align_info| { if (i < 1) return align_info.node; i -= 1; } }, Op.PtrType => |addr_of_info| { if (addr_of_info.align_info) |align_info| { if (i < 1) return align_info.node; i -= 1; } }, Op.ArrayType => |size_expr| { if (i < 1) return size_expr; i -= 1; }, Op.AddressOf, Op.Await, Op.BitNot, Op.BoolNot, Op.Cancel, Op.OptionalType, Op.Negation, Op.NegationWrap, Op.Try, Op.Resume, Op.Async, => {}, } if (i < 1) return self.rhs; i -= 1; return null; } pub fn firstToken(self: *const PrefixOp) TokenIndex { return self.op_token; } pub fn lastToken(self: *const PrefixOp) TokenIndex { return self.rhs.lastToken(); } }; pub const FieldInitializer = struct { base: Node, period_token: TokenIndex, name_token: TokenIndex, expr: *Node, pub fn iterate(self: *FieldInitializer, index: usize) ?*Node { var i = index; if (i < 1) return self.expr; i -= 1; return null; } pub fn firstToken(self: *const FieldInitializer) TokenIndex { return self.period_token; } pub fn lastToken(self: *const FieldInitializer) TokenIndex { return self.expr.lastToken(); } }; pub const SuffixOp = struct { base: Node, lhs: *Node, op: Op, rtoken: TokenIndex, pub const Op = union(enum) { Call: Call, ArrayAccess: *Node, Slice: Slice, ArrayInitializer: InitList, StructInitializer: InitList, Deref, UnwrapOptional, pub const InitList = NodeList; pub const Call = struct { params: ParamList, pub const ParamList = NodeList; }; pub const Slice = struct { start: *Node, end: ?*Node, }; }; pub fn iterate(self: *SuffixOp, index: usize) ?*Node { var i = index; if (i < 1) return self.lhs; i -= 1; switch (self.op) { .Call => |*call_info| { if (i < call_info.params.len) return call_info.params.at(i); i -= call_info.params.len; }, .ArrayAccess => |index_expr| { if (i < 1) return index_expr; i -= 1; }, .Slice => |range| { if (i < 1) return range.start; i -= 1; if (range.end) |end| { if (i < 1) return end; i -= 1; } }, .ArrayInitializer => |*exprs| { if (i < exprs.len) return exprs.at(i); i -= exprs.len; }, .StructInitializer => |*fields| { if (i < fields.len) return fields.at(i); i -= fields.len; }, .UnwrapOptional, .Deref, => {}, } return null; } pub fn firstToken(self: *const SuffixOp) TokenIndex { return self.lhs.firstToken(); } pub fn lastToken(self: *const SuffixOp) TokenIndex { return self.rtoken; } }; pub const GroupedExpression = struct { base: Node, lparen: TokenIndex, expr: *Node, rparen: TokenIndex, pub fn iterate(self: *GroupedExpression, index: usize) ?*Node { var i = index; if (i < 1) return self.expr; i -= 1; return null; } pub fn firstToken(self: *const GroupedExpression) TokenIndex { return self.lparen; } pub fn lastToken(self: *const GroupedExpression) TokenIndex { return self.rparen; } }; pub const ControlFlowExpression = struct { base: Node, ltoken: TokenIndex, kind: Kind, rhs: ?*Node, pub const Kind = union(enum) { Break: ?*Node, Continue: ?*Node, Return, }; pub fn iterate(self: *ControlFlowExpression, index: usize) ?*Node { var i = index; switch (self.kind) { Kind.Break => |maybe_label| { if (maybe_label) |label| { if (i < 1) return label; i -= 1; } }, Kind.Continue => |maybe_label| { if (maybe_label) |label| { if (i < 1) return label; i -= 1; } }, Kind.Return => {}, } if (self.rhs) |rhs| { if (i < 1) return rhs; i -= 1; } return null; } pub fn firstToken(self: *const ControlFlowExpression) TokenIndex { return self.ltoken; } pub fn lastToken(self: *const ControlFlowExpression) TokenIndex { if (self.rhs) |rhs| { return rhs.lastToken(); } switch (self.kind) { Kind.Break => |maybe_label| { if (maybe_label) |label| { return label.lastToken(); } }, Kind.Continue => |maybe_label| { if (maybe_label) |label| { return label.lastToken(); } }, Kind.Return => return self.ltoken, } return self.ltoken; } }; pub const Suspend = struct { base: Node, suspend_token: TokenIndex, body: ?*Node, pub fn iterate(self: *Suspend, index: usize) ?*Node { var i = index; if (self.body) |body| { if (i < 1) return body; i -= 1; } return null; } pub fn firstToken(self: *const Suspend) TokenIndex { return self.suspend_token; } pub fn lastToken(self: *const Suspend) TokenIndex { if (self.body) |body| { return body.lastToken(); } return self.suspend_token; } }; pub const IntegerLiteral = struct { base: Node, token: TokenIndex, pub fn iterate(self: *IntegerLiteral, index: usize) ?*Node { return null; } pub fn firstToken(self: *const IntegerLiteral) TokenIndex { return self.token; } pub fn lastToken(self: *const IntegerLiteral) TokenIndex { return self.token; } }; pub const EnumLiteral = struct { base: Node, dot: TokenIndex, name: TokenIndex, pub fn iterate(self: *EnumLiteral, index: usize) ?*Node { return null; } pub fn firstToken(self: *const EnumLiteral) TokenIndex { return self.dot; } pub fn lastToken(self: *const EnumLiteral) TokenIndex { return self.name; } }; pub const FloatLiteral = struct { base: Node, token: TokenIndex, pub fn iterate(self: *FloatLiteral, index: usize) ?*Node { return null; } pub fn firstToken(self: *const FloatLiteral) TokenIndex { return self.token; } pub fn lastToken(self: *const FloatLiteral) TokenIndex { return self.token; } }; pub const BuiltinCall = struct { base: Node, builtin_token: TokenIndex, params: ParamList, rparen_token: TokenIndex, pub const ParamList = NodeList; pub fn iterate(self: *BuiltinCall, index: usize) ?*Node { var i = index; if (i < self.params.len) return self.params.at(i); i -= self.params.len; return null; } pub fn firstToken(self: *const BuiltinCall) TokenIndex { return self.builtin_token; } pub fn lastToken(self: *const BuiltinCall) TokenIndex { return self.rparen_token; } }; pub const StringLiteral = struct { base: Node, token: TokenIndex, pub fn iterate(self: *StringLiteral, index: usize) ?*Node { return null; } pub fn firstToken(self: *const StringLiteral) TokenIndex { return self.token; } pub fn lastToken(self: *const StringLiteral) TokenIndex { return self.token; } }; pub const MultilineStringLiteral = struct { base: Node, lines: LineList, pub const LineList = TokenList; pub fn iterate(self: *MultilineStringLiteral, index: usize) ?*Node { return null; } pub fn firstToken(self: *const MultilineStringLiteral) TokenIndex { return self.lines.at(0); } pub fn lastToken(self: *const MultilineStringLiteral) TokenIndex { return self.lines.at(self.lines.len - 1); } }; pub const CharLiteral = struct { base: Node, token: TokenIndex, pub fn iterate(self: *CharLiteral, index: usize) ?*Node { return null; } pub fn firstToken(self: *const CharLiteral) TokenIndex { return self.token; } pub fn lastToken(self: *const CharLiteral) TokenIndex { return self.token; } }; pub const BoolLiteral = struct { base: Node, token: TokenIndex, pub fn iterate(self: *BoolLiteral, index: usize) ?*Node { return null; } pub fn firstToken(self: *const BoolLiteral) TokenIndex { return self.token; } pub fn lastToken(self: *const BoolLiteral) TokenIndex { return self.token; } }; pub const NullLiteral = struct { base: Node, token: TokenIndex, pub fn iterate(self: *NullLiteral, index: usize) ?*Node { return null; } pub fn firstToken(self: *const NullLiteral) TokenIndex { return self.token; } pub fn lastToken(self: *const NullLiteral) TokenIndex { return self.token; } }; pub const UndefinedLiteral = struct { base: Node, token: TokenIndex, pub fn iterate(self: *UndefinedLiteral, index: usize) ?*Node { return null; } pub fn firstToken(self: *const UndefinedLiteral) TokenIndex { return self.token; } pub fn lastToken(self: *const UndefinedLiteral) TokenIndex { return self.token; } }; pub const AsmOutput = struct { base: Node, lbracket: TokenIndex, symbolic_name: *Node, constraint: *Node, kind: Kind, rparen: TokenIndex, pub const Kind = union(enum) { Variable: *Identifier, Return: *Node, }; pub fn iterate(self: *AsmOutput, index: usize) ?*Node { var i = index; if (i < 1) return self.symbolic_name; i -= 1; if (i < 1) return self.constraint; i -= 1; switch (self.kind) { Kind.Variable => |variable_name| { if (i < 1) return &variable_name.base; i -= 1; }, Kind.Return => |return_type| { if (i < 1) return return_type; i -= 1; }, } return null; } pub fn firstToken(self: *const AsmOutput) TokenIndex { return self.lbracket; } pub fn lastToken(self: *const AsmOutput) TokenIndex { return self.rparen; } }; pub const AsmInput = struct { base: Node, lbracket: TokenIndex, symbolic_name: *Node, constraint: *Node, expr: *Node, rparen: TokenIndex, pub fn iterate(self: *AsmInput, index: usize) ?*Node { var i = index; if (i < 1) return self.symbolic_name; i -= 1; if (i < 1) return self.constraint; i -= 1; if (i < 1) return self.expr; i -= 1; return null; } pub fn firstToken(self: *const AsmInput) TokenIndex { return self.lbracket; } pub fn lastToken(self: *const AsmInput) TokenIndex { return self.rparen; } }; pub const Asm = struct { base: Node, asm_token: TokenIndex, volatile_token: ?TokenIndex, template: *Node, outputs: OutputList, inputs: InputList, clobbers: ClobberList, rparen: TokenIndex, pub const OutputList = NodeList; pub const InputList = NodeList; pub const ClobberList = NodeList; pub fn iterate(self: *Asm, index: usize) ?*Node { var i = index; if (i < self.outputs.len) return self.outputs.at(index); i -= self.outputs.len; if (i < self.inputs.len) return self.inputs.at(index); i -= self.inputs.len; return null; } pub fn firstToken(self: *const Asm) TokenIndex { return self.asm_token; } pub fn lastToken(self: *const Asm) TokenIndex { return self.rparen; } }; pub const Unreachable = struct { base: Node, token: TokenIndex, pub fn iterate(self: *Unreachable, index: usize) ?*Node { return null; } pub fn firstToken(self: *const Unreachable) TokenIndex { return self.token; } pub fn lastToken(self: *const Unreachable) TokenIndex { return self.token; } }; pub const ErrorType = struct { base: Node, token: TokenIndex, pub fn iterate(self: *ErrorType, index: usize) ?*Node { return null; } pub fn firstToken(self: *const ErrorType) TokenIndex { return self.token; } pub fn lastToken(self: *const ErrorType) TokenIndex { return self.token; } }; pub const VarType = struct { base: Node, token: TokenIndex, pub fn iterate(self: *VarType, index: usize) ?*Node { return null; } pub fn firstToken(self: *const VarType) TokenIndex { return self.token; } pub fn lastToken(self: *const VarType) TokenIndex { return self.token; } }; pub const DocComment = struct { base: Node, lines: LineList, pub const LineList = TokenList; pub fn iterate(self: *DocComment, index: usize) ?*Node { return null; } pub fn firstToken(self: *const DocComment) TokenIndex { return self.lines.at(0); } pub fn lastToken(self: *const DocComment) TokenIndex { return self.lines.at(self.lines.len - 1); } }; pub const TestDecl = struct { base: Node, doc_comments: ?*DocComment, test_token: TokenIndex, name: *Node, body_node: *Node, pub fn iterate(self: *TestDecl, index: usize) ?*Node { var i = index; if (i < 1) return self.body_node; i -= 1; return null; } pub fn firstToken(self: *const TestDecl) TokenIndex { return self.test_token; } pub fn lastToken(self: *const TestDecl) TokenIndex { return self.body_node.lastToken(); } }; pub const Recovery = struct { base: Node, token: *Token, pub fn iterate(self: *Recovery, index: usize) ?*Node { return null; } pub fn firstToken(self: *const Recovery) TokenIndex { return self.token; } pub fn lastToken(self: *const Recovery) TokenIndex { return self.token; } }; };
zig/zig_grammar.types.zig
const std = @import("std"); const common = @import("./_common.zig"); pub const default = common.Main(struct { pub const source_url = "https://unicode.org/Public/UCD/latest/ucd/ArabicShaping.txt"; pub const dest_file = "src/arabic_shaping.zig"; pub const dest_header = \\pub const Shaping = struct { \\ codepoint: u21, \\ schematic_name: []const u8, \\ joining_type: Joining.Type, \\ joining_group: Joining.Group, \\}; \\ \\pub const Joining = struct { \\ pub const Type = enum { \\ U, \\ D, \\ R, \\ C, \\ T, \\ L, \\ }; \\ \\ pub const Group = enum { \\ No_Joining_Group, \\ YEH, \\ ALEF, \\ WAW, \\ BEH, \\ TEH_MARBUTA, \\ HAH, \\ DAL, \\ REH, \\ SEEN, \\ SAD, \\ TAH, \\ AIN, \\ GAF, \\ FARSI_YEH, \\ FEH, \\ QAF, \\ KAF, \\ LAM, \\ MEEM, \\ NOON, \\ HEH, \\ SWASH_KAF, \\ NYA, \\ KNOTTED_HEH, \\ HEH_GOAL, \\ TEH_MARBUTA_GOAL, \\ YEH_WITH_TAIL, \\ YEH_BARREE, \\ ALAPH, \\ BETH, \\ GAMAL, \\ DALATH_RISH, \\ HE, \\ SYRIAC_WAW, \\ ZAIN, \\ HETH, \\ TETH, \\ YUDH, \\ YUDH_HE, \\ KAPH, \\ LAMADH, \\ MIM, \\ NUN, \\ SEMKATH, \\ FINAL_SEMKATH, \\ E, \\ PE, \\ REVERSED_PE, \\ SADHE, \\ QAPH, \\ SHIN, \\ TAW, \\ ZHAIN, \\ KHAPH, \\ FE, \\ BURUSHASKI_YEH_BARREE, \\ MALAYALAM_NGA, \\ MALAYALAM_JA, \\ MALAYALAM_NYA, \\ MALAYALAM_TTA, \\ MALAYALAM_NNA, \\ MALAYALAM_NNNA, \\ MALAYALAM_BHA, \\ MALAYALAM_RA, \\ MALAYALAM_LLA, \\ MALAYALAM_LLLA, \\ MALAYALAM_SSA, \\ ROHINGYA_YEH, \\ STRAIGHT_WAW, \\ AFRICAN_FEH, \\ AFRICAN_QAF, \\ AFRICAN_NOON, \\ MANICHAEAN_ALEPH, \\ MANICHAEAN_BETH, \\ MANICHAEAN_GIMEL, \\ MANICHAEAN_DALETH, \\ MANICHAEAN_WAW, \\ MANICHAEAN_ZAYIN, \\ MANICHAEAN_HETH, \\ MANICHAEAN_TETH, \\ MANICHAEAN_YODH, \\ MANICHAEAN_KAPH, \\ MANICHAEAN_LAMEDH, \\ MANICHAEAN_DHAMEDH, \\ MANICHAEAN_THAMEDH, \\ MANICHAEAN_MEM, \\ MANICHAEAN_NUN, \\ MANICHAEAN_SAMEKH, \\ MANICHAEAN_AYIN, \\ MANICHAEAN_PE, \\ MANICHAEAN_SADHE, \\ MANICHAEAN_QOPH, \\ MANICHAEAN_RESH, \\ MANICHAEAN_TAW, \\ MANICHAEAN_ONE, \\ MANICHAEAN_FIVE, \\ MANICHAEAN_TEN, \\ MANICHAEAN_TWENTY, \\ MANICHAEAN_HUNDRED, \\ HANIFI_ROHINGYA_PA, \\ HANIFI_ROHINGYA_KINNA_YA, \\ }; \\}; \\ \\pub const data = [_]Shaping{ \\ ; pub const dest_footer = \\}; \\ ; pub fn exec(alloc: *std.mem.Allocator, line: []const u8, writer: anytype) !bool { var it = std.mem.split(line, ";"); const c = std.mem.trim(u8, it.next().?, " "); const n = std.mem.trim(u8, it.next().?, " "); const t = std.mem.trim(u8, it.next().?, " "); const g = std.mem.trim(u8, it.next().?, " "); const g2 = try std.mem.replaceOwned(u8, alloc, g, " ", "_"); try common.stringToEnum(@import("../src/lib.zig").arabic_shaping.Joining.Type, t); try common.stringToEnum(@import("../src/lib.zig").arabic_shaping.Joining.Group, g2); try writer.print(" .{{ .codepoint = 0x{s}, .schematic_name = \"{s}\", .joining_type = .{s}, .joining_group = .{s} }},\n", .{ c, n, t, g2 }); return true; } });
scripts/arabic_shaping.zig
const std = @import("std"); const assert = std.debug.assert; const testing = std.testing; const dbgLog_ = @import("Log.zig").dbgLog; const HTTPMessageParser = @import("HTTPMessageParser.zig"); const parse = @import("Parse.zig"); const Files = @import("Files.zig"); const TCPServer = @import("TCPServer.zig"); const TLSConnection = @import("TLS.zig").TLSConnection; const httpExtraHeaders = @import("Config.zig").httpExtraHeaders; pub fn dbgLog(comptime s: []const u8, args: var) void { dbgLog_("HTTPS: " ++ s, args); } const c = @cImport({ @cInclude("stdio.h"); }); pub const RequestResponseState = struct { http_version: u1, keep_alive: bool, request_type: ?HTTPMessageParser.RequestType, // null -> invalid request, sends http error in sendResponse() file: ?[]const u8, // Only valid if request_type != null. null -> file not found mime_type: ?[]const u8, response_headers_sent: bool = false, data_sent: u32 = 0 }; fn doParse(request: []const u8, http_version: *u1, request_type: *HTTPMessageParser.RequestType, url: *([]const u8), keep_alive: *bool) !u32 { var s = request; request_type.* = try HTTPMessageParser.getRequestType(&s); url.* = try HTTPMessageParser.getRequestURL(&s); http_version.* = try HTTPMessageParser.verifyHTTPVersion(&s); dbgLog("http request [{}], url [{}]", .{ request_type.*, url.* }); // Default keep-alive setting keep_alive.* = http_version.* == 1; while (true) { const header = try HTTPMessageParser.getNextHeaderField(&s); if (header == null) { break; } dbgLog("header: [{}]", .{header.?[0..std.math.min(256, header.?.len)]}); var header_data = HTTPMessageParser.getHeader(header.?, "connection"); if (header_data != null) { if (parse.caseInsensitiveCompareIgnoreEndWhitespace(header_data.?, "keep-alive")) { keep_alive.* = true; } else if (parse.caseInsensitiveCompareIgnoreEndWhitespace(header_data.?, "close")) { keep_alive.* = false; } } } dbgLog("-- Header ends --\n", .{}); // Skip any extra whitespace between requests. parse.skipWhitespace(&s) catch { return @intCast(u32, request.len); }; return @intCast(u32, request.len - s.len); } test "HTTP Parse" { const http_request = "GET /a HTTP/1.0\r\nhost:b\r\ncoNNection: keep-alive \r\n\r\n"; var http_version: u1 = undefined; var request_type: HTTPMessageParser.RequestType = undefined; var url: []const u8 = undefined; var keep_alive: bool = undefined; const bytes_read = try doParse(http_request, &http_version, &request_type, &url, &keep_alive); testing.expect(http_version == 0); testing.expect(request_type == .GET); testing.expect(std.mem.eql(u8, url, "/a")); testing.expect(keep_alive); testing.expect(bytes_read == http_request.len); } // Returns false if only part of the header has been sent (no response is sent) // Returns true if the response has been delt with pub fn parseRequest(request: *([]const u8)) !(?RequestResponseState) { var http_version: u1 = undefined; var request_type: HTTPMessageParser.RequestType = undefined; var url: []const u8 = undefined; var keep_alive: bool = undefined; const bytes_read = doParse(request.*, &http_version, &request_type, &url, &keep_alive) catch |e| { if (e == error.EndOfString or e == error.EmptyString) { dbgLog("End of data {}\n", .{e}); return null; } else { dbgLog("Parse error: {}\n", .{e}); return e; } }; request.* = request.*[bytes_read..]; if (request_type == HTTPMessageParser.RequestType.GET) { var mime_type: ?[]const u8 = undefined; const file_data = Files.getFile(url, &mime_type); if (file_data == null) { dbgLog("File not found: [{}]\n", .{url}); return RequestResponseState{ .http_version = http_version, .keep_alive = keep_alive, .request_type = HTTPMessageParser.RequestType.GET, .file = null, .mime_type = null, }; } else { return RequestResponseState{ .http_version = http_version, .keep_alive = keep_alive, .request_type = HTTPMessageParser.RequestType.GET, .file = file_data, .mime_type = mime_type, }; } } else { dbgLog("Not a get. Sending 400 bad request.\n", .{}); return RequestResponseState{ .http_version = http_version, .keep_alive = keep_alive, .request_type = null, .file = undefined, .mime_type = null, }; } } // Assumes the TLS buffer has enough room to store the maximum header size pub fn sendResponse(conn: usize, tls: *TLSConnection, request_response_state: *?RequestResponseState) !void { assert(request_response_state.* != null); const http_version = request_response_state.*.?.http_version; const keep_alive = request_response_state.*.?.keep_alive; if (!request_response_state.*.?.response_headers_sent) { // Write buffer has been cleared (or has enough space) (HTTPSState.zig) so buffered writes are guaranteed to work if (request_response_state.*.?.request_type == null) { dbgLog("Sending: 400 Bad Request", .{}); try tls.bufferedWriteG(conn, "HTTP/1."); try tls.bufferedWriteG(conn, if (request_response_state.*.?.http_version == 1) "1" else "0"); try tls.bufferedWriteG(conn, " 400 Bad Request\r\nContent-Length: 19\r\n\r\n<h1>400 Bad Request"); try tls.flushWrite(conn); request_response_state.* = null; } else if (request_response_state.*.?.file == null) { dbgLog("Sending: 404 Not Found", .{}); try tls.bufferedWriteG(conn, "HTTP/1."); try tls.bufferedWriteG(conn, if (request_response_state.*.?.http_version == 1) "1" else "0"); try tls.bufferedWriteG(conn, " 404 Not Found\r\nContent-Length: 22\r\n\r\n<h1>404 Page Not Found"); try tls.flushWrite(conn); request_response_state.* = null; } else { dbgLog("Sending: 200 OK", .{}); try tls.bufferedWriteG(conn, "HTTP/1."); try tls.bufferedWriteG(conn, if (request_response_state.*.?.http_version == 1) "1" else "0"); try tls.bufferedWriteG(conn, " 200 OK\r\n" ++ "Content-Length: "); var length_string = [_]u8{0} ** 20; const length_string_len = c.snprintf(length_string[0..], length_string.len, "%d", @intCast(u32, request_response_state.*.?.file.?.len)); if (length_string_len < 1) { return error.SnprintfError; } dbgLog("content-length {}", .{length_string[0..@intCast(u32, length_string_len)]}); try tls.bufferedWriteG(conn, length_string[0..@intCast(u32, length_string_len)]); const mime_type = request_response_state.*.?.mime_type; if (mime_type != null) { try tls.bufferedWriteG(conn, "\r\nContent-Type: "); try tls.bufferedWriteG(conn, mime_type.?); } if (request_response_state.*.?.keep_alive) { try tls.bufferedWriteG(conn, "\r\nConnection: keep-alive\r\n"); } else { try tls.bufferedWriteG(conn, "\r\nConnection: close\r\n"); } try tls.bufferedWriteG(conn, httpExtraHeaders()); try tls.bufferedWriteG(conn, "\r\n"); request_response_state.*.?.response_headers_sent = true; } } if (request_response_state.* != null) { if (request_response_state.*.?.file == null) { request_response_state.* = null; } else { dbgLog("Sending file data. Data sent so far: {}", .{request_response_state.*.?.data_sent}); request_response_state.*.?.data_sent += try tls.bufferedWrite(conn, request_response_state.*.?.file.?[request_response_state.*.?.data_sent..]); dbgLog("Data sent so far now: {}", .{request_response_state.*.?.data_sent}); if (request_response_state.*.?.data_sent == request_response_state.*.?.file.?.len) { dbgLog("Sending file data. Finished sending data", .{}); request_response_state.* = null; } } } if (!keep_alive and request_response_state.* == null) { try tls.flushWriteAndShutdown(conn); } }
src/HTTPRequestHandler.zig
const std = @import("std"); const print = std.debug.print; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day19.txt"); pub fn main() !void { var timer = try std.time.Timer.start(); var scanners = try calculateScanners(data); defer { deinitScanners(scanners); } print("🎁 Magnitude: {}\n", .{try numberOfBeacons(scanners)}); print("Day 19 - part 01 took {:15}ns\n", .{timer.lap()}); timer.reset(); print("🎁 Largest magnitude: {}\n", .{maxManhattan(scanners)}); print("Day 19 - part 02 took {:15}ns\n", .{timer.lap()}); print("❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️\n", .{}); } const Point = struct { x : i32, y : i32, z : i32, pub fn dump(me : *const @This()) void { print("({}, {}, {})\n", .{me.x, me.y, me.z}); } pub fn init(x : i32, y : i32, z : i32) @This() { return Point { .x = x, .y = y, .z = z }; } pub fn equals(me : *const @This(), other : @This()) bool { return me.x == other.x and me.y == other.y and me.z == other.z; } pub fn sub(me : *const @This(), other : @This()) @This() { return Point { .x = me.x - other.x, .y = me.y - other.y, .z = me.z - other.z, }; } pub fn add(me : *const @This(), other : @This()) @This() { return Point { .x = me.x + other.x, .y = me.y + other.y, .z = me.z + other.z, }; } pub fn abs(me : *const @This()) @This() { return Point { .x = if (me.x < 0) -me.x else me.x, .y = if (me.y < 0) -me.y else me.y, .z = if (me.z < 0) -me.z else me.z, }; } }; const FixedBeaconIterator = struct { buffer : []const Point, index : usize, pub fn init(buffer : []const Point) @This() { return @This() { .buffer = buffer, .index = 0 }; } pub fn next(me : *@This()) ?Point { if (me.index == me.buffer.len) { return null; } var point = me.buffer[me.index]; me.index += 1; return point; } }; const BeaconIterator = struct { buffer : []const Point, index : usize, rotation : u6, pub fn init(buffer : []const Point, rotation : u6) @This() { // There are only 24 'real' rotations , continuous from [0..20), then [24..27). // Map our input rotation into this range now. std.debug.assert(rotation < 24); var actualRotation = rotation; if (actualRotation >= 20) { actualRotation += 4; } return BeaconIterator { .buffer = buffer, .index = 0, .rotation = actualRotation, }; } pub fn next(me : *@This()) ?Point { if (me.index == me.buffer.len) { return null; } var point = me.buffer[me.index]; const xRotation = @intCast(u2, (me.rotation >> 0) & 0x3); const yRotation = @intCast(u2, (me.rotation >> 2) & 0x3); const zRotation = @intCast(u2, (me.rotation >> 4) & 0x3); { const aOld = point.x; const bOld = point.y; switch (xRotation) { 0 => {}, 1 => { // 90 degrees point.x = bOld; point.y = -aOld; }, 2 => { // 180 degrees point.x = -aOld; point.y = -bOld; }, 3 => { // 270 degrees point.x = -bOld; point.y = aOld; } } } { const aOld = point.y; const bOld = point.z; switch (yRotation) { 0 => {}, 1 => { // 90 degrees point.y = bOld; point.z = -aOld; }, 2 => { // 180 degrees point.y = -aOld; point.z = -bOld; }, 3 => { // 270 degrees point.y = -bOld; point.z = aOld; } } } { const aOld = point.x; const bOld = point.z; switch (zRotation) { 0 => {}, 1 => { // 90 degrees point.x = bOld; point.z = -aOld; }, 2 => { // 180 degrees point.x = -aOld; point.z = -bOld; }, 3 => { // 270 degrees point.x = -bOld; point.z = aOld; } } } // Bump our index too! me.index += 1; return point; } }; const Scanner = struct { beacons : std.ArrayList(Point), aligned : bool, position : ?Point, pub fn init(allocator : *std.mem.Allocator) @This() { return Scanner { .beacons = std.ArrayList(Point).init(gpa), .aligned = false, .position = null, }; } pub fn deinit(me : @This()) void { me.beacons.deinit(); } pub fn add(me : *@This(), point : Point) !void { try me.beacons.append(point); } pub fn fix(me : *@This(), rotation : u6, position : Point) void { var iterator = me.rotatedIterator(rotation); var index : u32 = 0; while (iterator.next()) |next| { me.beacons.items[index] = next.add(position); index += 1; } me.aligned = true; me.position = position; } pub fn fixedIterator(me : *const @This()) FixedBeaconIterator { std.debug.assert(me.aligned); std.debug.assert(me.beacons.items.len != 0); return FixedBeaconIterator.init(me.beacons.items); } pub fn rotatedIterator(me : *const @This(), rotation : u6) BeaconIterator { // We cannot rotate an already aligned scanner! std.debug.assert(!me.aligned); std.debug.assert(me.beacons.items.len != 0); return BeaconIterator.init(me.beacons.items, rotation); } }; pub fn deinitScanners(scanners : std.ArrayList(Scanner)) void { for (scanners.items) |scanner| { scanner.deinit(); } scanners.deinit(); } pub fn calculateScanners(input : []const u8) !std.ArrayList(Scanner) { var scanners = std.ArrayList(Scanner).init(gpa); var splitIterator = std.mem.split(input, "--- scanner "); while (splitIterator.next()) |split| { var lines = std.mem.tokenize(split, "\r\n"); // Skip the first line that is just 'N ---' const discard = lines.next(); var scanner = Scanner.init(gpa); while (lines.next()) |line| { var coordIterator = std.mem.tokenize(line, ","); const x = try std.fmt.parseInt(i32, coordIterator.next().?, 10); const y = try std.fmt.parseInt(i32, coordIterator.next().?, 10); const z = try std.fmt.parseInt(i32, coordIterator.next().?, 10); try scanner.add(Point.init(x, y, z)); } if (scanner.beacons.items.len == 0) { scanner.deinit(); } else { try scanners.append(scanner); } } // We are going to align all the scanners relative to scanner 0, so lock in // the alignment of scanner 0 now. scanners.items[0].fix(0, Point.init(0, 0, 0)); while (true) { var anyUnaligned = false; for (scanners.items) |*scanner, i| { for (scanners.items) |other, k| { if (scanner.aligned) { break; } // Skip ourselves. if (i == k) { continue; } anyUnaligned = true; // We need the other scanner to be aligned. if (!other.aligned) { continue; } var rotation : u5 = 0; while (rotation < 24) : (rotation += 1) { var fixedIterator = other.fixedIterator(); while (fixedIterator.next()) |fixed| { if (scanner.aligned) { break; } var rotatedIterator = scanner.rotatedIterator(rotation); while (rotatedIterator.next()) |rotated| { const diff = fixed.sub(rotated); var fixedIterator2 = other.fixedIterator(); var matches : u32 = 0; while (fixedIterator2.next()) |fixed2| { var rotatedIterator2 = scanner.rotatedIterator(rotation); while (rotatedIterator2.next()) |rotated2| { if (fixed2.equals(rotated2.add(diff))) { matches += 1; } } } if (matches >= 12) { scanner.fix(rotation, diff); break; } } } } } } if (!anyUnaligned) { break; } } return scanners; } pub fn numberOfBeacons(scanners : std.ArrayList(Scanner)) !u32 { var map = std.AutoHashMap(Point, void).init(gpa); defer { map.deinit(); } for (scanners.items) |scanner| { var iterator = scanner.fixedIterator(); while (iterator.next()) |beacon| { try map.put(beacon, .{}); } } return map.count(); } pub fn maxManhattan(scanners : std.ArrayList(Scanner)) i32 { var max : i32 = 0; for (scanners.items) |i| { for (scanners.items) |k| { const vector = i.position.?.sub(k.position.?).abs(); const distance = vector.x + vector.y + vector.z; max = std.math.max(max, distance); } } return max; } test "example" { const input = \\--- scanner 0 --- \\404,-588,-901 \\528,-643,409 \\-838,591,734 \\390,-675,-793 \\-537,-823,-458 \\-485,-357,347 \\-345,-311,381 \\-661,-816,-575 \\-876,649,763 \\-618,-824,-621 \\553,345,-567 \\474,580,667 \\-447,-329,318 \\-584,868,-557 \\544,-627,-890 \\564,392,-477 \\455,729,728 \\-892,524,684 \\-689,845,-530 \\423,-701,434 \\7,-33,-71 \\630,319,-379 \\443,580,662 \\-789,900,-551 \\459,-707,401 \\ \\--- scanner 1 --- \\686,422,578 \\605,423,415 \\515,917,-361 \\-336,658,858 \\95,138,22 \\-476,619,847 \\-340,-569,-846 \\567,-361,727 \\-460,603,-452 \\669,-402,600 \\729,430,532 \\-500,-761,534 \\-322,571,750 \\-466,-666,-811 \\-429,-592,574 \\-355,545,-477 \\703,-491,-529 \\-328,-685,520 \\413,935,-424 \\-391,539,-444 \\586,-435,557 \\-364,-763,-893 \\807,-499,-711 \\755,-354,-619 \\553,889,-390 \\ \\--- scanner 2 --- \\649,640,665 \\682,-795,504 \\-784,533,-524 \\-644,584,-595 \\-588,-843,648 \\-30,6,44 \\-674,560,763 \\500,723,-460 \\609,671,-379 \\-555,-800,653 \\-675,-892,-343 \\697,-426,-610 \\578,704,681 \\493,664,-388 \\-671,-858,530 \\-667,343,800 \\571,-461,-707 \\-138,-166,112 \\-889,563,-600 \\646,-828,498 \\640,759,510 \\-630,509,768 \\-681,-892,-333 \\673,-379,-804 \\-742,-814,-386 \\577,-820,562 \\ \\--- scanner 3 --- \\-589,542,597 \\605,-692,669 \\-500,565,-823 \\-660,373,557 \\-458,-679,-417 \\-488,449,543 \\-626,468,-788 \\338,-750,-386 \\528,-832,-391 \\562,-778,733 \\-938,-730,414 \\543,643,-506 \\-524,371,-870 \\407,773,750 \\-104,29,83 \\378,-903,-323 \\-778,-728,485 \\426,699,580 \\-438,-605,-362 \\-469,-447,-387 \\509,732,623 \\647,635,-688 \\-868,-804,481 \\614,-800,639 \\595,780,-596 \\ \\--- scanner 4 --- \\727,592,562 \\-293,-554,779 \\441,611,-461 \\-714,465,-776 \\-743,427,-804 \\-660,-479,-426 \\832,-632,460 \\927,-485,-438 \\408,393,-506 \\466,436,-512 \\110,16,151 \\-258,-428,682 \\-393,719,612 \\-211,-452,876 \\808,-476,-593 \\-575,615,604 \\-485,667,467 \\-680,325,-822 \\-627,-443,-432 \\872,-547,-609 \\833,512,582 \\807,604,487 \\839,-516,451 \\891,-625,532 \\-652,-548,-490 \\30,-46,-14 ; var scanners = try calculateScanners(input); defer { scanners.deinit(); } const total = try numberOfBeacons(scanners); try std.testing.expect(total == 79); const max = maxManhattan(scanners); try std.testing.expect(max == 3621); }
src/day19.zig
usingnamespace @import("psptypes.zig"); const enum_unnamed_5 = extern enum(c_int) { PSP_HTTP_VERSION_1_0, PSP_HTTP_VERSION_1_1, _, }; pub const PspHttpHttpVersion = enum_unnamed_5; const enum_unnamed_6 = extern enum(c_int) { PSP_HTTP_METHOD_GET, PSP_HTTP_METHOD_POST, PSP_HTTP_METHOD_HEAD, _, }; pub const PspHttpMethod = enum_unnamed_6; const enum_unnamed_7 = extern enum(c_int) { PSP_HTTP_AUTH_BASIC, PSP_HTTP_AUTH_DIGEST, _, }; pub const PspHttpAuthType = enum_unnamed_7; const enum_unnamed_8 = extern enum(c_int) { PSP_HTTP_PROXY_AUTO, PSP_HTTP_PROXY_MANUAL, _, }; pub const PspHttpProxyMode = enum_unnamed_8; const enum_unnamed_9 = extern enum(c_int) { PSP_HTTP_HEADER_OVERWRITE, PSP_HTTP_HEADER_ADD, _, }; pub const PspHttpAddHeaderMode = enum_unnamed_9; pub const PspHttpMallocFunction = ?fn (SceSize) callconv(.C) ?*c_void; pub const PspHttpReallocFunction = ?fn (?*c_void, SceSize) callconv(.C) ?*c_void; pub const PspHttpFreeFunction = ?fn (?*c_void) callconv(.C) void; pub const PspHttpPasswordCB = ?fn (c_int, PspHttpAuthType, [*c]const u8, [*c]u8, [*c]u8, SceBool, [*c][*c]u8, [*c]SceSize, [*c]SceBool) callconv(.C) c_int; pub extern fn sceHttpInit(unknown1: c_uint) c_int; pub extern fn sceHttpEnd() c_int; pub extern fn sceHttpCreateTemplate(agent: [*c]u8, unknown1: c_int, unknown2: c_int) c_int; pub extern fn sceHttpDeleteTemplate(templateid: c_int) c_int; pub extern fn sceHttpCreateConnection(templateid: c_int, host: [*c]u8, unknown1: [*c]u8, port: c_ushort, unknown2: c_int) c_int; pub extern fn sceHttpCreateConnectionWithURL(templateid: c_int, url: [*c]const u8, unknown1: c_int) c_int; pub extern fn sceHttpDeleteConnection(connectionid: c_int) c_int; pub extern fn sceHttpCreateRequest(connectionid: c_int, method: PspHttpMethod, path: [*c]u8, contentlength: SceULong64) c_int; pub extern fn sceHttpCreateRequestWithURL(connectionid: c_int, method: PspHttpMethod, url: [*c]u8, contentlength: SceULong64) c_int; pub extern fn sceHttpDeleteRequest(requestid: c_int) c_int; pub extern fn sceHttpSendRequest(requestid: c_int, data: ?*c_void, datasize: c_uint) c_int; pub extern fn sceHttpAbortRequest(requestid: c_int) c_int; pub extern fn sceHttpReadData(requestid: c_int, data: ?*c_void, datasize: c_uint) c_int; pub extern fn sceHttpGetContentLength(requestid: c_int, contentlength: [*c]SceULong64) c_int; pub extern fn sceHttpGetStatusCode(requestid: c_int, statuscode: [*c]c_int) c_int; pub extern fn sceHttpSetResolveTimeOut(id: c_int, timeout: c_uint) c_int; pub extern fn sceHttpSetResolveRetry(id: c_int, count: c_int) c_int; pub extern fn sceHttpSetConnectTimeOut(id: c_int, timeout: c_uint) c_int; pub extern fn sceHttpSetSendTimeOut(id: c_int, timeout: c_uint) c_int; pub extern fn sceHttpSetRecvTimeOut(id: c_int, timeout: c_uint) c_int; pub extern fn sceHttpEnableKeepAlive(id: c_int) c_int; pub extern fn sceHttpDisableKeepAlive(id: c_int) c_int; pub extern fn sceHttpEnableRedirect(id: c_int) c_int; pub extern fn sceHttpDisableRedirect(id: c_int) c_int; pub extern fn sceHttpEnableCookie(id: c_int) c_int; pub extern fn sceHttpDisableCookie(id: c_int) c_int; pub extern fn sceHttpSaveSystemCookie() c_int; pub extern fn sceHttpLoadSystemCookie() c_int; pub extern fn sceHttpAddExtraHeader(id: c_int, name: [*c]u8, value: [*c]u8, unknown1: c_int) c_int; pub extern fn sceHttpDeleteHeader(id: c_int, name: [*c]const u8) c_int; pub extern fn sceHttpsInit(unknown1: c_int, unknown2: c_int, unknown3: c_int, unknown4: c_int) c_int; pub extern fn sceHttpsEnd() c_int; pub extern fn sceHttpsLoadDefaultCert(unknown1: c_int, unknown2: c_int) c_int; pub extern fn sceHttpDisableAuth(id: c_int) c_int; pub extern fn sceHttpDisableCache(id: c_int) c_int; pub extern fn sceHttpEnableAuth(id: c_int) c_int; pub extern fn sceHttpEnableCache(id: c_int) c_int; pub extern fn sceHttpEndCache() c_int; pub extern fn sceHttpGetAllHeader(request: c_int, header: [*c][*c]u8, header_size: [*c]c_uint) c_int; pub extern fn sceHttpGetNetworkErrno(request: c_int, err_num: [*c]c_int) c_int; pub extern fn sceHttpGetProxy(id: c_int, activate_flag: [*c]c_int, mode: [*c]c_int, proxy_host: [*c]u8, len: SceSize, proxy_port: [*c]c_ushort) c_int; pub extern fn sceHttpInitCache(max_size: SceSize) c_int; pub extern fn sceHttpSetAuthInfoCB(id: c_int, cbfunc: PspHttpPasswordCB) c_int; pub extern fn sceHttpSetProxy(id: c_int, activate_flag: c_int, mode: c_int, new_proxy_host: [*c]const u8, new_proxy_port: c_ushort) c_int; pub extern fn sceHttpSetResHeaderMaxSize(id: c_int, header_size: c_uint) c_int; pub extern fn sceHttpSetMallocFunction(malloc_func: PspHttpMallocFunction, free_func: PspHttpFreeFunction, realloc_func: PspHttpReallocFunction) c_int;
src/psp/sdk/psphttp.zig
const Self = @This(); const std = @import("std"); const gpa = std.heap.c_allocator; const View = @import("View.zig"); const Output = @import("Output.zig"); const c = @import("c.zig"); const wl = @import("wayland").server.wl; const wlr = @import("wlroots"); const default_cursor_size = 24; const default_seat_name = "herbwm-seat0"; wl_server: *wl.Server, wlr_backend: *wlr.Backend, // TODO: Support headless backend. wlr_renderer: *wlr.Renderer, wlr_allocator: *wlr.Allocator, wlr_scene: *wlr.Scene, wlr_compositor: *wlr.Compositor, wlr_output_layout: *wlr.OutputLayout, new_output: wl.Listener(*wlr.Output), wlr_xdg_shell: *wlr.XdgShell, new_xdg_surface: wl.Listener(*wlr.XdgSurface), views: wl.list.Head(View, "link") = undefined, wlr_seat: *wlr.Seat, wlr_cursor: *wlr.Cursor, wlr_xcursor_manager: *wlr.XcursorManager, pub fn init(self: *Self) !void { // Creating the server itself. self.wl_server = try wl.Server.create(); errdefer self.wl_server.destroy(); // Determine the backend based on the current environment to render with such as opening an X11 window if an X11 server is running. // NOTE: This frees itself when the server is destroyed. self.wlr_backend = try wlr.Backend.autocreate(self.wl_server); // Determining the renderer based on the current environment. // Possible renderers: Pixman / GLES2 / Vulkan. self.wlr_renderer = try wlr.Renderer.autocreate(self.wlr_backend); errdefer self.wlr_renderer.destroy(); // Autocreate an allocator. An allocator acts as a bridge between the renderer and the backend allowing us to render to the screen by handling buffer creation. self.wlr_allocator = try wlr.Allocator.autocreate(self.wlr_backend, self.wlr_renderer); errdefer self.wlr_allocator.destroy(); // Create the compositor from the server and renderer. self.wlr_compositor = try wlr.Compositor.create(self.wl_server, self.wlr_renderer); // Creating a scene graph. This handles the servers rendering and damage tracking. self.wlr_scene = try wlr.Scene.create(); // Create an output layout to work with the physical arrangement of screens. self.wlr_output_layout = try wlr.OutputLayout.create(); errdefer self.wlr_output_layout.destroy(); // Creating a xdg_shell which is a wayland protocol for application windows. self.wlr_xdg_shell = try wlr.XdgShell.create(self.wl_server); //Configures a seat, which is a single "seat" at which a user sits and //operates the computer. This conceptually includes up to one keyboard, //pointer, touch, and drawing tablet device. We also rig up a listener to //let us know when new input devices are available on the backend. self.wlr_seat = try wlr.Seat.create(self.wl_server, default_seat_name); errdefer self.wlr_seat.destroy(); // Create a wlr cursor object which is a wlroots utility to track the cursor on the screen. self.wlr_cursor = try wlr.Cursor.create(); errdefer self.wlr_cursor.destroy(); // Create a Xcursor manager which loads up xcursor themes on all scale factors. We pass null for theme name and 24 for the cursor size. self.wlr_xcursor_manager = try wlr.XcursorManager.create(null, default_cursor_size); errdefer self.wlr_xcursor_manager.destroy(); // Initialize wl_shm, linux-dmabuf and other buffer factory protocols. try self.wlr_renderer.initServer(self.wl_server); // Attach the output layout to the scene graph so we get automatic damage tracking. try self.wlr_scene.attachOutputLayout(self.wlr_output_layout); // NOTE: These all free themselves when wlr_server is destroy. // Create the data device manager from the server, this generally handles the input events such as keyboard, mouse, touch etc. _ = try wlr.DataDeviceManager.create(self.wl_server); _ = try wlr.DataControlManagerV1.create(self.wl_server); _ = try wlr.ExportDmabufManagerV1.create(self.wl_server); _ = try wlr.GammaControlManagerV1.create(self.wl_server); _ = try wlr.ScreencopyManagerV1.create(self.wl_server); _ = try wlr.Viewporter.create(self.wl_server); // Assign the new output callback to said event. // // zig only intializes structs with default value when using .{} notation. Since were not using that, we call `.setNotify`. In other instances // we use `.init` on the listener. self.new_output.setNotify(newOutput); self.wlr_backend.events.new_output.add(&self.new_output); // Add a callback for when new surfaces are created. // // zig only intializes structs with default value when using .{} notation. Since were not using that, we call `.setNotify`. In other instances // we use `.init` on the listener. self.new_xdg_surface.setNotify(newXdgSurface); self.wlr_xdg_shell.events.new_surface.add(&self.new_xdg_surface); self.views.init(); } // Create the socket, start the backend, and setup the environment pub fn start(self: *Self) !void { // We create a slice of 11 u8's ( practically a string buffer ) in which we store the socket value to be pushed later onto the env_map. var buf: [11]u8 = undefined; const socket = try self.wl_server.addSocketAuto(&buf); try self.wlr_backend.start(); // Set the wayland_display environment variable. if (c.setenv("WAYLAND_DISPLAY", socket, 1) < 0) return error.SetenvError; } pub fn deinit(self: *Self) void { // Destroy all clients of the server. self.wl_server.destroyClients(); self.wlr_backend.destroy(); self.wlr_renderer.destroy(); self.wlr_allocator.destroy(); // Destroy the server. self.wl_server.destroy(); } // Callback that gets triggered on existence of a new output. pub fn newOutput(listener: *wl.Listener(*wlr.Output), wlr_output: *wlr.Output) void { // Getting the server out of the listener. Field Parent Pointer - get a pointer to the parent struct from a field. const self = @fieldParentPtr(Self, "new_output", listener); // Configure the output created by the backend to use our allocator and renderer. if (!wlr_output.initRender(self.wlr_allocator, self.wlr_renderer)) return; // Some backends don't have modes. DRM+KMS does, and we need to set a mode before using the target. if (wlr_output.preferredMode()) |mode| { wlr_output.setMode(mode); wlr_output.enable(true); wlr_output.commit() catch return; } // Allocate memory to a new instance of output struct. const output = gpa.create(Output) catch { std.log.err("Failed to allocate new output", .{}); return; }; // Instantiate the output struct. output.* = .{ .server = self, .wlr_output = wlr_output, }; // Add a callback for the frame event from the output struct. // // Since we used .{} notation, the frame callback has been initialized so we don't need to call setNotify. wlr_output.events.frame.add(&output.frame); // Add the new output to the output_layout for automatic management by wlroots. self.wlr_output_layout.addAuto(wlr_output); } pub fn newXdgSurface(listener: *wl.Listener(*wlr.XdgSurface), xdg_surface: *wlr.XdgSurface) void { const self = @fieldParentPtr(Self, "new_xdg_surface", listener); switch (xdg_surface.role) { .toplevel => { const view = gpa.create(View) catch { std.log.err("Failed to allocate new view", .{}); return; }; view.* = .{ .server = self, .xdg_surface = xdg_surface, .scene_node = self.wlr_scene.node.createSceneXdgSurface(xdg_surface) catch { gpa.destroy(view); std.log.err("Failed to allocate new view", .{}); return; }, }; view.scene_node.data = @ptrToInt(view); xdg_surface.data = @ptrToInt(view.scene_node); xdg_surface.events.map.add(&view.map); //xdg_surface.events.unmap.add(&view.unmap); }, .popup => { // To be implemented soon. }, .none => unreachable, } } pub fn focusView(self: *Self, view: *View, surface: *wlr.Surface) void { if (self.wlr_seat.keyboard_state.focused_surface) |previous_surface| { if (previous_surface == surface) return; if (previous_surface.isXdgSurface()) { const xdg_surface = wlr.XdgSurface.fromWlrSurface(previous_surface); _ = xdg_surface.role_data.toplevel.setActivated(false); } } view.scene_node.raiseToTop(); view.link.remove(); self.views.prepend(view); _ = view.xdg_surface.role_data.toplevel.setActivated(true); }
herb/Server.zig
const std = @import("std"); const testing = std.testing; const mem = std.mem; const c = @import("c.zig").c; const Image = @This(); /// The width of this image, in pixels. width: u32, /// The height of this image, in pixels. height: u32, /// The pixel data of this image, arranged left-to-right, top-to-bottom. pixels: []u8, /// Whether or not the pixels data is owned by you (true) or GLFW (false). owned: bool, /// Initializes a new owned image with the given size and pixel_data_len of undefined .pixel values. pub inline fn init(allocator: mem.Allocator, width: u32, height: u32, pixel_data_len: usize) !Image { const buf = try allocator.alloc(u8, pixel_data_len); return Image{ .width = width, .height = height, .pixels = buf, .owned = true, }; } /// Turns a GLFW / C image into the nicer Zig type, and sets `.owned = false`. /// /// The length of pixel data must be supplied, as GLFW's image type does not itself describe the /// number of bytes required per pixel / the length of the pixel data array. /// /// The returned memory is valid for as long as the GLFW C memory is valid. pub inline fn fromC(native: c.GLFWimage, pixel_data_len: usize) Image { return Image{ .width = @intCast(u32, native.width), .height = @intCast(u32, native.height), .pixels = native.pixels[0..pixel_data_len], .owned = false, }; } /// Turns the nicer Zig type into a GLFW / C image, for passing into GLFW C functions. /// /// The returned memory is valid for as long as the Zig memory is valid. pub inline fn toC(self: Image) c.GLFWimage { return c.GLFWimage{ .width = @intCast(c_int, self.width), .height = @intCast(c_int, self.height), .pixels = &self.pixels[0], }; } /// Deinitializes the memory using the allocator iff `.owned = true`. pub inline fn deinit(self: Image, allocator: mem.Allocator) void { if (self.owned) allocator.free(self.pixels); } test "conversion" { const allocator = testing.allocator; const image = try Image.init(allocator, 256, 256, 256 * 256 * 4); defer image.deinit(allocator); const glfw = image.toC(); _ = Image.fromC(glfw, image.width * image.height * 4); }
glfw/src/Image.zig
const std = @import("std"); const imgui = @import("imgui"); const impl_glfw = @import("imgui_impl_glfw.zig"); const impl_gl3 = @import("imgui_impl_opengl3.zig"); const glfw = @import("include/glfw.zig"); const gl = @import("include/gl.zig"); const is_darwin = switch (std.builtin.os.tag) { .macosx, .ios, .watchos, .tvos => true, else => false, }; fn glfw_error_callback(err: c_int, description: ?[*:0]const u8) callconv(.C) void { std.debug.warn("Glfw Error {}: {}\n", .{ err, description }); } pub fn main() !void { // Setup window _ = glfw.glfwSetErrorCallback(glfw_error_callback); if (glfw.glfwInit() == 0) return error.GlfwInitFailed; // Decide GL+GLSL versions const glsl_version = if (is_darwin) "#version 150" else "#version 130"; if (is_darwin) { // GL 3.2 + GLSL 150 glfw.glfwWindowHint(glfw.GLFW_CONTEXT_VERSION_MAJOR, 3); glfw.glfwWindowHint(glfw.GLFW_CONTEXT_VERSION_MINOR, 2); glfw.glfwWindowHint(glfw.GLFW_OPENGL_PROFILE, glfw.GLFW_OPENGL_CORE_PROFILE); // 3.2+ only glfw.glfwWindowHint(glfw.GLFW_OPENGL_FORWARD_COMPAT, gl.GL_TRUE); // Required on Mac } else { // GL 3.0 + GLSL 130 glfw.glfwWindowHint(glfw.GLFW_CONTEXT_VERSION_MAJOR, 3); glfw.glfwWindowHint(glfw.GLFW_CONTEXT_VERSION_MINOR, 0); //glfw.glfwWindowHint(glfw.GLFW_OPENGL_PROFILE, glfw.GLFW_OPENGL_CORE_PROFILE); // 3.2+ only //glfw.glfwWindowHint(glfw.GLFW_OPENGL_FORWARD_COMPAT, gl.GL_TRUE); // 3.0+ only } // Create window with graphics context const window = glfw.glfwCreateWindow(1280, 720, "Dear ImGui GLFW+OpenGL3 example", null, null); if (window == null) return error.GlfwCreateWindowFailed; glfw.glfwMakeContextCurrent(window); glfw.glfwSwapInterval(1); // Enable vsync // Initialize OpenGL loader if (gl.gladLoadGL() == 0) return error.GladLoadGLFailed; // Setup Dear ImGui context imgui.CHECKVERSION(); _ = imgui.CreateContext(); const io = imgui.GetIO(); //io.ConfigFlags |= imgui.ConfigFlags.NavEnableKeyboard; // Enable Keyboard Controls //io.ConfigFlags |= imgui.ConfigFlags.NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style imgui.StyleColorsDark(); //imgui.StyleColorsClassic(); // Setup Platform/Renderer bindings _ = impl_glfw.InitForOpenGL(window.?, true); _ = impl_gl3.Init(glsl_version); // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Read 'docs/FONTS.txt' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts.AddFontDefault(); //io.Fonts.AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0); //io.Fonts.AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0); //io.Fonts.AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0); //io.Fonts.AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0); //ImFont* font = io.Fonts.AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0, null, io.Fonts->GetGlyphRangesJapanese()); //IM_ASSERT(font != NULL); // Our state var show_demo_window = true; var show_another_window = false; var clear_color = imgui.Vec4{ .x = 0.45, .y = 0.55, .z = 0.60, .w = 1.00 }; var slider_value: f32 = 0; var counter: i32 = 0; // Main loop while (glfw.glfwWindowShouldClose(window) == 0) { // Poll and handle events (inputs, window resize, etc.) // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. glfw.glfwPollEvents(); // Start the Dear ImGui frame impl_gl3.NewFrame(); impl_glfw.NewFrame(); imgui.NewFrame(); // 1. Show the big demo window (Most of the sample code is in imgui.ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). if (show_demo_window) imgui.ShowDemoWindowExt(&show_demo_window); // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. { _ = imgui.Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it. imgui.Text("This is some useful text."); // Display some text (you can use a format strings too) _ = imgui.Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state _ = imgui.Checkbox("Another Window", &show_another_window); _ = imgui.SliderFloat("float", &slider_value, 0.0, 1.0); // Edit 1 float using a slider from 0.0 to 1.0 _ = imgui.ColorEdit3("clear color", @ptrCast(*[3]f32, &clear_color)); // Edit 3 floats representing a color if (imgui.Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) counter += 1; imgui.SameLine(); imgui.Text("counter = %d", counter); imgui.Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0 / imgui.GetIO().Framerate, imgui.GetIO().Framerate); imgui.End(); } // 3. Show another simple window. if (show_another_window) { _ = imgui.BeginExt("Another Window", &show_another_window, .{}); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked) imgui.Text("Hello from another window!"); if (imgui.Button("Close Me")) show_another_window = false; imgui.End(); } // Rendering imgui.Render(); var display_w: c_int = 0; var display_h: c_int = 0; glfw.glfwGetFramebufferSize(window, &display_w, &display_h); gl.glViewport(0, 0, display_w, display_h); gl.glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); gl.glClear(gl.GL_COLOR_BUFFER_BIT); impl_gl3.RenderDrawData(imgui.GetDrawData()); glfw.glfwSwapBuffers(window); } // Cleanup impl_gl3.Shutdown(); impl_glfw.Shutdown(); imgui.DestroyContext(); glfw.glfwDestroyWindow(window); glfw.glfwTerminate(); }
examples/example_glfw_opengl3.zig
const std = @import("std"); const expect = std.testing.expect; const expectError = std.testing.expectError; const print = std.debug.print; pub const Error = error{ NotExhaustiveEnumError, ParseError, }; /// Get a parser function for the exhaustive enum E. pub fn EnumParser(comptime E: type) Error!(fn ([]const u8) Error!E) { if (@typeInfo(E) != .Enum or !@typeInfo(E).Enum.is_exhaustive) { return Error.NotExhaustiveEnumError; } return struct { const EntryList = std.ArrayListUnmanaged(HashMap.Entry); const HashMap = std.StringArrayHashMapUnmanaged(E); const hash_map: HashMap = .{ .entries = enumToEntries(), }; fn enumToEntries() EntryList { const n_values: u32 = @typeInfo(E).Enum.fields.len; var entries: [n_values]HashMap.Entry = undefined; inline for (@typeInfo(E).Enum.fields) |f, i| { // no fields have duplicated values entries[i] = .{ .hash = std.array_hash_map.hashString(f.name), .key = f.name, // f.value are comptime_ints, so need a cast .value = @intToEnum(E, f.value), }; } return EntryList{ .items = entries[0..], .capacity = n_values, }; } pub fn parse(string: []const u8) Error!E { const entry = @This().hash_map.get(string); if (entry) |e| { return e; } else { return Error.ParseError; } } }.parse; } test "non-exhaustive enum" { const Amount = enum(u8) { one, two, five, twenty, _ }; expectError(Error.NotExhaustiveEnumError, EnumParser(Amount)); } test "basic" { const EyeColor = enum { blu, hzl, gry, mag, ppl, grn, azure, blk, wht, ggg, pdp, rainbow, ddd, pqpqpd, da, z, q, dz0dz }; const ecParser = try EnumParser(EyeColor); expect((try ecParser("blu")) == EyeColor.blu); expectError(Error.ParseError, ecParser("???")); }
src/enum_parser.zig
const Span = @import("basics.zig").Span; const ConstantOrBuffer = @import("trigger.zig").ConstantOrBuffer; const fc32bit: f32 = 1 << 32; inline fn clamp01(v: f32) f32 { return if (v < 0.0) 0.0 else if (v > 1.0) 1.0 else v; } // 32-bit value into float with 23 bits precision inline fn utof23(x: u32) f32 { return @bitCast(f32, (x >> 9) | 0x3f800000) - 1; } // float from [0,1) into 0.32 unsigned fixed-point inline fn ftou32(v: f32) u32 { return @floatToInt(u32, v * fc32bit * 0.99995); } // this is a higher quality version of the square wave oscillator in // mod_oscillator.zig. it deals with aliasing by computing an average value for // each sample. however it doesn't support sweeping the input params (frequency // etc.) pub const PulseOsc = struct { pub const num_outputs = 1; pub const num_temps = 0; pub const Params = struct { sample_rate: f32, freq: ConstantOrBuffer, color: f32, }; cnt: u32, pub fn init() PulseOsc { return .{ .cnt = 0, }; } pub fn paint( self: *PulseOsc, span: Span, outputs: [num_outputs][]f32, temps: [num_temps][]f32, note_id_changed: bool, params: Params, ) void { switch (params.freq) { .constant => |freq| { self.paintConstantFrequency( outputs[0][span.start..span.end], params.sample_rate, freq, params.color, ); }, .buffer => |freq| { self.paintControlledFrequency( outputs[0][span.start..span.end], params.sample_rate, freq[span.start..span.end], params.color, ); } } } fn paintConstantFrequency( self: *PulseOsc, output: []f32, sample_rate: f32, freq: f32, color: f32, ) void { if (freq < 0 or freq > sample_rate / 8.0) { return; } // note: farbrausch code includes some explanatory comments. i've // preserved the variable names they used, but condensed the code var cnt = self.cnt; const SRfcobasefrq = fc32bit / sample_rate; const ifreq = @floatToInt(u32, SRfcobasefrq * freq); const brpt = ftou32(clamp01(color)); const gain = 0.7; const gdf = gain / utof23(ifreq); const col = utof23(brpt); const cc121 = gdf * 2.0 * (col - 1.0) + gain; const cc212 = gdf * 2.0 * col - gain; var state = if ((cnt -% ifreq) < brpt) @as(u32, 0b011) else @as(u32, 0b000); var i: usize = 0; while (i < output.len) : (i += 1) { const p = utof23(cnt); state = ((state << 1) | @boolToInt(cnt < brpt)) & 3; const s = state | (@as(u32, @boolToInt(cnt < ifreq)) << 2); output[i] += switch (s) { 0b011 => gain, // up 0b000 => -gain, // down 0b010 => gdf * 2.0 * (col - p) + gain, // up down 0b101 => gdf * 2.0 * p - gain, // down up 0b111 => cc121, // up down up 0b100 => cc212, // down up down else => unreachable, }; cnt +%= ifreq; } self.cnt = cnt; } fn paintControlledFrequency( self: *PulseOsc, output: []f32, sample_rate: f32, freq: []const f32, color: f32, ) void { // TODO - implement antialiasing here // TODO - add equivalent of the bad frequency check at the top of // paintConstantFrequency var cnt = self.cnt; const SRfcobasefrq = fc32bit / sample_rate; const brpt = ftou32(clamp01(color)); const gain: f32 = 0.7; var i: usize = 0; while (i < output.len) : (i += 1) { const ifreq = @floatToInt(u32, SRfcobasefrq * freq[i]); output[i] += if ((cnt -% ifreq) < brpt) gain else -gain; cnt +%= ifreq; } self.cnt = cnt; } };
src/zang/mod_pulseosc.zig
const c = @import("gl"); const std = @import("std"); const zalgebra = @import("zalgebra"); const Thread = std.Thread; const Allocator = std.mem.Allocator; const Window = @import("didot-window").Window; // TODO: get rid of that const windowContextLock = @import("didot-window").windowContextLock; const windowContextUnlock = @import("didot-window").windowContextUnlock; pub const ShaderError = error{ ShaderCompileError, InvalidContextError }; /// The type used for meshes's elements pub const MeshElementType = c.GLuint; pub const Mesh = struct { // OpenGL related variables vao: c.GLuint = 0, vbo: c.GLuint, ebo: ?c.GLuint, /// how many elements this Mesh has elements: usize, vertices: usize, pub fn create(vertices: []f32, elements: ?[]c.GLuint) Mesh { var vbo: c.GLuint = 0; c.glGenBuffers(1, &vbo); c.glBindBuffer(c.GL_ARRAY_BUFFER, vbo); c.glBufferData(c.GL_ARRAY_BUFFER, @intCast(c_long, vertices.len * @sizeOf(f32)), vertices.ptr, c.GL_STATIC_DRAW); const stride = 8 * @sizeOf(f32); var vao: c.GLuint = 0; c.glGenVertexArrays(1, &vao); c.glBindVertexArray(vao); c.glVertexAttribPointer(0, 3, c.GL_FLOAT, c.GL_FALSE, stride, @intToPtr(*allowzero const anyopaque, 0)); c.glVertexAttribPointer(1, 3, c.GL_FLOAT, c.GL_FALSE, stride, @intToPtr(*allowzero const anyopaque, 3 * @sizeOf(f32))); c.glVertexAttribPointer(2, 2, c.GL_FLOAT, c.GL_FALSE, stride, @intToPtr(*allowzero const anyopaque, 6 * @sizeOf(f32))); c.glEnableVertexAttribArray(0); c.glEnableVertexAttribArray(1); c.glEnableVertexAttribArray(2); var ebo: c.GLuint = 0; var elementsSize: ?usize = null; if (elements) |elem| { c.glGenBuffers(1, &ebo); c.glBindBuffer(c.GL_ELEMENT_ARRAY_BUFFER, ebo); c.glBufferData(c.GL_ELEMENT_ARRAY_BUFFER, @intCast(c_long, elem.len * @sizeOf(c.GLuint)), elem.ptr, c.GL_STATIC_DRAW); elementsSize = elem.len; } std.log.scoped(.didot).debug("Created mesh (VAO = {}, VBO = {})", .{vao, vbo}); return Mesh{ .vao = vao, .vbo = vbo, .ebo = if (elements == null) null else ebo, .elements = elementsSize orelse 0, .vertices = vertices.len, }; } }; /// Color defined to be a 3 component vector /// X value is red, Y value is blue and Z value is green. pub const Color = zalgebra.Vec3; pub const Material = struct { texture: ?AssetHandle = null, ambient: Color = Color.zero(), diffuse: Color = Color.one(), specular: Color = Color.one(), shininess: f32 = 32.0, pub const default = Material{}; }; pub fn checkGlError() void { const err = c.glGetError(); if (err != c.GL_NO_ERROR) { std.log.scoped(.didot).err("GL error {}", .{err}); } } pub const ShaderProgram = struct { id: c.GLuint, vao: c.GLuint, vertex: c.GLuint, fragment: c.GLuint, allocator: Allocator = std.heap.page_allocator, uniformLocations: std.StringHashMap(c.GLint), /// Hashes of the current values of uniforms. Used to avoid expensive glUniform uniformHashes: std.StringHashMap(u32), pub fn createFromFile(allocator: Allocator, vertPath: []const u8, fragPath: []const u8) !ShaderProgram { const vertFile = try std.fs.cwd().openFile(vertPath, .{ .read = true }); const vert = try vertFile.reader().readAllAlloc(allocator, std.math.maxInt(u64)); const nullVert = try allocator.dupeZ(u8, vert); // null-terminated string allocator.free(vert); defer allocator.free(nullVert); vertFile.close(); const fragFile = try std.fs.cwd().openFile(fragPath, .{ .read = true }); const frag = try fragFile.reader().readAllAlloc(allocator, std.math.maxInt(u64)); const nullFrag = try allocator.dupeZ(u8, frag); allocator.free(frag); defer allocator.free(nullFrag); fragFile.close(); return try ShaderProgram.create(allocator, nullVert, nullFrag); } pub fn create(allocator: Allocator, vert: [:0]const u8, frag: [:0]const u8) !ShaderProgram { var mutex = windowContextLock(1); defer windowContextUnlock(1); checkGlError(); const vertexShader = c.glCreateShader(c.GL_VERTEX_SHADER); std.debug.print("debug vertex_shader={}\n", .{vertexShader}); // try checkError(vertexShader); var v = try std.fmt.allocPrintZ(allocator, "{s}", .{vert}); c.glShaderSource(vertexShader, 1, @ptrCast([*c]const [*c]const u8, &v), null); checkGlError(); c.glCompileShader(vertexShader); allocator.free(v); try checkError(vertexShader); const fragmentShader = c.glCreateShader(c.GL_FRAGMENT_SHADER); var f = try std.fmt.allocPrintZ(allocator, "#version 330 core\n#define MAX_POINT_LIGHTS 4\n{s}", .{frag}); c.glShaderSource(fragmentShader, 1, @ptrCast([*c]const [*c]const u8, &f), null); c.glCompileShader(fragmentShader); allocator.free(f); try checkError(fragmentShader); const shaderProgramId = c.glCreateProgram(); c.glAttachShader(shaderProgramId, vertexShader); c.glAttachShader(shaderProgramId, fragmentShader); c.glBindFragDataLocation(shaderProgramId, 0, "outColor"); c.glLinkProgram(shaderProgramId); c.glUseProgram(shaderProgramId); var vao: c.GLuint = 0; c.glGenVertexArrays(1, &vao); c.glBindVertexArray(vao); const stride = 5 * @sizeOf(f32); const posAttrib = c.glGetAttribLocation(shaderProgramId, "position"); c.glVertexAttribPointer(@bitCast(c.GLuint, posAttrib), 3, c.GL_FLOAT, c.GL_FALSE, stride, @intToPtr(*allowzero const anyopaque, 0)); c.glEnableVertexAttribArray(@bitCast(c.GLuint, posAttrib)); const texAttrib = c.glGetAttribLocation(shaderProgramId, "texcoord"); c.glVertexAttribPointer(@bitCast(c.GLuint, texAttrib), 2, c.GL_FLOAT, c.GL_FALSE, stride, @intToPtr(*allowzero const anyopaque, 3 * @sizeOf(f32))); c.glEnableVertexAttribArray(@bitCast(c.GLuint, texAttrib)); std.log.scoped(.didot).debug("Created shader", .{}); _ = mutex; return ShaderProgram{ .id = shaderProgramId, .vao = vao, .vertex = vertexShader, .fragment = fragmentShader, .uniformLocations = std.StringHashMap(c.GLint).init(std.heap.page_allocator), .uniformHashes = std.StringHashMap(u32).init(std.heap.page_allocator), .allocator = allocator, }; } pub fn bind(self: *const ShaderProgram) void { c.glUseProgram(self.id); } fn getUniformLocation(self: *ShaderProgram, name: [:0]const u8) c.GLint { if (self.uniformLocations.get(name)) |location| { return location; } else { const location = c.glGetUniformLocation(self.id, name); if (location == -1) { std.log.scoped(.didot).warn("Shader uniform not found: {s}", .{name}); } else { //std.log.scoped(.didot).debug("Uniform location of {s} is {}", .{name, location}); } self.uniformLocations.put(name, location) catch {}; // as this is a cache, not being able to put the entry can be and should be discarded return location; } } fn isUniformSame(self: *ShaderProgram, name: [:0]const u8, bytes: []const u8) bool { const hash = std.hash.Crc32.hash(bytes); defer { self.uniformHashes.put(name, hash) catch {}; // again, as this is an optimization, it is not fatal if we can't put it in the map } if (self.uniformHashes.get(name)) |expected| { return expected == hash; } else { return false; } } /// Set an OpenGL uniform to the following 4x4 matrix. pub fn setUniformMat4(self: *ShaderProgram, name: [:0]const u8, val: zalgebra.Mat4) void { if (self.isUniformSame(name, &std.mem.toBytes(val))) return; var uniform = self.getUniformLocation(name); c.glUniformMatrix4fv(uniform, 1, c.GL_FALSE, val.getData()); } /// Set an OpenGL uniform to the following boolean. pub fn setUniformBool(self: *ShaderProgram, name: [:0]const u8, val: bool) void { if (self.isUniformSame(name, &std.mem.toBytes(val))) return; var uniform = self.getUniformLocation(name); var v: c.GLint = if (val) 1 else 0; c.glUniform1i(uniform, v); } /// Set an OpenGL uniform to the following float. pub fn setUniformFloat(self: *ShaderProgram, name: [:0]const u8, val: f32) void { if (self.isUniformSame(name, &std.mem.toBytes(val))) return; var uniform = self.getUniformLocation(name); c.glUniform1f(uniform, val); } /// Set an OpenGL uniform to the following 3D float vector. pub fn setUniformVec3(self: *ShaderProgram, name: [:0]const u8, val: zalgebra.Vec3) void { if (self.isUniformSame(name, &std.mem.toBytes(val))) return; var uniform = self.getUniformLocation(name); c.glUniform3f(uniform, val.x, val.y, val.z); } fn checkError(shader: c.GLuint) ShaderError!void { var status: c.GLint = undefined; const err = c.glGetError(); if (err != c.GL_NO_ERROR) { std.log.scoped(.didot).err("GL error while initializing shaders: {}", .{err}); } c.glGetShaderiv(shader, c.GL_COMPILE_STATUS, &status); if (status != c.GL_TRUE) { var buf: [2048]u8 = undefined; var totalLen: c.GLsizei = -1; c.glGetShaderInfoLog(shader, 2048, &totalLen, buf[0..]); if (totalLen == -1) { // the length of the infolog seems to not be set // when a GL context isn't set (so when the window isn't created) return ShaderError.InvalidContextError; } var totalSize: usize = @intCast(usize, totalLen); std.log.scoped(.didot).err("shader compilation errror:\n{s}", .{buf[0..totalSize]}); return ShaderError.ShaderCompileError; } else { std.log.scoped(.didot).debug("Shader compiled OK\n", .{}); } } pub fn deinit(self: *ShaderProgram) void { self.uniformLocations.deinit(); self.uniformHashes.deinit(); } }; const image = @import("didot-image"); const Image = image.Image; pub const CubemapSettings = struct { right: AssetHandle, left: AssetHandle, top: AssetHandle, bottom: AssetHandle, front: AssetHandle, back: AssetHandle }; pub const Texture = struct { id: c.GLuint, width: usize = 0, height: usize = 0, tiling: zalgebra.Vec2 = zalgebra.Vec2.new(1, 1), pub fn createEmptyCubemap() Texture { var id: c.GLuint = undefined; c.glGenTextures(1, &id); c.glBindTexture(c.GL_TEXTURE_CUBE_MAP, id); c.glPixelStorei(c.GL_UNPACK_ALIGNMENT, 1); c.glTexParameteri(c.GL_TEXTURE_CUBE_MAP, c.GL_TEXTURE_MIN_FILTER, c.GL_LINEAR); c.glTexParameteri(c.GL_TEXTURE_CUBE_MAP, c.GL_TEXTURE_MAG_FILTER, c.GL_LINEAR); return Texture { .id = id }; } pub fn createEmpty2D() Texture { var id: c.GLuint = undefined; c.glGenTextures(1, &id); c.glBindTexture(c.GL_TEXTURE_2D, id); c.glPixelStorei(c.GL_UNPACK_ALIGNMENT, 1); c.glTexParameteri(c.GL_TEXTURE_2D, c.GL_TEXTURE_MIN_FILTER, c.GL_LINEAR); c.glTexParameteri(c.GL_TEXTURE_2D, c.GL_TEXTURE_MAG_FILTER, c.GL_LINEAR); c.glTexParameteri(c.GL_TEXTURE_2D, c.GL_TEXTURE_WRAP_S, c.GL_CLAMP_TO_EDGE); c.glTexParameteri(c.GL_TEXTURE_2D, c.GL_TEXTURE_WRAP_T, c.GL_CLAMP_TO_EDGE); return Texture { .id = id }; } pub fn bind(self: *const Texture) void { c.glBindTexture(c.GL_TEXTURE_2D, self.id); } pub fn deinit(self: *const Texture) void { c.glDeleteTextures(1, &self.id); } }; // Image asset loader pub const TextureAsset = struct { pub fn init2D(allocator: Allocator, format: []const u8) !Asset { var data = try allocator.create(TextureAssetLoaderData); data.tiling = zalgebra.Vec2.new(0, 0); data.cubemap = null; data.format = format; return Asset { .loader = textureAssetLoader, .loaderData = @ptrToInt(data), .objectType = .Texture, .allocator = allocator }; } /// Memory is caller owned pub fn init(allocator: Allocator, original: TextureAssetLoaderData) !Asset { var data = try allocator.create(TextureAssetLoaderData); data.* = original; return Asset { .loader = textureAssetLoader, .loaderData = @ptrToInt(data), .objectType = .Texture, .allocator = allocator }; } /// Memory is caller owned pub fn initCubemap(allocator: Allocator, cb: CubemapSettings) !Asset { var data = try allocator.create(TextureAssetLoaderData); data.cubemap = cb; return Asset { .loader = textureAssetLoader, .loaderData = @ptrToInt(data), .objectType = .Texture, .allocator = allocator }; } }; pub const TextureAssetLoaderData = struct { cubemap: ?CubemapSettings = null, format: []const u8, tiling: zalgebra.Vec2 = zalgebra.Vec2.new(1, 1) }; pub const TextureAssetLoaderError = error{InvalidFormat}; fn textureLoadImage(allocator: Allocator, stream: *AssetStream, format: []const u8) !Image { if (std.mem.eql(u8, format, "png")) { return try image.png.read(allocator, stream.reader()); } else if (std.mem.eql(u8, format, "bmp")) { return try image.bmp.read(allocator, stream.reader(), stream.seekableStream()); } return TextureAssetLoaderError.InvalidFormat; } fn getTextureFormat(format: image.ImageFormat) c.GLuint { if (std.meta.eql(format, image.ImageFormat.RGB24)) { return c.GL_RGB; } else if (std.meta.eql(format, image.ImageFormat.BGR24)) { return c.GL_BGR; } else if (std.meta.eql(format, image.ImageFormat.RGBA32)) { return c.GL_RGBA; } else { unreachable; // TODO convert the source image to RGB } } pub fn textureAssetLoader(allocator: Allocator, dataPtr: usize, stream: *AssetStream) !usize { var data = @intToPtr(*TextureAssetLoaderData, dataPtr); if (data.cubemap) |cb| { _ = windowContextLock(2); var texture = Texture.createEmptyCubemap(); windowContextUnlock(2); const targets = [_]c.GLuint { c.GL_TEXTURE_CUBE_MAP_POSITIVE_X, c.GL_TEXTURE_CUBE_MAP_NEGATIVE_X, c.GL_TEXTURE_CUBE_MAP_POSITIVE_Y, c.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, c.GL_TEXTURE_CUBE_MAP_POSITIVE_Z, c.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z }; const names = [_][]const u8 {"X+", "X-", "Y+", "Y-", "Z+", "Z-"}; var frames: [6]@Frame(AssetHandle.getPointer) = undefined; comptime var i = 0; inline for (@typeInfo(CubemapSettings).Struct.fields) |field| { const handle = @field(cb, field.name); frames[i] = async handle.getPointer(allocator); i += 1; } i = 0; inline for (@typeInfo(CubemapSettings).Struct.fields) |_| { const ptr = try await frames[i]; const tex = @intToPtr(*Texture, ptr); var tmp = try allocator.alloc(u8, tex.width * tex.height * 3); _ = windowContextLock(3); tex.bind(); c.glGetTexImage(c.GL_TEXTURE_2D, 0, c.GL_RGB, c.GL_UNSIGNED_BYTE, tmp.ptr); c.glTexImage2D(targets[i], 0, c.GL_SRGB, @intCast(c_int, tex.width), @intCast(c_int, tex.height), 0, c.GL_RGB, c.GL_UNSIGNED_BYTE, tmp.ptr); allocator.free(tmp); windowContextUnlock(3); std.log.scoped(.didot).debug("Loaded cubemap {s}", .{names[i]}); i += 1; } var t = try allocator.create(Texture); t.* = texture; return @ptrToInt(t); } else { var img = try textureLoadImage(allocator, stream, data.format); _ = windowContextLock(4); var texture = Texture.createEmpty2D(); defer windowContextUnlock(4); c.glTexImage2D(c.GL_TEXTURE_2D, 0, c.GL_SRGB, @intCast(c_int, img.width), @intCast(c_int, img.height), 0, getTextureFormat(img.format), c.GL_UNSIGNED_BYTE, &img.data[0]); texture.tiling = data.tiling; texture.width = img.width; texture.height = img.height; img.deinit(); std.log.scoped(.didot).debug("Loaded texture (format={}, size={}x{})", .{img.format, img.width, img.height}); var t = try allocator.create(Texture); t.* = texture; return @ptrToInt(t); } } const objects = @import("../didot-objects/main.zig"); // hacky hack til i found a way for graphics to depend on objects const Scene = objects.Scene; const GameObject = objects.GameObject; const Camera = objects.Camera; const AssetManager = objects.AssetManager; const Asset = objects.Asset; const AssetStream = objects.AssetStream; const AssetHandle = objects.AssetHandle; /// Set this function to replace normal pre-render behaviour (GL state, clear, etc.), it happens after viewport pub var preRender: ?fn() void = null; /// Set this function to replace normal viewport behaviour pub var viewport: ?fn() zalgebra.Vec4 = null; pub fn renderScene(scene: *Scene, window: Window) !void { const size = window.getFramebufferSize(); try renderSceneOffscreen(scene, if (viewport) |func| func() else zalgebra.Vec4.new(0, 0, size.x, size.y)); } //pub var renderMutex: std.Thread.Mutex = undefined; /// Internal method for rendering a game scene. /// This method is here as it uses graphics API-dependent code (it's the rendering part afterall) pub fn renderSceneOffscreen(scene: *Scene, vp: zalgebra.Vec4) !void { var mutex = windowContextLock(5); defer windowContextUnlock(5); // std.debug.print("glViewport {} {}", .{vp.x, vp.y}); c.glViewport(@floatToInt(c_int, @floor(vp.x)), @floatToInt(c_int, @floor(vp.y)), @floatToInt(c_int, @floor(vp.z)), @floatToInt(c_int, @floor(vp.w))); if (preRender) |func| { func(); } else { c.glClear(c.GL_COLOR_BUFFER_BIT | c.GL_DEPTH_BUFFER_BIT); c.glEnable(c.GL_DEPTH_TEST); c.glEnable(c.GL_FRAMEBUFFER_SRGB); //c.glEnable(c.GL_CULL_FACE); } var assets = &scene.assetManager; if (scene.camera) |cameraObject| { const camera = cameraObject.getComponent(Camera).?; const projMatrix = switch (camera.projection) { .Perspective => |p| zalgebra.Mat4.perspective(p.fov, vp.z / vp.w, p.near, p.far), .Orthographic => |p| zalgebra.Mat4.orthographic(p.left, p.right, p.bottom, p.top, p.near, p.far) }; // create the direction vector to be used with the view matrix. const transform = cameraObject.getComponent(objects.Transform).?; const euler = transform.rotation.extractRotation(); const yaw = zalgebra.toRadians(euler.x); const pitch = zalgebra.toRadians(euler.y); const direction = zalgebra.Vec3.new( std.math.cos(yaw) * std.math.cos(pitch), std.math.sin(pitch), std.math.sin(yaw) * std.math.cos(pitch) ).norm(); const viewMatrix = zalgebra.Mat4.lookAt(transform.position, transform.position.add(direction), zalgebra.Vec3.new(0.0, 1.0, 0.0)); //const viewMatrix = zalgebra.Mat4.from_translate(transform.position.scale(-1)) // .mult(transform.rotation.to_mat4()); //const viewMatrix = zalgebra.Mat4.from_translate(transform.position).mult(zalgebra.Mat4.identity()); if (camera.skybox) |*skybox| { skybox.shader.bind(); const view = zalgebra.Mat4.identity() .mult(zalgebra.Mat4.fromEulerAngle(viewMatrix.extractRotation())); skybox.shader.setUniformMat4("view", view); skybox.shader.setUniformMat4("projection", projMatrix); try renderSkybox(skybox, assets); } camera.shader.bind(); camera.shader.setUniformMat4("projMatrix", projMatrix); camera.shader.setUniformMat4("viewMatrix", viewMatrix); if (scene.pointLight) |light| { const lightData = light.getComponent(objects.PointLight).?; camera.shader.setUniformVec3("light.position", light.getComponent(objects.Transform).?.position); camera.shader.setUniformVec3("light.color", lightData.color); camera.shader.setUniformFloat("light.constant", lightData.constant); camera.shader.setUniformFloat("light.linear", lightData.linear); camera.shader.setUniformFloat("light.quadratic", lightData.quadratic); camera.shader.setUniformBool("useLight", true); } else { camera.shader.setUniformBool("useLight", false); } camera.shader.setUniformVec3("viewPos", transform.position); //std.debug.print("treelock\n", .{}); scene.treeLock.lock(); for (scene.objects.items) |gameObject| { try renderObject(gameObject, assets, camera, zalgebra.Mat4.identity()); } //std.debug.print("treeunlock\n", .{}); scene.treeLock.unlock(); } _ = mutex; } fn renderSkybox(skybox: *objects.Skybox, assets: *AssetManager) !void { var mesh = try skybox.mesh.get(Mesh, assets.allocator); c.glDepthMask(c.GL_FALSE); c.glBindVertexArray(mesh.vao); windowContextUnlock(6); const texture = try skybox.cubemap.get(Texture, assets.allocator); _ = windowContextLock(6); c.glBindTexture(c.GL_TEXTURE_CUBE_MAP, texture.id); if (mesh.ebo != null) { c.glDrawElements(c.GL_TRIANGLES, @intCast(c_int, mesh.elements), c.GL_UNSIGNED_INT, null); } else { c.glDrawArrays(c.GL_TRIANGLES, 0, @intCast(c_int, mesh.vertices)); } c.glDepthMask(c.GL_TRUE); } // TODO: remake parent matrix with the new system fn renderObject(gameObject: *GameObject, assets: *AssetManager, camera: *Camera, parentMatrix: zalgebra.Mat4) anyerror!void { if (gameObject.getComponent(objects.Transform)) |transform| { const matrix = zalgebra.Mat4.recompose(transform.position, transform.rotation, transform.scale); _ = parentMatrix; // TODO: take it in account if (gameObject.mesh) |handle| { windowContextUnlock(7); const mesh = try handle.get(Mesh, assets.allocator); _ = windowContextLock(7); c.glBindVertexArray(mesh.vao); const material = gameObject.material; if (material.texture) |asset| { windowContextUnlock(8); const texture = try asset.get(Texture, assets.allocator); _ = windowContextLock(8); texture.bind(); camera.shader.setUniformFloat("xTiling", if (texture.tiling.x == 0) 1 else transform.scale.x / texture.tiling.x); camera.shader.setUniformFloat("yTiling", if (texture.tiling.y == 0) 1 else transform.scale.z / texture.tiling.y); camera.shader.setUniformBool("useTex", true); } else { camera.shader.setUniformBool("useTex", false); } camera.shader.setUniformVec3("material.ambient", material.ambient); camera.shader.setUniformVec3("material.diffuse", material.diffuse); camera.shader.setUniformVec3("material.specular", material.specular); var s: f32 = std.math.clamp(material.shininess, 1.0, 128.0); camera.shader.setUniformFloat("material.shininess", s); camera.shader.setUniformMat4("modelMatrix", matrix); if (mesh.ebo != null) { c.glDrawElements(c.GL_TRIANGLES, @intCast(c_int, mesh.elements), c.GL_UNSIGNED_INT, null); } else { c.glDrawArrays(c.GL_TRIANGLES, 0, @intCast(c_int, mesh.vertices)); } } } } comptime { std.testing.refAllDecls(@This()); std.testing.refAllDecls(ShaderProgram); std.testing.refAllDecls(Texture); }
didot-opengl/graphics.zig
//-------------------------------------------------------------------------------- // Section: Types (31) //-------------------------------------------------------------------------------- pub const PRJ_NAMESPACE_VIRTUALIZATION_CONTEXT = isize; pub const PRJ_DIR_ENTRY_BUFFER_HANDLE = isize; pub const PRJ_NOTIFY_TYPES = enum(u32) { NONE = 0, SUPPRESS_NOTIFICATIONS = 1, FILE_OPENED = 2, NEW_FILE_CREATED = 4, FILE_OVERWRITTEN = 8, PRE_DELETE = 16, PRE_RENAME = 32, PRE_SET_HARDLINK = 64, FILE_RENAMED = 128, HARDLINK_CREATED = 256, FILE_HANDLE_CLOSED_NO_MODIFICATION = 512, FILE_HANDLE_CLOSED_FILE_MODIFIED = 1024, FILE_HANDLE_CLOSED_FILE_DELETED = 2048, FILE_PRE_CONVERT_TO_FULL = 4096, USE_EXISTING_MASK = 4294967295, _, pub fn initFlags(o: struct { NONE: u1 = 0, SUPPRESS_NOTIFICATIONS: u1 = 0, FILE_OPENED: u1 = 0, NEW_FILE_CREATED: u1 = 0, FILE_OVERWRITTEN: u1 = 0, PRE_DELETE: u1 = 0, PRE_RENAME: u1 = 0, PRE_SET_HARDLINK: u1 = 0, FILE_RENAMED: u1 = 0, HARDLINK_CREATED: u1 = 0, FILE_HANDLE_CLOSED_NO_MODIFICATION: u1 = 0, FILE_HANDLE_CLOSED_FILE_MODIFIED: u1 = 0, FILE_HANDLE_CLOSED_FILE_DELETED: u1 = 0, FILE_PRE_CONVERT_TO_FULL: u1 = 0, USE_EXISTING_MASK: u1 = 0, }) PRJ_NOTIFY_TYPES { return @intToEnum(PRJ_NOTIFY_TYPES, (if (o.NONE == 1) @enumToInt(PRJ_NOTIFY_TYPES.NONE) else 0) | (if (o.SUPPRESS_NOTIFICATIONS == 1) @enumToInt(PRJ_NOTIFY_TYPES.SUPPRESS_NOTIFICATIONS) else 0) | (if (o.FILE_OPENED == 1) @enumToInt(PRJ_NOTIFY_TYPES.FILE_OPENED) else 0) | (if (o.NEW_FILE_CREATED == 1) @enumToInt(PRJ_NOTIFY_TYPES.NEW_FILE_CREATED) else 0) | (if (o.FILE_OVERWRITTEN == 1) @enumToInt(PRJ_NOTIFY_TYPES.FILE_OVERWRITTEN) else 0) | (if (o.PRE_DELETE == 1) @enumToInt(PRJ_NOTIFY_TYPES.PRE_DELETE) else 0) | (if (o.PRE_RENAME == 1) @enumToInt(PRJ_NOTIFY_TYPES.PRE_RENAME) else 0) | (if (o.PRE_SET_HARDLINK == 1) @enumToInt(PRJ_NOTIFY_TYPES.PRE_SET_HARDLINK) else 0) | (if (o.FILE_RENAMED == 1) @enumToInt(PRJ_NOTIFY_TYPES.FILE_RENAMED) else 0) | (if (o.HARDLINK_CREATED == 1) @enumToInt(PRJ_NOTIFY_TYPES.HARDLINK_CREATED) else 0) | (if (o.FILE_HANDLE_CLOSED_NO_MODIFICATION == 1) @enumToInt(PRJ_NOTIFY_TYPES.FILE_HANDLE_CLOSED_NO_MODIFICATION) else 0) | (if (o.FILE_HANDLE_CLOSED_FILE_MODIFIED == 1) @enumToInt(PRJ_NOTIFY_TYPES.FILE_HANDLE_CLOSED_FILE_MODIFIED) else 0) | (if (o.FILE_HANDLE_CLOSED_FILE_DELETED == 1) @enumToInt(PRJ_NOTIFY_TYPES.FILE_HANDLE_CLOSED_FILE_DELETED) else 0) | (if (o.FILE_PRE_CONVERT_TO_FULL == 1) @enumToInt(PRJ_NOTIFY_TYPES.FILE_PRE_CONVERT_TO_FULL) else 0) | (if (o.USE_EXISTING_MASK == 1) @enumToInt(PRJ_NOTIFY_TYPES.USE_EXISTING_MASK) else 0) ); } }; pub const PRJ_NOTIFY_NONE = PRJ_NOTIFY_TYPES.NONE; pub const PRJ_NOTIFY_SUPPRESS_NOTIFICATIONS = PRJ_NOTIFY_TYPES.SUPPRESS_NOTIFICATIONS; pub const PRJ_NOTIFY_FILE_OPENED = PRJ_NOTIFY_TYPES.FILE_OPENED; pub const PRJ_NOTIFY_NEW_FILE_CREATED = PRJ_NOTIFY_TYPES.NEW_FILE_CREATED; pub const PRJ_NOTIFY_FILE_OVERWRITTEN = PRJ_NOTIFY_TYPES.FILE_OVERWRITTEN; pub const PRJ_NOTIFY_PRE_DELETE = PRJ_NOTIFY_TYPES.PRE_DELETE; pub const PRJ_NOTIFY_PRE_RENAME = PRJ_NOTIFY_TYPES.PRE_RENAME; pub const PRJ_NOTIFY_PRE_SET_HARDLINK = PRJ_NOTIFY_TYPES.PRE_SET_HARDLINK; pub const PRJ_NOTIFY_FILE_RENAMED = PRJ_NOTIFY_TYPES.FILE_RENAMED; pub const PRJ_NOTIFY_HARDLINK_CREATED = PRJ_NOTIFY_TYPES.HARDLINK_CREATED; pub const PRJ_NOTIFY_FILE_HANDLE_CLOSED_NO_MODIFICATION = PRJ_NOTIFY_TYPES.FILE_HANDLE_CLOSED_NO_MODIFICATION; pub const PRJ_NOTIFY_FILE_HANDLE_CLOSED_FILE_MODIFIED = PRJ_NOTIFY_TYPES.FILE_HANDLE_CLOSED_FILE_MODIFIED; pub const PRJ_NOTIFY_FILE_HANDLE_CLOSED_FILE_DELETED = PRJ_NOTIFY_TYPES.FILE_HANDLE_CLOSED_FILE_DELETED; pub const PRJ_NOTIFY_FILE_PRE_CONVERT_TO_FULL = PRJ_NOTIFY_TYPES.FILE_PRE_CONVERT_TO_FULL; pub const PRJ_NOTIFY_USE_EXISTING_MASK = PRJ_NOTIFY_TYPES.USE_EXISTING_MASK; pub const PRJ_NOTIFICATION = enum(i32) { FILE_OPENED = 2, NEW_FILE_CREATED = 4, FILE_OVERWRITTEN = 8, PRE_DELETE = 16, PRE_RENAME = 32, PRE_SET_HARDLINK = 64, FILE_RENAMED = 128, HARDLINK_CREATED = 256, FILE_HANDLE_CLOSED_NO_MODIFICATION = 512, FILE_HANDLE_CLOSED_FILE_MODIFIED = 1024, FILE_HANDLE_CLOSED_FILE_DELETED = 2048, FILE_PRE_CONVERT_TO_FULL = 4096, }; pub const PRJ_NOTIFICATION_FILE_OPENED = PRJ_NOTIFICATION.FILE_OPENED; pub const PRJ_NOTIFICATION_NEW_FILE_CREATED = PRJ_NOTIFICATION.NEW_FILE_CREATED; pub const PRJ_NOTIFICATION_FILE_OVERWRITTEN = PRJ_NOTIFICATION.FILE_OVERWRITTEN; pub const PRJ_NOTIFICATION_PRE_DELETE = PRJ_NOTIFICATION.PRE_DELETE; pub const PRJ_NOTIFICATION_PRE_RENAME = PRJ_NOTIFICATION.PRE_RENAME; pub const PRJ_NOTIFICATION_PRE_SET_HARDLINK = PRJ_NOTIFICATION.PRE_SET_HARDLINK; pub const PRJ_NOTIFICATION_FILE_RENAMED = PRJ_NOTIFICATION.FILE_RENAMED; pub const PRJ_NOTIFICATION_HARDLINK_CREATED = PRJ_NOTIFICATION.HARDLINK_CREATED; pub const PRJ_NOTIFICATION_FILE_HANDLE_CLOSED_NO_MODIFICATION = PRJ_NOTIFICATION.FILE_HANDLE_CLOSED_NO_MODIFICATION; pub const PRJ_NOTIFICATION_FILE_HANDLE_CLOSED_FILE_MODIFIED = PRJ_NOTIFICATION.FILE_HANDLE_CLOSED_FILE_MODIFIED; pub const PRJ_NOTIFICATION_FILE_HANDLE_CLOSED_FILE_DELETED = PRJ_NOTIFICATION.FILE_HANDLE_CLOSED_FILE_DELETED; pub const PRJ_NOTIFICATION_FILE_PRE_CONVERT_TO_FULL = PRJ_NOTIFICATION.FILE_PRE_CONVERT_TO_FULL; pub const PRJ_EXT_INFO_TYPE = enum(i32) { K = 1, }; pub const PRJ_EXT_INFO_TYPE_SYMLINK = PRJ_EXT_INFO_TYPE.K; pub const PRJ_EXTENDED_INFO = extern struct { InfoType: PRJ_EXT_INFO_TYPE, NextInfoOffset: u32, Anonymous: extern union { Symlink: extern struct { TargetName: ?[*:0]const u16, }, }, }; pub const PRJ_NOTIFICATION_MAPPING = extern struct { NotificationBitMask: PRJ_NOTIFY_TYPES, NotificationRoot: ?[*:0]const u16, }; pub const PRJ_STARTVIRTUALIZING_FLAGS = enum(u32) { NONE = 0, USE_NEGATIVE_PATH_CACHE = 1, _, pub fn initFlags(o: struct { NONE: u1 = 0, USE_NEGATIVE_PATH_CACHE: u1 = 0, }) PRJ_STARTVIRTUALIZING_FLAGS { return @intToEnum(PRJ_STARTVIRTUALIZING_FLAGS, (if (o.NONE == 1) @enumToInt(PRJ_STARTVIRTUALIZING_FLAGS.NONE) else 0) | (if (o.USE_NEGATIVE_PATH_CACHE == 1) @enumToInt(PRJ_STARTVIRTUALIZING_FLAGS.USE_NEGATIVE_PATH_CACHE) else 0) ); } }; pub const PRJ_FLAG_NONE = PRJ_STARTVIRTUALIZING_FLAGS.NONE; pub const PRJ_FLAG_USE_NEGATIVE_PATH_CACHE = PRJ_STARTVIRTUALIZING_FLAGS.USE_NEGATIVE_PATH_CACHE; pub const PRJ_STARTVIRTUALIZING_OPTIONS = extern struct { Flags: PRJ_STARTVIRTUALIZING_FLAGS, PoolThreadCount: u32, ConcurrentThreadCount: u32, NotificationMappings: ?*PRJ_NOTIFICATION_MAPPING, NotificationMappingsCount: u32, }; pub const PRJ_VIRTUALIZATION_INSTANCE_INFO = extern struct { InstanceID: Guid, WriteAlignment: u32, }; pub const PRJ_PLACEHOLDER_ID = enum(i32) { H = 128, }; pub const PRJ_PLACEHOLDER_ID_LENGTH = PRJ_PLACEHOLDER_ID.H; pub const PRJ_PLACEHOLDER_VERSION_INFO = extern struct { ProviderID: [128]u8, ContentID: [128]u8, }; pub const PRJ_FILE_BASIC_INFO = extern struct { IsDirectory: BOOLEAN, FileSize: i64, CreationTime: LARGE_INTEGER, LastAccessTime: LARGE_INTEGER, LastWriteTime: LARGE_INTEGER, ChangeTime: LARGE_INTEGER, FileAttributes: u32, }; pub const PRJ_PLACEHOLDER_INFO = extern struct { FileBasicInfo: PRJ_FILE_BASIC_INFO, EaInformation: extern struct { EaBufferSize: u32, OffsetToFirstEa: u32, }, SecurityInformation: extern struct { SecurityBufferSize: u32, OffsetToSecurityDescriptor: u32, }, StreamsInformation: extern struct { StreamsInfoBufferSize: u32, OffsetToFirstStreamInfo: u32, }, VersionInfo: PRJ_PLACEHOLDER_VERSION_INFO, VariableData: [1]u8, }; pub const PRJ_UPDATE_TYPES = enum(u32) { NONE = 0, ALLOW_DIRTY_METADATA = 1, ALLOW_DIRTY_DATA = 2, ALLOW_TOMBSTONE = 4, RESERVED1 = 8, RESERVED2 = 16, ALLOW_READ_ONLY = 32, MAX_VAL = 64, _, pub fn initFlags(o: struct { NONE: u1 = 0, ALLOW_DIRTY_METADATA: u1 = 0, ALLOW_DIRTY_DATA: u1 = 0, ALLOW_TOMBSTONE: u1 = 0, RESERVED1: u1 = 0, RESERVED2: u1 = 0, ALLOW_READ_ONLY: u1 = 0, MAX_VAL: u1 = 0, }) PRJ_UPDATE_TYPES { return @intToEnum(PRJ_UPDATE_TYPES, (if (o.NONE == 1) @enumToInt(PRJ_UPDATE_TYPES.NONE) else 0) | (if (o.ALLOW_DIRTY_METADATA == 1) @enumToInt(PRJ_UPDATE_TYPES.ALLOW_DIRTY_METADATA) else 0) | (if (o.ALLOW_DIRTY_DATA == 1) @enumToInt(PRJ_UPDATE_TYPES.ALLOW_DIRTY_DATA) else 0) | (if (o.ALLOW_TOMBSTONE == 1) @enumToInt(PRJ_UPDATE_TYPES.ALLOW_TOMBSTONE) else 0) | (if (o.RESERVED1 == 1) @enumToInt(PRJ_UPDATE_TYPES.RESERVED1) else 0) | (if (o.RESERVED2 == 1) @enumToInt(PRJ_UPDATE_TYPES.RESERVED2) else 0) | (if (o.ALLOW_READ_ONLY == 1) @enumToInt(PRJ_UPDATE_TYPES.ALLOW_READ_ONLY) else 0) | (if (o.MAX_VAL == 1) @enumToInt(PRJ_UPDATE_TYPES.MAX_VAL) else 0) ); } }; pub const PRJ_UPDATE_NONE = PRJ_UPDATE_TYPES.NONE; pub const PRJ_UPDATE_ALLOW_DIRTY_METADATA = PRJ_UPDATE_TYPES.ALLOW_DIRTY_METADATA; pub const PRJ_UPDATE_ALLOW_DIRTY_DATA = PRJ_UPDATE_TYPES.ALLOW_DIRTY_DATA; pub const PRJ_UPDATE_ALLOW_TOMBSTONE = PRJ_UPDATE_TYPES.ALLOW_TOMBSTONE; pub const PRJ_UPDATE_RESERVED1 = PRJ_UPDATE_TYPES.RESERVED1; pub const PRJ_UPDATE_RESERVED2 = PRJ_UPDATE_TYPES.RESERVED2; pub const PRJ_UPDATE_ALLOW_READ_ONLY = PRJ_UPDATE_TYPES.ALLOW_READ_ONLY; pub const PRJ_UPDATE_MAX_VAL = PRJ_UPDATE_TYPES.MAX_VAL; pub const PRJ_UPDATE_FAILURE_CAUSES = enum(u32) { NONE = 0, DIRTY_METADATA = 1, DIRTY_DATA = 2, TOMBSTONE = 4, READ_ONLY = 8, _, pub fn initFlags(o: struct { NONE: u1 = 0, DIRTY_METADATA: u1 = 0, DIRTY_DATA: u1 = 0, TOMBSTONE: u1 = 0, READ_ONLY: u1 = 0, }) PRJ_UPDATE_FAILURE_CAUSES { return @intToEnum(PRJ_UPDATE_FAILURE_CAUSES, (if (o.NONE == 1) @enumToInt(PRJ_UPDATE_FAILURE_CAUSES.NONE) else 0) | (if (o.DIRTY_METADATA == 1) @enumToInt(PRJ_UPDATE_FAILURE_CAUSES.DIRTY_METADATA) else 0) | (if (o.DIRTY_DATA == 1) @enumToInt(PRJ_UPDATE_FAILURE_CAUSES.DIRTY_DATA) else 0) | (if (o.TOMBSTONE == 1) @enumToInt(PRJ_UPDATE_FAILURE_CAUSES.TOMBSTONE) else 0) | (if (o.READ_ONLY == 1) @enumToInt(PRJ_UPDATE_FAILURE_CAUSES.READ_ONLY) else 0) ); } }; pub const PRJ_UPDATE_FAILURE_CAUSE_NONE = PRJ_UPDATE_FAILURE_CAUSES.NONE; pub const PRJ_UPDATE_FAILURE_CAUSE_DIRTY_METADATA = PRJ_UPDATE_FAILURE_CAUSES.DIRTY_METADATA; pub const PRJ_UPDATE_FAILURE_CAUSE_DIRTY_DATA = PRJ_UPDATE_FAILURE_CAUSES.DIRTY_DATA; pub const PRJ_UPDATE_FAILURE_CAUSE_TOMBSTONE = PRJ_UPDATE_FAILURE_CAUSES.TOMBSTONE; pub const PRJ_UPDATE_FAILURE_CAUSE_READ_ONLY = PRJ_UPDATE_FAILURE_CAUSES.READ_ONLY; pub const PRJ_FILE_STATE = enum(u32) { PLACEHOLDER = 1, HYDRATED_PLACEHOLDER = 2, DIRTY_PLACEHOLDER = 4, FULL = 8, TOMBSTONE = 16, _, pub fn initFlags(o: struct { PLACEHOLDER: u1 = 0, HYDRATED_PLACEHOLDER: u1 = 0, DIRTY_PLACEHOLDER: u1 = 0, FULL: u1 = 0, TOMBSTONE: u1 = 0, }) PRJ_FILE_STATE { return @intToEnum(PRJ_FILE_STATE, (if (o.PLACEHOLDER == 1) @enumToInt(PRJ_FILE_STATE.PLACEHOLDER) else 0) | (if (o.HYDRATED_PLACEHOLDER == 1) @enumToInt(PRJ_FILE_STATE.HYDRATED_PLACEHOLDER) else 0) | (if (o.DIRTY_PLACEHOLDER == 1) @enumToInt(PRJ_FILE_STATE.DIRTY_PLACEHOLDER) else 0) | (if (o.FULL == 1) @enumToInt(PRJ_FILE_STATE.FULL) else 0) | (if (o.TOMBSTONE == 1) @enumToInt(PRJ_FILE_STATE.TOMBSTONE) else 0) ); } }; pub const PRJ_FILE_STATE_PLACEHOLDER = PRJ_FILE_STATE.PLACEHOLDER; pub const PRJ_FILE_STATE_HYDRATED_PLACEHOLDER = PRJ_FILE_STATE.HYDRATED_PLACEHOLDER; pub const PRJ_FILE_STATE_DIRTY_PLACEHOLDER = PRJ_FILE_STATE.DIRTY_PLACEHOLDER; pub const PRJ_FILE_STATE_FULL = PRJ_FILE_STATE.FULL; pub const PRJ_FILE_STATE_TOMBSTONE = PRJ_FILE_STATE.TOMBSTONE; pub const PRJ_CALLBACK_DATA_FLAGS = enum(i32) { START_SCAN = 1, TURN_SINGLE_ENTRY = 2, }; pub const PRJ_CB_DATA_FLAG_ENUM_RESTART_SCAN = PRJ_CALLBACK_DATA_FLAGS.START_SCAN; pub const PRJ_CB_DATA_FLAG_ENUM_RETURN_SINGLE_ENTRY = PRJ_CALLBACK_DATA_FLAGS.TURN_SINGLE_ENTRY; pub const PRJ_CALLBACK_DATA = extern struct { Size: u32, Flags: PRJ_CALLBACK_DATA_FLAGS, NamespaceVirtualizationContext: PRJ_NAMESPACE_VIRTUALIZATION_CONTEXT, CommandId: i32, FileId: Guid, DataStreamId: Guid, FilePathName: ?[*:0]const u16, VersionInfo: ?*PRJ_PLACEHOLDER_VERSION_INFO, TriggeringProcessId: u32, TriggeringProcessImageFileName: ?[*:0]const u16, InstanceContext: ?*anyopaque, }; pub const PRJ_START_DIRECTORY_ENUMERATION_CB = fn( callbackData: ?*const PRJ_CALLBACK_DATA, enumerationId: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PRJ_GET_DIRECTORY_ENUMERATION_CB = fn( callbackData: ?*const PRJ_CALLBACK_DATA, enumerationId: ?*const Guid, searchExpression: ?[*:0]const u16, dirEntryBufferHandle: PRJ_DIR_ENTRY_BUFFER_HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PRJ_END_DIRECTORY_ENUMERATION_CB = fn( callbackData: ?*const PRJ_CALLBACK_DATA, enumerationId: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PRJ_GET_PLACEHOLDER_INFO_CB = fn( callbackData: ?*const PRJ_CALLBACK_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PRJ_GET_FILE_DATA_CB = fn( callbackData: ?*const PRJ_CALLBACK_DATA, byteOffset: u64, length: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PRJ_QUERY_FILE_NAME_CB = fn( callbackData: ?*const PRJ_CALLBACK_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PRJ_NOTIFICATION_PARAMETERS = extern union { PostCreate: extern struct { NotificationMask: PRJ_NOTIFY_TYPES, }, FileRenamed: extern struct { NotificationMask: PRJ_NOTIFY_TYPES, }, FileDeletedOnHandleClose: extern struct { IsFileModified: BOOLEAN, }, }; pub const PRJ_NOTIFICATION_CB = fn( callbackData: ?*const PRJ_CALLBACK_DATA, isDirectory: BOOLEAN, notification: PRJ_NOTIFICATION, destinationFileName: ?[*:0]const u16, operationParameters: ?*PRJ_NOTIFICATION_PARAMETERS, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PRJ_CANCEL_COMMAND_CB = fn( callbackData: ?*const PRJ_CALLBACK_DATA, ) callconv(@import("std").os.windows.WINAPI) void; pub const PRJ_CALLBACKS = extern struct { StartDirectoryEnumerationCallback: ?PRJ_START_DIRECTORY_ENUMERATION_CB, EndDirectoryEnumerationCallback: ?PRJ_END_DIRECTORY_ENUMERATION_CB, GetDirectoryEnumerationCallback: ?PRJ_GET_DIRECTORY_ENUMERATION_CB, GetPlaceholderInfoCallback: ?PRJ_GET_PLACEHOLDER_INFO_CB, GetFileDataCallback: ?PRJ_GET_FILE_DATA_CB, QueryFileNameCallback: ?PRJ_QUERY_FILE_NAME_CB, NotificationCallback: ?PRJ_NOTIFICATION_CB, CancelCommandCallback: ?PRJ_CANCEL_COMMAND_CB, }; pub const PRJ_COMPLETE_COMMAND_TYPE = enum(i32) { NOTIFICATION = 1, ENUMERATION = 2, }; pub const PRJ_COMPLETE_COMMAND_TYPE_NOTIFICATION = PRJ_COMPLETE_COMMAND_TYPE.NOTIFICATION; pub const PRJ_COMPLETE_COMMAND_TYPE_ENUMERATION = PRJ_COMPLETE_COMMAND_TYPE.ENUMERATION; pub const PRJ_COMPLETE_COMMAND_EXTENDED_PARAMETERS = extern struct { CommandType: PRJ_COMPLETE_COMMAND_TYPE, Anonymous: extern union { Notification: extern struct { NotificationMask: PRJ_NOTIFY_TYPES, }, Enumeration: extern struct { DirEntryBufferHandle: PRJ_DIR_ENTRY_BUFFER_HANDLE, }, }, }; //-------------------------------------------------------------------------------- // Section: Functions (19) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows10.0.17763' pub extern "PROJECTEDFSLIB" fn PrjStartVirtualizing( virtualizationRootPath: ?[*:0]const u16, callbacks: ?*const PRJ_CALLBACKS, instanceContext: ?*const anyopaque, options: ?*const PRJ_STARTVIRTUALIZING_OPTIONS, namespaceVirtualizationContext: ?*PRJ_NAMESPACE_VIRTUALIZATION_CONTEXT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.17763' pub extern "PROJECTEDFSLIB" fn PrjStopVirtualizing( namespaceVirtualizationContext: PRJ_NAMESPACE_VIRTUALIZATION_CONTEXT, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows10.0.17763' pub extern "PROJECTEDFSLIB" fn PrjClearNegativePathCache( namespaceVirtualizationContext: PRJ_NAMESPACE_VIRTUALIZATION_CONTEXT, totalEntryNumber: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.17763' pub extern "PROJECTEDFSLIB" fn PrjGetVirtualizationInstanceInfo( namespaceVirtualizationContext: PRJ_NAMESPACE_VIRTUALIZATION_CONTEXT, virtualizationInstanceInfo: ?*PRJ_VIRTUALIZATION_INSTANCE_INFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.17763' pub extern "PROJECTEDFSLIB" fn PrjMarkDirectoryAsPlaceholder( rootPathName: ?[*:0]const u16, targetPathName: ?[*:0]const u16, versionInfo: ?*const PRJ_PLACEHOLDER_VERSION_INFO, virtualizationInstanceID: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.17763' pub extern "PROJECTEDFSLIB" fn PrjWritePlaceholderInfo( namespaceVirtualizationContext: PRJ_NAMESPACE_VIRTUALIZATION_CONTEXT, destinationFileName: ?[*:0]const u16, // TODO: what to do with BytesParamIndex 3? placeholderInfo: ?*const PRJ_PLACEHOLDER_INFO, placeholderInfoSize: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.19041' pub extern "PROJECTEDFSLIB" fn PrjWritePlaceholderInfo2( namespaceVirtualizationContext: PRJ_NAMESPACE_VIRTUALIZATION_CONTEXT, destinationFileName: ?[*:0]const u16, // TODO: what to do with BytesParamIndex 3? placeholderInfo: ?*const PRJ_PLACEHOLDER_INFO, placeholderInfoSize: u32, ExtendedInfo: ?*const PRJ_EXTENDED_INFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.17763' // This function from dll 'PROJECTEDFSLIB' is being skipped because it has some sort of issue pub fn PrjUpdateFileIfNeeded() void { @panic("this function is not working"); } // TODO: this type is limited to platform 'windows10.0.17763' // This function from dll 'PROJECTEDFSLIB' is being skipped because it has some sort of issue pub fn PrjDeleteFile() void { @panic("this function is not working"); } // TODO: this type is limited to platform 'windows10.0.17763' pub extern "PROJECTEDFSLIB" fn PrjWriteFileData( namespaceVirtualizationContext: PRJ_NAMESPACE_VIRTUALIZATION_CONTEXT, dataStreamId: ?*const Guid, // TODO: what to do with BytesParamIndex 4? buffer: ?*anyopaque, byteOffset: u64, length: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.17763' pub extern "PROJECTEDFSLIB" fn PrjGetOnDiskFileState( destinationFileName: ?[*:0]const u16, fileState: ?*PRJ_FILE_STATE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.17763' pub extern "PROJECTEDFSLIB" fn PrjAllocateAlignedBuffer( namespaceVirtualizationContext: PRJ_NAMESPACE_VIRTUALIZATION_CONTEXT, size: usize, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; // TODO: this type is limited to platform 'windows10.0.17763' pub extern "PROJECTEDFSLIB" fn PrjFreeAlignedBuffer( buffer: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows10.0.17763' pub extern "PROJECTEDFSLIB" fn PrjCompleteCommand( namespaceVirtualizationContext: PRJ_NAMESPACE_VIRTUALIZATION_CONTEXT, commandId: i32, completionResult: HRESULT, extendedParameters: ?*PRJ_COMPLETE_COMMAND_EXTENDED_PARAMETERS, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.17763' pub extern "PROJECTEDFSLIB" fn PrjFillDirEntryBuffer( fileName: ?[*:0]const u16, fileBasicInfo: ?*PRJ_FILE_BASIC_INFO, dirEntryBufferHandle: PRJ_DIR_ENTRY_BUFFER_HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.19041' pub extern "PROJECTEDFSLIB" fn PrjFillDirEntryBuffer2( dirEntryBufferHandle: PRJ_DIR_ENTRY_BUFFER_HANDLE, fileName: ?[*:0]const u16, fileBasicInfo: ?*PRJ_FILE_BASIC_INFO, extendedInfo: ?*PRJ_EXTENDED_INFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.17763' pub extern "PROJECTEDFSLIB" fn PrjFileNameMatch( fileNameToCheck: ?[*:0]const u16, pattern: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) BOOLEAN; // TODO: this type is limited to platform 'windows10.0.17763' pub extern "PROJECTEDFSLIB" fn PrjFileNameCompare( fileName1: ?[*:0]const u16, fileName2: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows10.0.17763' pub extern "PROJECTEDFSLIB" fn PrjDoesNameContainWildCards( fileName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) BOOLEAN; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (0) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { }, .wide => struct { }, .unspecified => if (@import("builtin").is_test) struct { } else struct { }, }; //-------------------------------------------------------------------------------- // Section: Imports (5) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOLEAN = @import("../foundation.zig").BOOLEAN; const HRESULT = @import("../foundation.zig").HRESULT; const LARGE_INTEGER = @import("../foundation.zig").LARGE_INTEGER; const PWSTR = @import("../foundation.zig").PWSTR; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "PRJ_START_DIRECTORY_ENUMERATION_CB")) { _ = PRJ_START_DIRECTORY_ENUMERATION_CB; } if (@hasDecl(@This(), "PRJ_GET_DIRECTORY_ENUMERATION_CB")) { _ = PRJ_GET_DIRECTORY_ENUMERATION_CB; } if (@hasDecl(@This(), "PRJ_END_DIRECTORY_ENUMERATION_CB")) { _ = PRJ_END_DIRECTORY_ENUMERATION_CB; } if (@hasDecl(@This(), "PRJ_GET_PLACEHOLDER_INFO_CB")) { _ = PRJ_GET_PLACEHOLDER_INFO_CB; } if (@hasDecl(@This(), "PRJ_GET_FILE_DATA_CB")) { _ = PRJ_GET_FILE_DATA_CB; } if (@hasDecl(@This(), "PRJ_QUERY_FILE_NAME_CB")) { _ = PRJ_QUERY_FILE_NAME_CB; } if (@hasDecl(@This(), "PRJ_NOTIFICATION_CB")) { _ = PRJ_NOTIFICATION_CB; } if (@hasDecl(@This(), "PRJ_CANCEL_COMMAND_CB")) { _ = PRJ_CANCEL_COMMAND_CB; } @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/storage/projected_file_system.zig
pub const UI_ALL_COMMANDS = @as(u32, 0); pub const UI_COLLECTION_INVALIDINDEX = @as(u32, 4294967295); pub const LIBID_UIRibbon = Guid.initString("942f35c2-e83b-45ef-b085-ac295dd63d5b"); //-------------------------------------------------------------------------------- // Section: Types (33) //-------------------------------------------------------------------------------- const CLSID_UIRibbonFramework_Value = Guid.initString("926749fa-2615-4987-8845-c33e65f2b957"); pub const CLSID_UIRibbonFramework = &CLSID_UIRibbonFramework_Value; const CLSID_UIRibbonImageFromBitmapFactory_Value = Guid.initString("0f7434b6-59b6-4250-999e-d168d6ae4293"); pub const CLSID_UIRibbonImageFromBitmapFactory = &CLSID_UIRibbonImageFromBitmapFactory_Value; pub const UI_CONTEXTAVAILABILITY = enum(i32) { NOTAVAILABLE = 0, AVAILABLE = 1, ACTIVE = 2, }; pub const UI_CONTEXTAVAILABILITY_NOTAVAILABLE = UI_CONTEXTAVAILABILITY.NOTAVAILABLE; pub const UI_CONTEXTAVAILABILITY_AVAILABLE = UI_CONTEXTAVAILABILITY.AVAILABLE; pub const UI_CONTEXTAVAILABILITY_ACTIVE = UI_CONTEXTAVAILABILITY.ACTIVE; pub const UI_FONTPROPERTIES = enum(i32) { NOTAVAILABLE = 0, NOTSET = 1, SET = 2, }; pub const UI_FONTPROPERTIES_NOTAVAILABLE = UI_FONTPROPERTIES.NOTAVAILABLE; pub const UI_FONTPROPERTIES_NOTSET = UI_FONTPROPERTIES.NOTSET; pub const UI_FONTPROPERTIES_SET = UI_FONTPROPERTIES.SET; pub const UI_FONTVERTICALPOSITION = enum(i32) { NOTAVAILABLE = 0, NOTSET = 1, SUPERSCRIPT = 2, SUBSCRIPT = 3, }; pub const UI_FONTVERTICALPOSITION_NOTAVAILABLE = UI_FONTVERTICALPOSITION.NOTAVAILABLE; pub const UI_FONTVERTICALPOSITION_NOTSET = UI_FONTVERTICALPOSITION.NOTSET; pub const UI_FONTVERTICALPOSITION_SUPERSCRIPT = UI_FONTVERTICALPOSITION.SUPERSCRIPT; pub const UI_FONTVERTICALPOSITION_SUBSCRIPT = UI_FONTVERTICALPOSITION.SUBSCRIPT; pub const UI_FONTUNDERLINE = enum(i32) { NOTAVAILABLE = 0, NOTSET = 1, SET = 2, }; pub const UI_FONTUNDERLINE_NOTAVAILABLE = UI_FONTUNDERLINE.NOTAVAILABLE; pub const UI_FONTUNDERLINE_NOTSET = UI_FONTUNDERLINE.NOTSET; pub const UI_FONTUNDERLINE_SET = UI_FONTUNDERLINE.SET; pub const UI_FONTDELTASIZE = enum(i32) { GROW = 0, SHRINK = 1, }; pub const UI_FONTDELTASIZE_GROW = UI_FONTDELTASIZE.GROW; pub const UI_FONTDELTASIZE_SHRINK = UI_FONTDELTASIZE.SHRINK; pub const UI_CONTROLDOCK = enum(i32) { TOP = 1, BOTTOM = 3, }; pub const UI_CONTROLDOCK_TOP = UI_CONTROLDOCK.TOP; pub const UI_CONTROLDOCK_BOTTOM = UI_CONTROLDOCK.BOTTOM; pub const UI_SWATCHCOLORTYPE = enum(i32) { NOCOLOR = 0, AUTOMATIC = 1, RGB = 2, }; pub const UI_SWATCHCOLORTYPE_NOCOLOR = UI_SWATCHCOLORTYPE.NOCOLOR; pub const UI_SWATCHCOLORTYPE_AUTOMATIC = UI_SWATCHCOLORTYPE.AUTOMATIC; pub const UI_SWATCHCOLORTYPE_RGB = UI_SWATCHCOLORTYPE.RGB; pub const UI_SWATCHCOLORMODE = enum(i32) { NORMAL = 0, MONOCHROME = 1, }; pub const UI_SWATCHCOLORMODE_NORMAL = UI_SWATCHCOLORMODE.NORMAL; pub const UI_SWATCHCOLORMODE_MONOCHROME = UI_SWATCHCOLORMODE.MONOCHROME; pub const UI_EVENTTYPE = enum(i32) { ApplicationMenuOpened = 0, RibbonMinimized = 1, RibbonExpanded = 2, ApplicationModeSwitched = 3, TabActivated = 4, MenuOpened = 5, CommandExecuted = 6, TooltipShown = 7, }; pub const UI_EVENTTYPE_ApplicationMenuOpened = UI_EVENTTYPE.ApplicationMenuOpened; pub const UI_EVENTTYPE_RibbonMinimized = UI_EVENTTYPE.RibbonMinimized; pub const UI_EVENTTYPE_RibbonExpanded = UI_EVENTTYPE.RibbonExpanded; pub const UI_EVENTTYPE_ApplicationModeSwitched = UI_EVENTTYPE.ApplicationModeSwitched; pub const UI_EVENTTYPE_TabActivated = UI_EVENTTYPE.TabActivated; pub const UI_EVENTTYPE_MenuOpened = UI_EVENTTYPE.MenuOpened; pub const UI_EVENTTYPE_CommandExecuted = UI_EVENTTYPE.CommandExecuted; pub const UI_EVENTTYPE_TooltipShown = UI_EVENTTYPE.TooltipShown; pub const UI_EVENTLOCATION = enum(i32) { Ribbon = 0, QAT = 1, ApplicationMenu = 2, ContextPopup = 3, }; pub const UI_EVENTLOCATION_Ribbon = UI_EVENTLOCATION.Ribbon; pub const UI_EVENTLOCATION_QAT = UI_EVENTLOCATION.QAT; pub const UI_EVENTLOCATION_ApplicationMenu = UI_EVENTLOCATION.ApplicationMenu; pub const UI_EVENTLOCATION_ContextPopup = UI_EVENTLOCATION.ContextPopup; // TODO: this type is limited to platform 'windows6.1' const IID_IUISimplePropertySet_Value = Guid.initString("c205bb48-5b1c-4219-a106-15bd0a5f24e2"); pub const IID_IUISimplePropertySet = &IID_IUISimplePropertySet_Value; pub const IUISimplePropertySet = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetValue: fn( self: *const IUISimplePropertySet, key: ?*const PROPERTYKEY, value: ?*PROPVARIANT, ) 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 IUISimplePropertySet_GetValue(self: *const T, key: ?*const PROPERTYKEY, value: ?*PROPVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IUISimplePropertySet.VTable, self.vtable).GetValue(@ptrCast(*const IUISimplePropertySet, self), key, value); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IUIRibbon_Value = Guid.initString("803982ab-370a-4f7e-a9e7-8784036a6e26"); pub const IID_IUIRibbon = &IID_IUIRibbon_Value; pub const IUIRibbon = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetHeight: fn( self: *const IUIRibbon, cy: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, LoadSettingsFromStream: fn( self: *const IUIRibbon, pStream: ?*IStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SaveSettingsToStream: fn( self: *const IUIRibbon, pStream: ?*IStream, ) 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 IUIRibbon_GetHeight(self: *const T, cy: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IUIRibbon.VTable, self.vtable).GetHeight(@ptrCast(*const IUIRibbon, self), cy); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IUIRibbon_LoadSettingsFromStream(self: *const T, pStream: ?*IStream) callconv(.Inline) HRESULT { return @ptrCast(*const IUIRibbon.VTable, self.vtable).LoadSettingsFromStream(@ptrCast(*const IUIRibbon, self), pStream); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IUIRibbon_SaveSettingsToStream(self: *const T, pStream: ?*IStream) callconv(.Inline) HRESULT { return @ptrCast(*const IUIRibbon.VTable, self.vtable).SaveSettingsToStream(@ptrCast(*const IUIRibbon, self), pStream); } };} pub usingnamespace MethodMixin(@This()); }; pub const UI_INVALIDATIONS = enum(i32) { STATE = 1, VALUE = 2, PROPERTY = 4, ALLPROPERTIES = 8, }; pub const UI_INVALIDATIONS_STATE = UI_INVALIDATIONS.STATE; pub const UI_INVALIDATIONS_VALUE = UI_INVALIDATIONS.VALUE; pub const UI_INVALIDATIONS_PROPERTY = UI_INVALIDATIONS.PROPERTY; pub const UI_INVALIDATIONS_ALLPROPERTIES = UI_INVALIDATIONS.ALLPROPERTIES; // TODO: this type is limited to platform 'windows6.1' const IID_IUIFramework_Value = Guid.initString("f4f0385d-6872-43a8-ad09-4c339cb3f5c5"); pub const IID_IUIFramework = &IID_IUIFramework_Value; pub const IUIFramework = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const IUIFramework, frameWnd: ?HWND, application: ?*IUIApplication, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Destroy: fn( self: *const IUIFramework, ) callconv(@import("std").os.windows.WINAPI) HRESULT, LoadUI: fn( self: *const IUIFramework, instance: ?HINSTANCE, resourceName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetView: fn( self: *const IUIFramework, viewId: u32, riid: ?*const Guid, ppv: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetUICommandProperty: fn( self: *const IUIFramework, commandId: u32, key: ?*const PROPERTYKEY, value: ?*PROPVARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetUICommandProperty: fn( self: *const IUIFramework, commandId: u32, key: ?*const PROPERTYKEY, value: ?*const PROPVARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InvalidateUICommand: fn( self: *const IUIFramework, commandId: u32, flags: UI_INVALIDATIONS, key: ?*const PROPERTYKEY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FlushPendingInvalidations: fn( self: *const IUIFramework, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetModes: fn( self: *const IUIFramework, iModes: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IUIFramework_Initialize(self: *const T, frameWnd: ?HWND, application: ?*IUIApplication) callconv(.Inline) HRESULT { return @ptrCast(*const IUIFramework.VTable, self.vtable).Initialize(@ptrCast(*const IUIFramework, self), frameWnd, application); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IUIFramework_Destroy(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IUIFramework.VTable, self.vtable).Destroy(@ptrCast(*const IUIFramework, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IUIFramework_LoadUI(self: *const T, instance: ?HINSTANCE, resourceName: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IUIFramework.VTable, self.vtable).LoadUI(@ptrCast(*const IUIFramework, self), instance, resourceName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IUIFramework_GetView(self: *const T, viewId: u32, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IUIFramework.VTable, self.vtable).GetView(@ptrCast(*const IUIFramework, self), viewId, riid, ppv); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IUIFramework_GetUICommandProperty(self: *const T, commandId: u32, key: ?*const PROPERTYKEY, value: ?*PROPVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IUIFramework.VTable, self.vtable).GetUICommandProperty(@ptrCast(*const IUIFramework, self), commandId, key, value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IUIFramework_SetUICommandProperty(self: *const T, commandId: u32, key: ?*const PROPERTYKEY, value: ?*const PROPVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IUIFramework.VTable, self.vtable).SetUICommandProperty(@ptrCast(*const IUIFramework, self), commandId, key, value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IUIFramework_InvalidateUICommand(self: *const T, commandId: u32, flags: UI_INVALIDATIONS, key: ?*const PROPERTYKEY) callconv(.Inline) HRESULT { return @ptrCast(*const IUIFramework.VTable, self.vtable).InvalidateUICommand(@ptrCast(*const IUIFramework, self), commandId, flags, key); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IUIFramework_FlushPendingInvalidations(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IUIFramework.VTable, self.vtable).FlushPendingInvalidations(@ptrCast(*const IUIFramework, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IUIFramework_SetModes(self: *const T, iModes: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IUIFramework.VTable, self.vtable).SetModes(@ptrCast(*const IUIFramework, self), iModes); } };} pub usingnamespace MethodMixin(@This()); }; pub const UI_EVENTPARAMS_COMMAND = extern struct { CommandID: u32, CommandName: ?[*:0]const u16, ParentCommandID: u32, ParentCommandName: ?[*:0]const u16, SelectionIndex: u32, Location: UI_EVENTLOCATION, }; pub const UI_EVENTPARAMS = extern struct { EventType: UI_EVENTTYPE, Anonymous: extern union { Modes: i32, Params: UI_EVENTPARAMS_COMMAND, }, }; // TODO: this type is limited to platform 'windows8.0' const IID_IUIEventLogger_Value = Guid.initString("ec3e1034-dbf4-41a1-95d5-03e0f1026e05"); pub const IID_IUIEventLogger = &IID_IUIEventLogger_Value; pub const IUIEventLogger = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnUIEvent: fn( self: *const IUIEventLogger, pEventParams: ?*UI_EVENTPARAMS, ) callconv(@import("std").os.windows.WINAPI) void, }; 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 IUIEventLogger_OnUIEvent(self: *const T, pEventParams: ?*UI_EVENTPARAMS) callconv(.Inline) void { return @ptrCast(*const IUIEventLogger.VTable, self.vtable).OnUIEvent(@ptrCast(*const IUIEventLogger, self), pEventParams); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.0' const IID_IUIEventingManager_Value = Guid.initString("3be6ea7f-9a9b-4198-9368-9b0f923bd534"); pub const IID_IUIEventingManager = &IID_IUIEventingManager_Value; pub const IUIEventingManager = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetEventLogger: fn( self: *const IUIEventingManager, eventLogger: ?*IUIEventLogger, ) 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 IUIEventingManager_SetEventLogger(self: *const T, eventLogger: ?*IUIEventLogger) callconv(.Inline) HRESULT { return @ptrCast(*const IUIEventingManager.VTable, self.vtable).SetEventLogger(@ptrCast(*const IUIEventingManager, self), eventLogger); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IUIContextualUI_Value = Guid.initString("eea11f37-7c46-437c-8e55-b52122b29293"); pub const IID_IUIContextualUI = &IID_IUIContextualUI_Value; pub const IUIContextualUI = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, ShowAtLocation: fn( self: *const IUIContextualUI, x: i32, y: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IUIContextualUI_ShowAtLocation(self: *const T, x: i32, y: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IUIContextualUI.VTable, self.vtable).ShowAtLocation(@ptrCast(*const IUIContextualUI, self), x, y); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IUICollection_Value = Guid.initString("df4f45bf-6f9d-4dd7-9d68-d8f9cd18c4db"); pub const IID_IUICollection = &IID_IUICollection_Value; pub const IUICollection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCount: fn( self: *const IUICollection, count: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetItem: fn( self: *const IUICollection, index: u32, item: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Add: fn( self: *const IUICollection, item: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Insert: fn( self: *const IUICollection, index: u32, item: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveAt: fn( self: *const IUICollection, index: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Replace: fn( self: *const IUICollection, indexReplaced: u32, itemReplaceWith: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clear: fn( self: *const IUICollection, ) 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 IUICollection_GetCount(self: *const T, count: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IUICollection.VTable, self.vtable).GetCount(@ptrCast(*const IUICollection, self), count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IUICollection_GetItem(self: *const T, index: u32, item: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IUICollection.VTable, self.vtable).GetItem(@ptrCast(*const IUICollection, self), index, item); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IUICollection_Add(self: *const T, item: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IUICollection.VTable, self.vtable).Add(@ptrCast(*const IUICollection, self), item); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IUICollection_Insert(self: *const T, index: u32, item: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IUICollection.VTable, self.vtable).Insert(@ptrCast(*const IUICollection, self), index, item); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IUICollection_RemoveAt(self: *const T, index: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IUICollection.VTable, self.vtable).RemoveAt(@ptrCast(*const IUICollection, self), index); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IUICollection_Replace(self: *const T, indexReplaced: u32, itemReplaceWith: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IUICollection.VTable, self.vtable).Replace(@ptrCast(*const IUICollection, self), indexReplaced, itemReplaceWith); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IUICollection_Clear(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IUICollection.VTable, self.vtable).Clear(@ptrCast(*const IUICollection, self)); } };} pub usingnamespace MethodMixin(@This()); }; pub const UI_COLLECTIONCHANGE = enum(i32) { INSERT = 0, REMOVE = 1, REPLACE = 2, RESET = 3, }; pub const UI_COLLECTIONCHANGE_INSERT = UI_COLLECTIONCHANGE.INSERT; pub const UI_COLLECTIONCHANGE_REMOVE = UI_COLLECTIONCHANGE.REMOVE; pub const UI_COLLECTIONCHANGE_REPLACE = UI_COLLECTIONCHANGE.REPLACE; pub const UI_COLLECTIONCHANGE_RESET = UI_COLLECTIONCHANGE.RESET; // TODO: this type is limited to platform 'windows6.1' const IID_IUICollectionChangedEvent_Value = Guid.initString("6502ae91-a14d-44b5-bbd0-62aacc581d52"); pub const IID_IUICollectionChangedEvent = &IID_IUICollectionChangedEvent_Value; pub const IUICollectionChangedEvent = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnChanged: fn( self: *const IUICollectionChangedEvent, action: UI_COLLECTIONCHANGE, oldIndex: u32, oldItem: ?*IUnknown, newIndex: u32, newItem: ?*IUnknown, ) 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 IUICollectionChangedEvent_OnChanged(self: *const T, action: UI_COLLECTIONCHANGE, oldIndex: u32, oldItem: ?*IUnknown, newIndex: u32, newItem: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IUICollectionChangedEvent.VTable, self.vtable).OnChanged(@ptrCast(*const IUICollectionChangedEvent, self), action, oldIndex, oldItem, newIndex, newItem); } };} pub usingnamespace MethodMixin(@This()); }; pub const UI_EXECUTIONVERB = enum(i32) { EXECUTE = 0, PREVIEW = 1, CANCELPREVIEW = 2, }; pub const UI_EXECUTIONVERB_EXECUTE = UI_EXECUTIONVERB.EXECUTE; pub const UI_EXECUTIONVERB_PREVIEW = UI_EXECUTIONVERB.PREVIEW; pub const UI_EXECUTIONVERB_CANCELPREVIEW = UI_EXECUTIONVERB.CANCELPREVIEW; // TODO: this type is limited to platform 'windows6.1' const IID_IUICommandHandler_Value = Guid.initString("75ae0a2d-dc03-4c9f-8883-069660d0beb6"); pub const IID_IUICommandHandler = &IID_IUICommandHandler_Value; pub const IUICommandHandler = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Execute: fn( self: *const IUICommandHandler, commandId: u32, verb: UI_EXECUTIONVERB, key: ?*const PROPERTYKEY, currentValue: ?*const PROPVARIANT, commandExecutionProperties: ?*IUISimplePropertySet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpdateProperty: fn( self: *const IUICommandHandler, commandId: u32, key: ?*const PROPERTYKEY, currentValue: ?*const PROPVARIANT, newValue: ?*PROPVARIANT, ) 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 IUICommandHandler_Execute(self: *const T, commandId: u32, verb: UI_EXECUTIONVERB, key: ?*const PROPERTYKEY, currentValue: ?*const PROPVARIANT, commandExecutionProperties: ?*IUISimplePropertySet) callconv(.Inline) HRESULT { return @ptrCast(*const IUICommandHandler.VTable, self.vtable).Execute(@ptrCast(*const IUICommandHandler, self), commandId, verb, key, currentValue, commandExecutionProperties); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IUICommandHandler_UpdateProperty(self: *const T, commandId: u32, key: ?*const PROPERTYKEY, currentValue: ?*const PROPVARIANT, newValue: ?*PROPVARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IUICommandHandler.VTable, self.vtable).UpdateProperty(@ptrCast(*const IUICommandHandler, self), commandId, key, currentValue, newValue); } };} pub usingnamespace MethodMixin(@This()); }; pub const UI_COMMANDTYPE = enum(i32) { UNKNOWN = 0, GROUP = 1, ACTION = 2, ANCHOR = 3, CONTEXT = 4, COLLECTION = 5, COMMANDCOLLECTION = 6, DECIMAL = 7, BOOLEAN = 8, FONT = 9, RECENTITEMS = 10, COLORANCHOR = 11, COLORCOLLECTION = 12, }; pub const UI_COMMANDTYPE_UNKNOWN = UI_COMMANDTYPE.UNKNOWN; pub const UI_COMMANDTYPE_GROUP = UI_COMMANDTYPE.GROUP; pub const UI_COMMANDTYPE_ACTION = UI_COMMANDTYPE.ACTION; pub const UI_COMMANDTYPE_ANCHOR = UI_COMMANDTYPE.ANCHOR; pub const UI_COMMANDTYPE_CONTEXT = UI_COMMANDTYPE.CONTEXT; pub const UI_COMMANDTYPE_COLLECTION = UI_COMMANDTYPE.COLLECTION; pub const UI_COMMANDTYPE_COMMANDCOLLECTION = UI_COMMANDTYPE.COMMANDCOLLECTION; pub const UI_COMMANDTYPE_DECIMAL = UI_COMMANDTYPE.DECIMAL; pub const UI_COMMANDTYPE_BOOLEAN = UI_COMMANDTYPE.BOOLEAN; pub const UI_COMMANDTYPE_FONT = UI_COMMANDTYPE.FONT; pub const UI_COMMANDTYPE_RECENTITEMS = UI_COMMANDTYPE.RECENTITEMS; pub const UI_COMMANDTYPE_COLORANCHOR = UI_COMMANDTYPE.COLORANCHOR; pub const UI_COMMANDTYPE_COLORCOLLECTION = UI_COMMANDTYPE.COLORCOLLECTION; pub const UI_VIEWTYPE = enum(i32) { N = 1, }; pub const UI_VIEWTYPE_RIBBON = UI_VIEWTYPE.N; pub const UI_VIEWVERB = enum(i32) { CREATE = 0, DESTROY = 1, SIZE = 2, ERROR = 3, }; pub const UI_VIEWVERB_CREATE = UI_VIEWVERB.CREATE; pub const UI_VIEWVERB_DESTROY = UI_VIEWVERB.DESTROY; pub const UI_VIEWVERB_SIZE = UI_VIEWVERB.SIZE; pub const UI_VIEWVERB_ERROR = UI_VIEWVERB.ERROR; // TODO: this type is limited to platform 'windows6.1' const IID_IUIApplication_Value = Guid.initString("d428903c-729a-491d-910d-682a08ff2522"); pub const IID_IUIApplication = &IID_IUIApplication_Value; pub const IUIApplication = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnViewChanged: fn( self: *const IUIApplication, viewId: u32, typeID: UI_VIEWTYPE, view: ?*IUnknown, verb: UI_VIEWVERB, uReasonCode: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnCreateUICommand: fn( self: *const IUIApplication, commandId: u32, typeID: UI_COMMANDTYPE, commandHandler: ?*?*IUICommandHandler, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnDestroyUICommand: fn( self: *const IUIApplication, commandId: u32, typeID: UI_COMMANDTYPE, commandHandler: ?*IUICommandHandler, ) 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 IUIApplication_OnViewChanged(self: *const T, viewId: u32, typeID: UI_VIEWTYPE, view: ?*IUnknown, verb: UI_VIEWVERB, uReasonCode: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IUIApplication.VTable, self.vtable).OnViewChanged(@ptrCast(*const IUIApplication, self), viewId, typeID, view, verb, uReasonCode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IUIApplication_OnCreateUICommand(self: *const T, commandId: u32, typeID: UI_COMMANDTYPE, commandHandler: ?*?*IUICommandHandler) callconv(.Inline) HRESULT { return @ptrCast(*const IUIApplication.VTable, self.vtable).OnCreateUICommand(@ptrCast(*const IUIApplication, self), commandId, typeID, commandHandler); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IUIApplication_OnDestroyUICommand(self: *const T, commandId: u32, typeID: UI_COMMANDTYPE, commandHandler: ?*IUICommandHandler) callconv(.Inline) HRESULT { return @ptrCast(*const IUIApplication.VTable, self.vtable).OnDestroyUICommand(@ptrCast(*const IUIApplication, self), commandId, typeID, commandHandler); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IUIImage_Value = Guid.initString("23c8c838-4de6-436b-ab01-5554bb7c30dd"); pub const IID_IUIImage = &IID_IUIImage_Value; pub const IUIImage = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetBitmap: fn( self: *const IUIImage, bitmap: ?*?HBITMAP, ) 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 IUIImage_GetBitmap(self: *const T, bitmap: ?*?HBITMAP) callconv(.Inline) HRESULT { return @ptrCast(*const IUIImage.VTable, self.vtable).GetBitmap(@ptrCast(*const IUIImage, self), bitmap); } };} pub usingnamespace MethodMixin(@This()); }; pub const UI_OWNERSHIP = enum(i32) { TRANSFER = 0, COPY = 1, }; pub const UI_OWNERSHIP_TRANSFER = UI_OWNERSHIP.TRANSFER; pub const UI_OWNERSHIP_COPY = UI_OWNERSHIP.COPY; // TODO: this type is limited to platform 'windows6.1' const IID_IUIImageFromBitmap_Value = Guid.initString("18aba7f3-4c1c-4ba2-bf6c-f5c3326fa816"); pub const IID_IUIImageFromBitmap = &IID_IUIImageFromBitmap_Value; pub const IUIImageFromBitmap = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CreateImage: fn( self: *const IUIImageFromBitmap, bitmap: ?HBITMAP, options: UI_OWNERSHIP, image: ?*?*IUIImage, ) 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 IUIImageFromBitmap_CreateImage(self: *const T, bitmap: ?HBITMAP, options: UI_OWNERSHIP, image: ?*?*IUIImage) callconv(.Inline) HRESULT { return @ptrCast(*const IUIImageFromBitmap.VTable, self.vtable).CreateImage(@ptrCast(*const IUIImageFromBitmap, self), bitmap, options, image); } };} 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 (10) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const HBITMAP = @import("../graphics/gdi.zig").HBITMAP; const HINSTANCE = @import("../foundation.zig").HINSTANCE; const HRESULT = @import("../foundation.zig").HRESULT; const HWND = @import("../foundation.zig").HWND; const IStream = @import("../system/com.zig").IStream; const IUnknown = @import("../system/com.zig").IUnknown; const PROPERTYKEY = @import("../ui/shell/properties_system.zig").PROPERTYKEY; const PROPVARIANT = @import("../system/com/structured_storage.zig").PROPVARIANT; 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; } } }
win32/ui/ribbon.zig
const std = @import("std"); const testing = std.testing; pub const Encoder = struct { const Self = @This(); buffer: []const u8, index: ?usize, bit_off: u3, /// Init the encoder. pub fn init(buffer: []const u8) Encoder { return .{ .buffer = buffer, .index = 0, .bit_off = 0, }; } /// Calculate the Base32-encoded size of an array of bytes. pub fn calcSize(source_len: usize) usize { const source_len_bits = source_len * 8; return source_len_bits / 5 + (if (source_len_bits % 5 > 0) @as(usize, 1) else 0); } /// Encode some data as Base32. /// Note that `dest.len` must at least be as big as `Encoder.calcSize(source.len)`. pub fn encode(dest: []u8, source: []const u8) []const u8 { const out_len = calcSize(source.len); std.debug.assert(dest.len >= out_len); var e = init(source); for (dest[0..out_len]) |*b| b.* = e.next() orelse unreachable; return dest[0..out_len]; } /// Calculate the amount of bits can be read from `self.buffer[self.index]`, /// with a maximum of 5 and an offset of `self.bit_off`. fn frontBitsLen(self: *const Self) u3 { // bit_off frontBitsLen // 0 5 // 1 5 // 2 5 // 3 5 // 4 4 // 5 3 // 6 2 // 7 1 return if (self.bit_off <= 3) 5 else 7 - self.bit_off + 1; } /// Get the bits of `self.buffer[self.index]`, read with an offset of `self.bit_off`, /// aligned to the left of the 5-bit unsigned integer. /// Returns null if `self.index` is null. /// An illustration of its behaviour, with `self.buffer[self.index]` being 0b10010111: /// | `self.bit_off` | `frontBits` | /// |----------------|-------------| /// | 0 | 0b10010 | /// | 1 | 0b00101 | /// | 2 | 0b01011 | /// | 3 | 0b10111 | /// | 4 | 0b01110 | /// | 5 | 0b11100 | /// | 6 | 0b11000 | /// | 7 | 0b10000 | fn frontBits(self: *const Self) ?u5 { const index = self.index orelse return null; const bits = self.buffer[index]; if (self.bit_off >= 4) return @truncate(u5, bits << (self.bit_off - 3)); return @truncate(u5, bits >> (3 - self.bit_off)); } /// Get the bits of `self.buffer[self.index]` with the maximum amount specified by the `bits` parameter, /// aligned to the right of the 5-bit unsigned integer. /// Because a 5-bit integer is returned, not more than 5 bits can be read. `bits` must not be greater than 5. /// An illustration of its behaviour, with `self.buffer[self.index]` being 0b11101001: /// | `bits` | `backBits` | /// |--------|------------| /// | 0 | 0b00000 | /// | 1 | 0b00001 | /// | 2 | 0b00011 | /// | 3 | 0b00111 | /// | 4 | 0b01110 | /// | 5 | 0b11101 | fn backBits(self: *const Self, bits: u3) u5 { std.debug.assert(bits <= 5); if (bits == 0 or self.index == null) return 0; return @truncate(u5, self.buffer[self.index.?] >> (7 - bits + 1)); } /// Get the next 5-bit integer, read from `self.buffer`. fn nextU5(self: *Self) ?u5 { // `self.buffer` is read 5 bits at a time by `nextU5`. // Because of the elements of `self.buffer` being 8 bits each, we need to // read from 2 bytes from `self.buffer` to return a whole u5. // `front_bits` are the bits that come first, read from `self.buffer[self.index]`. // `back_bits` are the bits that come last, read from `self.buffer[self.index + 1]`. // `back_bits` is only used when we can't read 5 bits from `self.buffer[self.index]`. const front_bits = self.frontBits() orelse return null; const n_front_bits = self.frontBitsLen(); var back_bits: u5 = 0; if (self.bit_off >= 3) { // Next time we'll need to read from the next byte in `self.buffer`. // We may need to grab the back bits from that next byte for this call too (if it exist). self.bit_off -= 3; // same as self.bit_off + 5 - 8 const new_index = self.index.? + 1; if (self.buffer.len > new_index) { self.index = new_index; back_bits = self.backBits(5 - n_front_bits); } else { self.index = null; } } else { // We need to read from the current byte in the next call to `nextU5` too. self.bit_off += 5; } return front_bits | back_bits; } /// Get the corresponding ASCII character for 5 bits of the input. fn char(unencoded: u5) u8 { return unencoded + (if (unencoded < 26) @as(u8, 'A') else '2' - 26); } /// Get the next byte of the encoded buffer. pub fn next(self: *Self) ?u8 { const unencoded = self.nextU5() orelse return null; return char(unencoded); } }; pub const DecodeError = error{CorruptInput}; pub const Decoder = struct { const Self = @This(); buffer: []const u8, index: ?usize, buf: u8, buf_len: u4, /// Init the decoder. pub fn init(buffer: []const u8) Self { return .{ .buffer = buffer, .index = 0, .buf_len = 0, .buf = 0, }; } /// Calculate the size of a Base32-encoded array of bytes. pub fn calcSize(source_len: usize) usize { return safeMulDiv(source_len, 5, 8); } /// Decode a slice of Base32-encoded data. /// Note that `dest.len` must at least be as big as `Decoder.calcSize(source.len)`. pub fn decode(dest: []u8, source: []const u8) DecodeError![]const u8 { const out_len = calcSize(source.len); std.debug.assert(dest.len >= out_len); var d = init(source); for (dest[0..out_len]) |*b| b.* = (try d.next()) orelse unreachable; return dest[0..out_len]; } /// Get a character from the buffer. fn decodeChar(c: u8) DecodeError!u5 { if (c >= 'A' and c <= 'Z') { return @truncate(u5, c - @as(u8, 'A')); } else if (c >= '2' and c <= '9') { // '2' -> 26 return @truncate(u5, c - @as(u8, '2') + 26); } else { return error.CorruptInput; } } /// Get the next 5-bit decoded character, read from `self.buffer`. fn nextU5(self: *Self) DecodeError!?u5 { const index = self.index orelse return null; self.index = if (index + 1 < self.buffer.len) index + 1 else null; return try decodeChar(self.buffer[index]); } /// Get the next byte of the decoded buffer. pub fn next(self: *Self) DecodeError!?u8 { while (true) { // Read a character and decode it. const c = (try self.nextU5()) orelse break; // Check how many bits we can write to the buffer. const buf_remaining_len = 8 - self.buf_len; // Calculate how many bytes we will write to the buffer (the decoded character represents 5 bits). const buf_write_len = if (buf_remaining_len > 5) 5 else buf_remaining_len; // Calculate how many bits of the decoded remain when we've written part of it to the buffer. const c_remaining_len = 5 - buf_write_len; // Write (the first) part of the decoded character to the buffer. self.buf |= (@as(u8, c) << 3) >> @truncate(u3, self.buf_len); self.buf_len += buf_write_len; if (self.buf_len == 8) { // The buffer is full, we can return a byte. const ret = self.buf; self.buf_len = c_remaining_len; self.buf = 0; if (buf_write_len != 5) { // We didn't write the entire decoded character to the buffer. // Write the remaining part to the beginning of the buffer. self.buf = @as(u8, c) << @truncate(u3, buf_write_len + 3); } return ret; } } // We aren't able to read any characters anymore. // If the buffer doesn't contain any (actual) data we can stop decoding. // Otherwise, we can return what remains in the buffer, and stop decoding // after having done that. if (self.buf == 0 and self.buf_len < 5) return null; const ret = self.buf; self.buf_len = 0; self.buf = 0; return ret; } }; // Taken from std.time. // Calculate (a * b) / c without risk of overflowing too early because of the // multiplication. fn safeMulDiv(a: u64, b: u64, c: u64) u64 { const q = a / c; const r = a % c; // (a * b) / c == (a / c) * b + ((a % c) * b) / c return (q * b) + (r * b) / c; } test { const encoded = "ORUGS4ZANFZSAYJAORSXG5A"; const decoded = "this is a test"; var decode_buf: [Decoder.calcSize(encoded.len)]u8 = undefined; const decode_res = try Decoder.decode(&decode_buf, encoded); try testing.expectEqualStrings(decoded, decode_res); var encode_buf: [Encoder.calcSize(decoded.len)]u8 = undefined; const encode_res = Encoder.encode(&encode_buf, decoded); try testing.expectEqualStrings(encoded, encode_res); } test { const encoded = "SNAH7EH5X4P5R2M2RGF3LVAL6NRFIXLN2E67O6FNRUQ4JCQBPL64GEBPLY"; const decoded = &[_]u8{ 0x93, 0x40, 0x7f, 0x90, 0xfd, 0xbf, 0x1f, 0xd8, 0xe9, 0x9a, 0x89, 0x8b, 0xb5, 0xd4, 0x0b, 0xf3, 0x62, 0x54, 0x5d, 0x6d, 0xd1, 0x3d, 0xf7, 0x78, 0xad, 0x8d, 0x21, 0xc4, 0x8a, 0x01, 0x7a, 0xfd, 0xc3, 0x10, 0x2f, 0x5e }; var decode_buf: [Decoder.calcSize(encoded.len)]u8 = undefined; const decode_res = try Decoder.decode(&decode_buf, encoded); try testing.expectEqualSlices(u8, decoded, decode_res); var encode_buf: [Encoder.calcSize(decoded.len)]u8 = undefined; const encode_res = Encoder.encode(&encode_buf, decoded); try testing.expectEqualSlices(u8, encoded, encode_res); }
src/base32.zig
const std = @import("std"); const mem = std.mem; const Compare = mem.Compare; const Allocator = mem.Allocator; const ArrayList = std.ArrayList; fn nextPowerOf2(x: usize) usize { if (x == 0) return 1; var result = x -% 1; result = switch (@sizeOf(usize)) { 8 => result | (result >> 32), 4 => result | (result >> 16), 2 => result | (result >> 8), 1 => result | (result >> 4), else => 0, }; result |= (result >> 4); result |= (result >> 2); result |= (result >> 1); return result +% (1 + @boolToInt(x <= 0)); } pub fn Trie(comptime T: type) type { return struct { const Self = @This(); const Node = struct { allocator: *Allocator, prefix: ?[]const u8, children: []*Node, data: ?T, fn new(allocator: *Allocator, prefix: ?[]const u8) Node { return Node { .allocator = allocator, .children = undefined, .prefix = prefix, .data = null, }; } fn add(self: *Node, node: *Node) !void { const new_size = self.children.len + 1; self.children = try self.allocator.realloc(*Node, self.children, new_size); self.children[new_size - 1] = node; } }; nodes: ArrayList(Node), root: Node, pub fn init(allocator: *Allocator) Self { return Self { .nodes = ArrayList(Node).init(allocator), .root = Node.new(allocator, null), }; } pub fn insert(self: *Self, key: []const u8, value: T) !void { var nodes = &self.root.children; // Compare.GreaterThan -- create new node, append node // Compare.Equal -- do nothing? (update value) // Compare.LessThan -- split node } pub fn get(self: Self, key: []const u8) ?T { return null; } }; } test "StaticTrie" { var trie = Trie([]const u8).init(std.debug.global_allocator); const words = [][]const u8 { "peter", "piper", "picked", "peck", "pickled", "peppers" }; for (words) |word| { try trie.put(word, word); } for (words) |word| { std.debug.warn("{}\n", trie.get(word)); } }
src/index.zig
const vk = @import("vulkan.zig"); usingnamespace @import("vez-l1.zig"); pub const struct_Swapchain_T = opaque {}; pub const Swapchain = ?*struct_Swapchain_T; pub const struct_Pipeline_T = opaque {}; pub const Pipeline = ?*struct_Pipeline_T; pub const struct_Framebuffer_T = opaque {}; pub const Framebuffer = ?*struct_Framebuffer_T; pub const struct_VertexInputFormat_T = opaque {}; pub const VertexInputFormat = ?*struct_VertexInputFormat_T; pub const MEMORY_GPU_ONLY = @enumToInt(enum_MemoryFlagsBits.MEMORY_GPU_ONLY); pub const MEMORY_CPU_ONLY = @enumToInt(enum_MemoryFlagsBits.MEMORY_CPU_ONLY); pub const MEMORY_CPU_TO_GPU = @enumToInt(enum_MemoryFlagsBits.MEMORY_CPU_TO_GPU); pub const MEMORY_GPU_TO_CPU = @enumToInt(enum_MemoryFlagsBits.MEMORY_GPU_TO_CPU); pub const MEMORY_DEDICATED_ALLOCATION = @enumToInt(enum_MemoryFlagsBits.MEMORY_DEDICATED_ALLOCATION); pub const MEMORY_NO_ALLOCATION = @enumToInt(enum_MemoryFlagsBits.MEMORY_NO_ALLOCATION); pub const enum_MemoryFlagsBits = extern enum(c_int) { MEMORY_GPU_ONLY = 0, MEMORY_CPU_ONLY = 1, MEMORY_CPU_TO_GPU = 2, MEMORY_GPU_TO_CPU = 4, MEMORY_DEDICATED_ALLOCATION = 8, MEMORY_NO_ALLOCATION = 16, _, }; pub const MemoryFlagsBits = enum_MemoryFlagsBits; pub const MemoryFlags = vk.Flags; pub const BASE_TYPE_BOOL = @enumToInt(enum_BaseType.BASE_TYPE_BOOL); pub const BASE_TYPE_CHAR = @enumToInt(enum_BaseType.BASE_TYPE_CHAR); pub const BASE_TYPE_INT = @enumToInt(enum_BaseType.BASE_TYPE_INT); pub const BASE_TYPE_UINT = @enumToInt(enum_BaseType.BASE_TYPE_UINT); pub const BASE_TYPE_UINT64 = @enumToInt(enum_BaseType.BASE_TYPE_UINT64); pub const BASE_TYPE_HALF = @enumToInt(enum_BaseType.BASE_TYPE_HALF); pub const BASE_TYPE_FLOAT = @enumToInt(enum_BaseType.BASE_TYPE_FLOAT); pub const BASE_TYPE_DOUBLE = @enumToInt(enum_BaseType.BASE_TYPE_DOUBLE); pub const BASE_TYPE_STRUCT = @enumToInt(enum_BaseType.BASE_TYPE_STRUCT); pub const enum_BaseType = extern enum(c_int) { BASE_TYPE_BOOL = 0, BASE_TYPE_CHAR = 1, BASE_TYPE_INT = 2, BASE_TYPE_UINT = 3, BASE_TYPE_UINT64 = 4, BASE_TYPE_HALF = 5, BASE_TYPE_FLOAT = 6, BASE_TYPE_DOUBLE = 7, BASE_TYPE_STRUCT = 8, _, }; pub const BaseType = enum_BaseType; pub const PIPELINE_RESOURCE_TYPE_INPUT = @enumToInt(enum_PipelineResourceType.PIPELINE_RESOURCE_TYPE_INPUT); pub const PIPELINE_RESOURCE_TYPE_OUTPUT = @enumToInt(enum_PipelineResourceType.PIPELINE_RESOURCE_TYPE_OUTPUT); pub const PIPELINE_RESOURCE_TYPE_SAMPLER = @enumToInt(enum_PipelineResourceType.PIPELINE_RESOURCE_TYPE_SAMPLER); pub const PIPELINE_RESOURCE_TYPE_COMBINED_IMAGE_SAMPLER = @enumToInt(enum_PipelineResourceType.PIPELINE_RESOURCE_TYPE_COMBINED_IMAGE_SAMPLER); pub const PIPELINE_RESOURCE_TYPE_SAMPLED_IMAGE = @enumToInt(enum_PipelineResourceType.PIPELINE_RESOURCE_TYPE_SAMPLED_IMAGE); pub const PIPELINE_RESOURCE_TYPE_STORAGE_IMAGE = @enumToInt(enum_PipelineResourceType.PIPELINE_RESOURCE_TYPE_STORAGE_IMAGE); pub const PIPELINE_RESOURCE_TYPE_UNIFORM_TEXEL_BUFFER = @enumToInt(enum_PipelineResourceType.PIPELINE_RESOURCE_TYPE_UNIFORM_TEXEL_BUFFER); pub const PIPELINE_RESOURCE_TYPE_STORAGE_TEXEL_BUFFER = @enumToInt(enum_PipelineResourceType.PIPELINE_RESOURCE_TYPE_STORAGE_TEXEL_BUFFER); pub const PIPELINE_RESOURCE_TYPE_UNIFORM_BUFFER = @enumToInt(enum_PipelineResourceType.PIPELINE_RESOURCE_TYPE_UNIFORM_BUFFER); pub const PIPELINE_RESOURCE_TYPE_STORAGE_BUFFER = @enumToInt(enum_PipelineResourceType.PIPELINE_RESOURCE_TYPE_STORAGE_BUFFER); pub const PIPELINE_RESOURCE_TYPE_INPUT_ATTACHMENT = @enumToInt(enum_PipelineResourceType.PIPELINE_RESOURCE_TYPE_INPUT_ATTACHMENT); pub const PIPELINE_RESOURCE_TYPE_PUSH_CONSTANT_BUFFER = @enumToInt(enum_PipelineResourceType.PIPELINE_RESOURCE_TYPE_PUSH_CONSTANT_BUFFER); pub const enum_PipelineResourceType = extern enum(c_int) { PIPELINE_RESOURCE_TYPE_INPUT = 0, PIPELINE_RESOURCE_TYPE_OUTPUT = 1, PIPELINE_RESOURCE_TYPE_SAMPLER = 2, PIPELINE_RESOURCE_TYPE_COMBINED_IMAGE_SAMPLER = 3, PIPELINE_RESOURCE_TYPE_SAMPLED_IMAGE = 4, PIPELINE_RESOURCE_TYPE_STORAGE_IMAGE = 5, PIPELINE_RESOURCE_TYPE_UNIFORM_TEXEL_BUFFER = 6, PIPELINE_RESOURCE_TYPE_STORAGE_TEXEL_BUFFER = 7, PIPELINE_RESOURCE_TYPE_UNIFORM_BUFFER = 8, PIPELINE_RESOURCE_TYPE_STORAGE_BUFFER = 9, PIPELINE_RESOURCE_TYPE_INPUT_ATTACHMENT = 10, PIPELINE_RESOURCE_TYPE_PUSH_CONSTANT_BUFFER = 11, _, }; pub const PipelineResourceType = enum_PipelineResourceType; pub const struct_ClearAttachment = extern struct { colorAttachment: u32, clearValue: vk.ClearValue, }; pub const ClearAttachment = struct_ClearAttachment; pub const struct_ApplicationInfo = extern struct { pNext: ?*const c_void = null, pApplicationName: [*c]const u8, applicationVersion: u32, pEngineName: [*c]const u8, engineVersion: u32, }; pub const ApplicationInfo = struct_ApplicationInfo; pub const struct_InstanceCreateInfo = extern struct { pNext: ?*const c_void = null, pApplicationInfo: [*c]const ApplicationInfo, enabledLayerCount: u32, ppEnabledLayerNames: [*c]const [*c]const u8, enabledExtensionCount: u32, ppEnabledExtensionNames: [*c]const [*c]const u8, }; pub const InstanceCreateInfo = struct_InstanceCreateInfo; pub const struct_SwapchainCreateInfo = extern struct { pNext: ?*const c_void = null, surface: vk.SurfaceKHR, format: vk.SurfaceFormatKHR, tripleBuffer: vk.Bool32, }; pub const SwapchainCreateInfo = struct_SwapchainCreateInfo; pub const struct_DeviceCreateInfo = extern struct { pNext: ?*const c_void = null, enabledLayerCount: u32, ppEnabledLayerNames: [*c]const [*c]const u8, enabledExtensionCount: u32, ppEnabledExtensionNames: [*c]const [*c]const u8, }; pub const DeviceCreateInfo = struct_DeviceCreateInfo; pub const struct_SubmitInfo = extern struct { pNext: ?*const c_void = null, waitSemaphoreCount: u32, pWaitSemaphores: [*c]const vk.Semaphore, pWaitDstStageMask: [*c]const vk.PipelineStageFlags, commandBufferCount: u32, pCommandBuffers: [*c]const vk.CommandBuffer, signalSemaphoreCount: u32, pSignalSemaphores: [*c]vk.Semaphore, }; pub const SubmitInfo = struct_SubmitInfo; pub const struct_PresentInfo = extern struct { pNext: ?*const c_void = null, waitSemaphoreCount: u32, pWaitSemaphores: [*c]const vk.Semaphore, pWaitDstStageMask: [*c]const vk.PipelineStageFlags, swapchainCount: u32, pSwapchains: [*c]const Swapchain, pImages: [*c]const vk.Image, signalSemaphoreCount: u32, pSignalSemaphores: [*c]vk.Semaphore, pResults: [*c]vk.Result, }; pub const PresentInfo = struct_PresentInfo; pub const struct_QueryPoolCreateInfo = extern struct { pNext: ?*const c_void = null, queryType: vk.QueryType, queryCount: u32, pipelineStatistics: vk.QueryPipelineStatisticFlags, }; pub const QueryPoolCreateInfo = struct_QueryPoolCreateInfo; pub const struct_CommandBufferAllocateInfo = extern struct { pNext: ?*const c_void = null, queue: vk.Queue, commandBufferCount: u32, }; pub const CommandBufferAllocateInfo = struct_CommandBufferAllocateInfo; pub const struct_ShaderModuleCreateInfo = extern struct { pNext: ?*const c_void = null, stage: vk.ShaderStageFlagBits, codeSize: usize, pCode: [*c]const u32, pGLSLSource: [*c]const u8, pEntryPoint: [*c]const u8, }; pub const ShaderModuleCreateInfo = struct_ShaderModuleCreateInfo; pub const struct_PipelineShaderStageCreateInfo = extern struct { pNext: ?*const c_void = null, module: vk.ShaderModule, pEntryPoint: [*c]const u8, pSpecializationInfo: [*c]const vk.SpecializationInfo, }; pub const PipelineShaderStageCreateInfo = struct_PipelineShaderStageCreateInfo; pub const struct_GraphicsPipelineCreateInfo = extern struct { pNext: ?*const c_void = null, stageCount: u32, pStages: [*c]const PipelineShaderStageCreateInfo, }; pub const GraphicsPipelineCreateInfo = struct_GraphicsPipelineCreateInfo; pub const struct_ComputePipelineCreateInfo = extern struct { pNext: ?*const c_void = null, pStage: [*c]const PipelineShaderStageCreateInfo, }; pub const ComputePipelineCreateInfo = struct_ComputePipelineCreateInfo; pub const struct_MemberInfo = extern struct { baseType: BaseType, offset: u32, size: u32, vecSize: u32, columns: u32, arraySize: u32, name: [256]u8, pNext: [*c]const struct_MemberInfo, pMembers: [*c]const struct_MemberInfo, }; pub const MemberInfo = struct_MemberInfo; pub const struct_PipelineResource = extern struct { stages: vk.ShaderStageFlags, resourceType: PipelineResourceType, baseType: BaseType, access: vk.AccessFlags, set: u32, binding: u32, location: u32, inputAttachmentIndex: u32, vecSize: u32, columns: u32, arraySize: u32, offset: u32, size: u32, name: [256]u8, pMembers: [*c]const MemberInfo, }; pub const PipelineResource = struct_PipelineResource; pub const struct_VertexInputFormatCreateInfo = extern struct { vertexBindingDescriptionCount: u32, pVertexBindingDescriptions: [*c]const vk.VertexInputBindingDescription, vertexAttributeDescriptionCount: u32, pVertexAttributeDescriptions: [*c]const vk.VertexInputAttributeDescription, }; pub const VertexInputFormatCreateInfo = struct_VertexInputFormatCreateInfo; pub const struct_SamplerCreateInfo = extern struct { pNext: ?*const c_void = null, magFilter: vk.Filter, minFilter: vk.Filter, mipmapMode: vk.SamplerMipmapMode, addressModeU: vk.SamplerAddressMode, addressModeV: vk.SamplerAddressMode, addressModeW: vk.SamplerAddressMode, mipLodBias: f32 = 0, anisotropyEnable: vk.Bool32 = 0, maxAnisotropy: f32 = 0, compareEnable: vk.Bool32 = 0, compareOp: vk.CompareOp = .COMPARE_OP_NEVER, minLod: f32 = 0, maxLod: f32 = 0, borderColor: vk.BorderColor, unnormalizedCoordinates: vk.Bool32, }; pub const SamplerCreateInfo = struct_SamplerCreateInfo; pub const struct_BufferCreateInfo = extern struct { pNext: ?*const c_void = null, size: vk.DeviceSize, usage: vk.BufferUsageFlags, queueFamilyIndexCount: u32 = 0, pQueueFamilyIndices: [*c]const u32 = null, }; pub const BufferCreateInfo = struct_BufferCreateInfo; pub const struct_MappedBufferRange = extern struct { buffer: vk.Buffer, offset: vk.DeviceSize, size: vk.DeviceSize, }; pub const MappedBufferRange = struct_MappedBufferRange; pub const struct_BufferViewCreateInfo = extern struct { pNext: ?*const c_void = null, buffer: vk.Buffer, format: vk.Format, offset: vk.DeviceSize, range: vk.DeviceSize, }; pub const BufferViewCreateInfo = struct_BufferViewCreateInfo; pub const struct_ImageCreateInfo = extern struct { pNext: ?*const c_void = null, flags: vk.ImageCreateFlags = 0, imageType: vk.ImageType = .IMAGE_TYPE_2D, format: vk.Format, extent: vk.Extent3D, mipLevels: u32 = 1, arrayLayers: u32 = 1, samples: vk.SampleCountFlagBits = .SAMPLE_COUNT_1_BIT, tiling: vk.ImageTiling = .IMAGE_TILING_OPTIMAL, usage: vk.ImageUsageFlags, queueFamilyIndexCount: u32 = 0, pQueueFamilyIndices: [*c]const u32 = null, }; pub const ImageCreateInfo = struct_ImageCreateInfo; pub const struct_ImageSubresource = extern struct { mipLevel: u32, arrayLayer: u32, }; pub const ImageSubresource = struct_ImageSubresource; pub const struct_SubresourceLayout = extern struct { offset: vk.DeviceSize, size: vk.DeviceSize, rowPitch: vk.DeviceSize, arrayPitch: vk.DeviceSize, depthPitch: vk.DeviceSize, }; pub const SubresourceLayout = struct_SubresourceLayout; pub const struct_ImageSubresourceRange = extern struct { baseMipLevel: u32 = 0, levelCount: u32 = 1, baseArrayLayer: u32 = 0, layerCount: u32 = 1, }; pub const ImageSubresourceRange = struct_ImageSubresourceRange; pub const struct_ImageViewCreateInfo = extern struct { pNext: ?*const c_void = null, image: vk.Image, viewType: vk.ImageViewType, format: vk.Format, components: vk.ComponentMapping = vk.ComponentMapping{}, subresourceRange: ImageSubresourceRange = ImageSubresourceRange{}, }; pub const ImageViewCreateInfo = struct_ImageViewCreateInfo; pub const struct_FramebufferCreateInfo = extern struct { pNext: ?*const c_void = null, attachmentCount: u32, pAttachments: [*c]const vk.ImageView, width: u32, height: u32, layers: u32, }; pub const FramebufferCreateInfo = struct_FramebufferCreateInfo; pub const struct_InputAssemblyState = extern struct { pNext: ?*const c_void = null, topology: vk.PrimitiveTopology, primitiveRestartEnable: vk.Bool32, }; pub const InputAssemblyState = struct_InputAssemblyState; pub const struct_RasterizationState = extern struct { pNext: ?*const c_void = null, depthClampEnable: vk.Bool32, rasterizerDiscardEnable: vk.Bool32, polygonMode: vk.PolygonMode, cullMode: vk.CullModeFlags, frontFace: vk.FrontFace, depthBiasEnable: vk.Bool32, }; pub const RasterizationState = struct_RasterizationState; pub const struct_MultisampleState = extern struct { pNext: ?*const c_void = null, rasterizationSamples: vk.SampleCountFlagBits, sampleShadingEnable: vk.Bool32, minSampleShading: f32, pSampleMask: [*c]const vk.SampleMask, alphaToCoverageEnable: vk.Bool32, alphaToOneEnable: vk.Bool32, }; pub const MultisampleStateCreateInfo = struct_MultisampleState; pub const struct_StencilOpState = extern struct { failOp: vk.StencilOp, passOp: vk.StencilOp, depthFailOp: vk.StencilOp, compareOp: vk.CompareOp = .COMPARE_OP_NEVER, }; pub const StencilOpState = struct_StencilOpState; pub const struct_DepthStencilState = extern struct { pNext: ?*const c_void = null, depthTestEnable: vk.Bool32, depthWriteEnable: vk.Bool32, depthCompareOp: vk.CompareOp, depthBoundsTestEnable: vk.Bool32, stencilTestEnable: vk.Bool32, front: StencilOpState, back: StencilOpState, }; pub const PipelineDepthStencilState = struct_DepthStencilState; pub const struct_ColorBlendAttachmentState = extern struct { blendEnable: vk.Bool32, srcColorBlendFactor: vk.BlendFactor, dstColorBlendFactor: vk.BlendFactor, colorBlendOp: vk.BlendOp, srcAlphaBlendFactor: vk.BlendFactor, dstAlphaBlendFactor: vk.BlendFactor, alphaBlendOp: vk.BlendOp, colorWriteMask: vk.ColorComponentFlags, }; pub const ColorBlendAttachmentState = struct_ColorBlendAttachmentState; pub const struct_ColorBlendState = extern struct { pNext: ?*const c_void = null, logicOpEnable: vk.Bool32, logicOp: vk.LogicOp, attachmentCount: u32, pAttachments: [*c]const ColorBlendAttachmentState, }; pub const ColorBlendState = struct_ColorBlendState; pub const struct_AttachmentInfo = extern struct { loadOp: vk.AttachmentLoadOp = .ATTACHMENT_LOAD_OP_CLEAR, storeOp: vk.AttachmentStoreOp = .ATTACHMENT_STORE_OP_STORE, clearValue: vk.ClearValue, }; pub const AttachmentReference = struct_AttachmentInfo; pub const struct_RenderPassBeginInfo = extern struct { pNext: ?*const c_void = null, framebuffer: Framebuffer, attachmentCount: u32, pAttachments: [*c]const struct_AttachmentInfo, }; pub const RenderPassBeginInfo = struct_RenderPassBeginInfo; pub const struct_BufferCopy = extern struct { srcOffset: vk.DeviceSize, dstOffset: vk.DeviceSize, size: vk.DeviceSize, }; pub const BufferCopy = struct_BufferCopy; pub const struct_ImageSubresourceLayers = extern struct { mipLevel: u32 = 0, baseArrayLayer: u32 = 0, layerCount: u32 = 1, }; pub const ImageSubresourceLayers = struct_ImageSubresourceLayers; pub const struct_ImageSubDataInfo = extern struct { dataRowLength: u32 = 0, dataImageHeight: u32 = 0, imageSubresource: ImageSubresourceLayers = ImageSubresourceLayers{}, imageOffset: vk.Offset3D = vk.Offset3D{}, imageExtent: vk.Extent3D, }; pub const ImageSubDataInfo = struct_ImageSubDataInfo; pub const struct_ImageResolve = extern struct { srcSubresource: ImageSubresourceLayers, srcOffset: vk.Offset3D, dstSubresource: ImageSubresourceLayers, dstOffset: vk.Offset3D, extent: vk.Extent3D, }; pub const ImageResolve = struct_ImageResolve; pub const struct_ImageCopy = extern struct { srcSubresource: ImageSubresourceLayers, srcOffset: vk.Offset3D, dstSubresource: ImageSubresourceLayers, dstOffset: vk.Offset3D, extent: vk.Extent3D, }; pub const ImageCopy = struct_ImageCopy; pub const struct_ImageBlit = extern struct { srcSubresource: ImageSubresourceLayers, srcOffsets: [2]vk.Offset3D, dstSubresource: ImageSubresourceLayers, dstOffsets: [2]vk.Offset3D, }; pub const ImageBlit = struct_ImageBlit; pub const struct_BufferImageCopy = extern struct { bufferOffset: vk.DeviceSize, bufferRowLength: u32, bufferImageHeight: u32, imageSubresource: ImageSubresourceLayers, imageOffset: vk.Offset3D, imageExtent: vk.Extent3D, }; pub const BufferImageCopy = struct_BufferImageCopy; // Instance functions. pub extern fn vezEnumerateInstanceExtensionProperties(pLayerName: [*c]const u8, pPropertyCount: [*c]u32, pProperties: [*c]vk.ExtensionProperties) vk.Result; pub extern fn vezEnumerateInstanceLayerProperties(pPropertyCount: [*c]u32, pProperties: [*c]vk.LayerProperties) vk.Result; pub extern fn vezCreateInstance(pCreateInfo: [*c]const InstanceCreateInfo, pInstance: [*c]vk.Instance) vk.Result; pub extern fn vezDestroyInstance(instance: vk.Instance) void; pub extern fn vezEnumeratePhysicalDevices(instance: vk.Instance, pPhysicalDeviceCount: [*c]u32, pPhysicalDevices: [*c]vk.PhysicalDevice) vk.Result; // Physical device functions. pub extern fn vezGetPhysicalDeviceProperties(physicalDevice: vk.PhysicalDevice, pProperties: [*c]vk.PhysicalDeviceProperties) void; pub extern fn vezGetPhysicalDeviceFeatures(physicalDevice: vk.PhysicalDevice, pFeatures: [*c]vk.PhysicalDeviceFeatures) void; pub extern fn vezGetPhysicalDeviceFormatProperties(physicalDevice: vk.PhysicalDevice, format: vk.Format, pFormatProperties: [*c]vk.FormatProperties) void; pub extern fn vezGetPhysicalDeviceImageFormatProperties(physicalDevice: vk.PhysicalDevice, format: vk.Format, type: vk.ImageType, tiling: vk.ImageTiling, usage: vk.ImageUsageFlags, flags: vk.ImageCreateFlags, pImageFormatProperties: [*c]vk.ImageFormatProperties) vk.Result; pub extern fn vezGetPhysicalDeviceQueueFamilyProperties(physicalDevice: vk.PhysicalDevice, pQueueFamilyPropertyCount: [*c]u32, pQueueFamilyProperties: [*c]vk.QueueFamilyProperties) void; pub extern fn vezGetPhysicalDeviceSurfaceFormats(physicalDevice: vk.PhysicalDevice, surface: vk.SurfaceKHR, pSurfaceFormatCount: [*c]u32, pSurfaceFormats: [*c]vk.SurfaceFormatKHR) vk.Result; pub extern fn vezGetPhysicalDevicePresentSupport(physicalDevice: vk.PhysicalDevice, queueFamilyIndex: u32, surface: vk.SurfaceKHR, pSupported: [*c]vk.Bool32) vk.Result; pub extern fn vezEnumerateDeviceExtensionProperties(physicalDevice: vk.PhysicalDevice, pLayerName: [*c]const u8, pPropertyCount: [*c]u32, pProperties: [*c]vk.ExtensionProperties) vk.Result; pub extern fn vezEnumerateDeviceLayerProperties(physicalDevice: vk.PhysicalDevice, pPropertyCount: [*c]u32, pProperties: [*c]vk.LayerProperties) vk.Result; // Device functions. pub extern fn vezCreateDevice(physicalDevice: vk.PhysicalDevice, pCreateInfo: [*c]const DeviceCreateInfo, pDevice: [*c]vk.Device) vk.Result; pub extern fn vezDestroyDevice(device: vk.Device) void; pub extern fn vezDeviceWaitIdle(device: vk.Device) vk.Result; pub extern fn vezGetDeviceQueue(device: vk.Device, queueFamilyIndex: u32, queueIndex: u32, pQueue: [*c]vk.Queue) void; pub extern fn vezGetDeviceGraphicsQueue(device: vk.Device, queueIndex: u32, pQueue: [*c]vk.Queue) void; pub extern fn vezGetDeviceComputeQueue(device: vk.Device, queueIndex: u32, pQueue: [*c]vk.Queue) void; pub extern fn vezGetDeviceTransferQueue(device: vk.Device, queueIndex: u32, pQueue: [*c]vk.Queue) void; // Swapchain pub extern fn vezCreateSwapchain(device: vk.Device, pCreateInfo: [*c]const SwapchainCreateInfo, pSwapchain: [*c]Swapchain) vk.Result; pub extern fn vezDestroySwapchain(device: vk.Device, swapchain: Swapchain) void; pub extern fn vezGetSwapchainSurfaceFormat(swapchain: Swapchain, pFormat: [*c]vk.SurfaceFormatKHR) void; pub extern fn vezSwapchainSetVSync(swapchain: Swapchain, enabled: vk.Bool32) vk.Result; // Queue functions. pub extern fn vezQueueSubmit(queue: vk.Queue, submitCount: u32, pSubmits: [*c]const SubmitInfo, pFence: [*c]vk.Fence) vk.Result; pub extern fn vezQueuePresent(queue: vk.Queue, pPresentInfo: [*c]const PresentInfo) vk.Result; pub extern fn vezQueueWaitIdle(queue: vk.Queue) vk.Result; // Synchronization primitives functions. pub extern fn vezDestroyFence(device: vk.Device, fence: vk.Fence) void; pub extern fn vezGetFenceStatus(device: vk.Device, fence: vk.Fence) vk.Result; pub extern fn vezWaitForFences(device: vk.Device, fenceCount: u32, pFences: [*c]const vk.Fence, waitAll: vk.Bool32, timeout: u64) vk.Result; pub extern fn vezDestroySemaphore(device: vk.Device, semaphore: vk.Semaphore) void; pub extern fn vezCreateEvent(device: vk.Device, pEvent: [*c]vk.Event) vk.Result; pub extern fn vezDestroyEvent(device: vk.Device, event: vk.Event) void; pub extern fn vezGetEventStatus(device: vk.Device, event: vk.Event) vk.Result; pub extern fn vezSetEvent(device: vk.Device, event: vk.Event) vk.Result; pub extern fn vezResetEvent(device: vk.Device, event: vk.Event) vk.Result; // Query pool functions. pub extern fn vezCreateQueryPool(device: vk.Device, pCreateInfo: [*c]const QueryPoolCreateInfo, pQueryPool: [*c]vk.QueryPool) vk.Result; pub extern fn vezDestroyQueryPool(device: vk.Device, queryPool: vk.QueryPool) void; pub extern fn vezGetQueryPoolResults(device: vk.Device, queryPool: vk.QueryPool, firstQuery: u32, queryCount: u32, dataSize: usize, pData: ?*c_void, stride: vk.DeviceSize, flags: vk.QueryResultFlags) vk.Result; // Shader module and pipeline functions. pub extern fn vezCreateShaderModule(device: vk.Device, pCreateInfo: [*c]const ShaderModuleCreateInfo, pShaderModule: [*c]vk.ShaderModule) vk.Result; pub extern fn vezDestroyShaderModule(device: vk.Device, shaderModule: vk.ShaderModule) void; pub extern fn vezGetShaderModuleInfoLog(shaderModule: vk.ShaderModule, pLength: [*c]u32, pInfoLog: [*c]u8) void; pub extern fn vezGetShaderModuleBinary(shaderModule: vk.ShaderModule, pLength: [*c]u32, pBinary: [*c]u32) vk.Result; pub extern fn vezCreateGraphicsPipeline(device: vk.Device, pCreateInfo: [*c]const GraphicsPipelineCreateInfo, pPipeline: [*c]Pipeline) vk.Result; pub extern fn vezCreateComputePipeline(device: vk.Device, pCreateInfo: [*c]const ComputePipelineCreateInfo, pPipeline: [*c]Pipeline) vk.Result; pub extern fn vezDestroyPipeline(device: vk.Device, pipeline: Pipeline) void; pub extern fn vezEnumeratePipelineResources(pipeline: Pipeline, pResourceCount: [*c]u32, ppResources: [*c]PipelineResource) vk.Result; pub extern fn vezGetPipelineResource(pipeline: Pipeline, name: [*c]const u8, pResource: [*c]PipelineResource) vk.Result; // Vertex input format functions. pub extern fn vezCreateVertexInputFormat(device: vk.Device, pCreateInfo: [*c]const VertexInputFormatCreateInfo, pFormat: [*c]VertexInputFormat) vk.Result; pub extern fn vezDestroyVertexInputFormat(device: vk.Device, format: VertexInputFormat) void; // Sampler functions. pub extern fn vezCreateSampler(device: vk.Device, pCreateInfo: [*c]const SamplerCreateInfo, pSampler: [*c]vk.Sampler) vk.Result; pub extern fn vezDestroySampler(device: vk.Device, sampler: vk.Sampler) void; // Buffer functions. pub extern fn vezCreateBuffer(device: vk.Device, memFlags: MemoryFlags, pCreateInfo: [*c]const BufferCreateInfo, pBuffer: [*c]vk.Buffer) vk.Result; pub extern fn vezDestroyBuffer(device: vk.Device, buffer: vk.Buffer) void; pub extern fn vezBufferSubData(device: vk.Device, buffer: vk.Buffer, offset: vk.DeviceSize, size: vk.DeviceSize, pData: ?[*]const u8) vk.Result; pub extern fn vezMapBuffer(device: vk.Device, buffer: vk.Buffer, offset: vk.DeviceSize, size: vk.DeviceSize, ppData: [*c]?*c_void) vk.Result; pub extern fn vezUnmapBuffer(device: vk.Device, buffer: vk.Buffer) void; pub extern fn vezFlushMappedBufferRanges(device: vk.Device, bufferRangeCount: u32, pBufferRanges: [*c]const MappedBufferRange) vk.Result; pub extern fn vezInvalidateMappedBufferRanges(device: vk.Device, bufferRangeCount: u32, pBufferRanges: [*c]const MappedBufferRange) vk.Result; pub extern fn vezCreateBufferView(device: vk.Device, pCreateInfo: [*c]const BufferViewCreateInfo, pView: [*c]vk.BufferView) vk.Result; pub extern fn vezDestroyBufferView(device: vk.Device, bufferView: vk.BufferView) void; // Image functions. pub extern fn vezCreateImage(device: vk.Device, memFlags: MemoryFlags, pCreateInfo: [*c]const ImageCreateInfo, pImage: [*c]vk.Image) vk.Result; pub extern fn vezDestroyImage(device: vk.Device, image: vk.Image) void; pub extern fn vezImageSubData(device: vk.Device, image: vk.Image, pSubDataInfo: *const ImageSubDataInfo, pData: ?[*]const u8) vk.Result; pub extern fn vezCreateImageView(device: vk.Device, pCreateInfo: *const ImageViewCreateInfo, pView: *vk.ImageView) vk.Result; pub extern fn vezDestroyImageView(device: vk.Device, imageView: vk.ImageView) void; // Framebuffer functions. pub extern fn vezCreateFramebuffer(device: vk.Device, pCreateInfo: *const FramebufferCreateInfo, pFramebuffer: *Framebuffer) vk.Result; pub extern fn vezDestroyFramebuffer(device: vk.Device, framebuffer: Framebuffer) void; // Command buffer functions. pub extern fn vezAllocateCommandBuffers(device: vk.Device, pAllocateInfo: *const CommandBufferAllocateInfo, pCommandBuffers: [*c]vk.CommandBuffer) vk.Result; pub extern fn vezFreeCommandBuffers(device: vk.Device, commandBufferCount: u32, pCommandBuffers: [*c]const vk.CommandBuffer) void; pub extern fn vezBeginCommandBuffer(commandBuffer: vk.CommandBuffer, flags: vk.CommandBufferUsageFlags) vk.Result; pub extern fn vezEndCommandBuffer(...) vk.Result; pub extern fn vezResetCommandBuffer(commandBuffer: vk.CommandBuffer) vk.Result; pub extern fn vezCmdBeginRenderPass(pBeginInfo: [*c]const RenderPassBeginInfo) void; pub extern fn vezCmdNextSubpass(...) void; pub extern fn vezCmdEndRenderPass(...) void; pub extern fn vezCmdBindPipeline(pipeline: Pipeline) void; pub extern fn vezCmdPushConstants(offset: u32, size: u32, pValues: ?[*]const u8) void; pub extern fn vezCmdBindBuffer(buffer: vk.Buffer, offset: vk.DeviceSize, range: vk.DeviceSize, set: u32, binding: u32, arrayElement: u32) void; pub extern fn vezCmdBindBufferView(bufferView: vk.BufferView, set: u32, binding: u32, arrayElement: u32) void; pub extern fn vezCmdBindImageView(imageView: vk.ImageView, sampler: vk.Sampler, set: u32, binding: u32, arrayElement: u32) void; pub extern fn vezCmdBindSampler(sampler: vk.Sampler, set: u32, binding: u32, arrayElement: u32) void; pub extern fn vezCmdBindVertexBuffers(firstBinding: u32, bindingCount: u32, pBuffers: [*]const vk.Buffer, pOffsets: [*]const vk.DeviceSize) void; pub extern fn vezCmdBindIndexBuffer(buffer: vk.Buffer, offset: vk.DeviceSize, indexType: vk.IndexType) void; pub extern fn vezCmdSetVertexInputFormat(format: VertexInputFormat) void; pub extern fn vezCmdSetViewportState(viewportCount: u32) void; pub extern fn vezCmdSetInputAssemblyState(pStateInfo: *const InputAssemblyState) void; pub extern fn vezCmdSetRasterizationState(pStateInfo: *const RasterizationState) void; pub extern fn vezCmdSetMultisampleState(pStateInfo: *const MultisampleStateCreateInfo) void; pub extern fn vezCmdSetDepthStencilState(pStateInfo: *const PipelineDepthStencilState) void; pub extern fn vezCmdSetColorBlendState(pStateInfo: *const ColorBlendState) void; pub extern fn vezCmdSetViewport(firstViewport: u32, viewportCount: u32, pViewports: [*]const vk.Viewport) void; pub extern fn vezCmdSetScissor(firstScissor: u32, scissorCount: u32, pScissors: [*]const vk.Rect2D) void; pub extern fn vezCmdSetLineWidth(lineWidth: f32) void; pub extern fn vezCmdSetDepthBias(depthBiasConstantFactor: f32, depthBiasClamp: f32, depthBiasSlopeFactor: f32) void; pub extern fn vezCmdSetBlendConstants(blendConstants: [*c]const f32) void; pub extern fn vezCmdSetDepthBounds(minDepthBounds: f32, maxDepthBounds: f32) void; pub extern fn vezCmdSetStencilCompareMask(faceMask: vk.StencilFaceFlags, compareMask: u32) void; pub extern fn vezCmdSetStencilWriteMask(faceMask: vk.StencilFaceFlags, writeMask: u32) void; pub extern fn vezCmdSetStencilReference(faceMask: vk.StencilFaceFlags, reference: u32) void; pub extern fn vezCmdDraw(vertexCount: u32, instanceCount: u32, firstVertex: u32, firstInstance: u32) void; pub extern fn vezCmdDrawIndexed(indexCount: u32, instanceCount: u32, firstIndex: u32, vertexOffset: i32, firstInstance: u32) void; pub extern fn vezCmdDrawIndirect(buffer: vk.Buffer, offset: vk.DeviceSize, drawCount: u32, stride: u32) void; pub extern fn vezCmdDrawIndexedIndirect(buffer: vk.Buffer, offset: vk.DeviceSize, drawCount: u32, stride: u32) void; pub extern fn vezCmdDispatch(groupCountX: u32, groupCountY: u32, groupCountZ: u32) void; pub extern fn vezCmdDispatchIndirect(buffer: vk.Buffer, offset: vk.DeviceSize) void; pub extern fn vezCmdCopyBuffer(srcBuffer: vk.Buffer, dstBuffer: vk.Buffer, regionCount: u32, pRegions: [*]const BufferCopy) void; pub extern fn vezCmdCopyImage(srcImage: vk.Image, dstImage: vk.Image, regionCount: u32, pRegions: [*]const ImageCopy) void; pub extern fn vezCmdBlitImage(srcImage: vk.Image, dstImage: vk.Image, regionCount: u32, pRegions: [*]const ImageBlit, filter: vk.Filter) void; pub extern fn vezCmdCopyBufferToImage(srcBuffer: vk.Buffer, dstImage: vk.Image, regionCount: u32, pRegions: [*]const BufferImageCopy) void; pub extern fn vezCmdCopyImageToBuffer(srcImage: vk.Image, dstBuffer: vk.Buffer, regionCount: u32, pRegions: [*]const BufferImageCopy) void; pub extern fn vezCmdUpdateBuffer(dstBuffer: vk.Buffer, dstOffset: vk.DeviceSize, dataSize: vk.DeviceSize, pData: ?[*]const u8) void; pub extern fn vezCmdFillBuffer(dstBuffer: vk.Buffer, dstOffset: vk.DeviceSize, size: vk.DeviceSize, data: u32) void; pub extern fn vezCmdClearColorImage(image: vk.Image, pColor: [*c]const vk.ClearColorValue, rangeCount: u32, pRanges: [*]const ImageSubresourceRange) void; pub extern fn vezCmdClearDepthStencilImage(image: vk.Image, pDepthStencil: *const vk.ClearDepthStencilValue, rangeCount: u32, pRanges: [*]const ImageSubresourceRange) void; pub extern fn vezCmdClearAttachments(attachmentCount: u32, pAttachments: [*]const ClearAttachment, rectCount: u32, pRects: [*]const vk.ClearRect) void; pub extern fn vezCmdResolveImage(srcImage: vk.Image, dstImage: vk.Image, regionCount: u32, pRegions: [*]const ImageResolve) void; pub extern fn vezCmdSetEvent(event: vk.Event, stageMask: vk.PipelineStageFlags) void; pub extern fn vezCmdResetEvent(event: vk.Event, stageMask: vk.PipelineStageFlags) void; pub const Swapchain_T = struct_Swapchain_T; pub const Pipeline_T = struct_Pipeline_T; pub const Framebuffer_T = struct_Framebuffer_T; pub const VertexInputFormat_T = struct_VertexInputFormat_T; pub const MultisampleState = struct_MultisampleState; pub const DepthStencilState = struct_DepthStencilState; pub const AttachmentInfo = struct_AttachmentInfo;
src/lib/vez.zig
const std = @import("std"); pub const Signal = enum { /// Hangup detected on controlling terminal or death of controlling process hup = 1, /// Interrupt from keyboard int = 2, /// Quit from keyboard quit = 3, /// Illegal Instruction ill = 4, /// Trace/breakpoint trap trap = 5, /// Abort signal from abort(3) abrt = 6, /// Bus error (bad memory access) bus = 7, /// Floating-point exception fpe = 8, /// Kill signal kill = 9, /// User-defined signal 1 usr1 = 10, /// Invalid memory reference segv = 11, /// User-defined signal 2 usr2 = 12, /// Broken pipe: write to pipe with no readers; see pipe(7) pipe = 13, /// Timer signal from alarm(2) alrm = 14, /// Termination signal term = 15, }; pub const Errno = enum(u12) { pub const E = blk: { const fields = std.meta.fields(Errno); var errors: [fields.len]std.builtin.TypeInfo.Error = undefined; for (fields) |field, i| { errors[i].name = field.name; } break :blk @Type(.{ .ErrorSet = &errors }); }; pub fn from(err: E) Errno { inline for (std.meta.fields(Errno)) |field| { if (err == @field(E, field.name)) { return @field(Errno, field.name); } } unreachable; } /// Operation not permitted EPERM = 1, /// No such file or directory ENOENT = 2, /// No such process ESRCH = 3, /// Interrupted system call EINTR = 4, /// I/O error EIO = 5, /// No such device or address ENXIO = 6, /// Arg list too long E2BIG = 7, /// Exec format error ENOEXEC = 8, /// Bad file number EBADF = 9, /// No child processes ECHILD = 10, /// Try again EAGAIN = 11, /// Out of memory ENOMEM = 12, /// Permission denied EACCES = 13, /// Bad address EFAULT = 14, /// Block device required ENOTBLK = 15, /// Device or resource busy EBUSY = 16, /// File exists EEXIST = 17, /// Cross-device link EXDEV = 18, /// No such device ENODEV = 19, /// Not a directory ENOTDIR = 20, /// Is a directory EISDIR = 21, /// Invalid argument EINVAL = 22, /// File table overflow ENFILE = 23, /// Too many open files EMFILE = 24, /// Not a typewriter ENOTTY = 25, /// Text file busy ETXTBSY = 26, /// File too large EFBIG = 27, /// No space left on device ENOSPC = 28, /// Illegal seek ESPIPE = 29, /// Read-only file system EROFS = 30, /// Too many links EMLINK = 31, /// Broken pipe EPIPE = 32, /// Math argument out of domain of func EDOM = 33, /// Math result not representable ERANGE = 34, /// Resource deadlock would occur EDEADLK = 35, /// File name too long ENAMETOOLONG = 36, /// No record locks available ENOLCK = 37, /// Function not implemented ENOSYS = 38, /// Directory not empty ENOTEMPTY = 39, /// Too many symbolic links encountered ELOOP = 40, /// No message of desired type ENOMSG = 42, /// Identifier removed EIDRM = 43, /// Channel number out of range ECHRNG = 44, /// Level 2 not synchronized EL2NSYNC = 45, /// Level 3 halted EL3HLT = 46, /// Level 3 reset EL3RST = 47, /// Link number out of range ELNRNG = 48, /// Protocol driver not attached EUNATCH = 49, /// No CSI structure available ENOCSI = 50, /// Level 2 halted EL2HLT = 51, /// Invalid exchange EBADE = 52, /// Invalid request descriptor EBADR = 53, /// Exchange full EXFULL = 54, /// No anode ENOANO = 55, /// Invalid request code EBADRQC = 56, /// Invalid slot EBADSLT = 57, /// Bad font file format EBFONT = 59, /// Device not a stream ENOSTR = 60, /// No data available ENODATA = 61, /// Timer expired ETIME = 62, /// Out of streams resources ENOSR = 63, /// Machine is not on the network ENONET = 64, /// Package not installed ENOPKG = 65, /// Object is remote EREMOTE = 66, /// Link has been severed ENOLINK = 67, /// Advertise error EADV = 68, /// Srmount error ESRMNT = 69, /// Communication error on send ECOMM = 70, /// Protocol error EPROTO = 71, /// Multihop attempted EMULTIHOP = 72, /// RFS specific error EDOTDOT = 73, /// Not a data message EBADMSG = 74, /// Value too large for defined data type EOVERFLOW = 75, /// Name not unique on network ENOTUNIQ = 76, /// File descriptor in bad state EBADFD = 77, /// Remote address changed EREMCHG = 78, /// Can not access a needed shared library ELIBACC = 79, /// Accessing a corrupted shared library ELIBBAD = 80, /// .lib section in a.out corrupted ELIBSCN = 81, /// Attempting to link in too many shared libraries ELIBMAX = 82, /// Cannot exec a shared library directly ELIBEXEC = 83, /// Illegal byte sequence EILSEQ = 84, /// Interrupted system call should be restarted ERESTART = 85, /// Streams pipe error ESTRPIPE = 86, /// Too many users EUSERS = 87, /// Socket operation on non-socket ENOTSOCK = 88, /// Destination address required EDESTADDRREQ = 89, /// Message too long EMSGSIZE = 90, /// Protocol wrong type for socket EPROTOTYPE = 91, /// Protocol not available ENOPROTOOPT = 92, /// Protocol not supported EPROTONOSUPPORT = 93, /// Socket type not supported ESOCKTNOSUPPORT = 94, /// Operation not supported on transport endpoint EOPNOTSUPP = 95, /// Protocol family not supported EPFNOSUPPORT = 96, /// Address family not supported by protocol EAFNOSUPPORT = 97, /// Address already in use EADDRINUSE = 98, /// Cannot assign requested address EADDRNOTAVAIL = 99, /// Network is down ENETDOWN = 100, /// Network is unreachable ENETUNREACH = 101, /// Network dropped connection because of reset ENETRESET = 102, /// Software caused connection abort ECONNABORTED = 103, /// Connection reset by peer ECONNRESET = 104, /// No buffer space available ENOBUFS = 105, /// Transport endpoint is already connected EISCONN = 106, /// Transport endpoint is not connected ENOTCONN = 107, /// Cannot send after transport endpoint shutdown ESHUTDOWN = 108, /// Too many references: cannot splice ETOOMANYREFS = 109, /// Connection timed out ETIMEDOUT = 110, /// Connection refused ECONNREFUSED = 111, /// Host is down EHOSTDOWN = 112, /// No route to host EHOSTUNREACH = 113, /// Operation already in progress EALREADY = 114, /// Operation now in progress EINPROGRESS = 115, /// Stale NFS file handle ESTALE = 116, /// Structure needs cleaning EUCLEAN = 117, /// Not a XENIX named type file ENOTNAM = 118, /// No XENIX semaphores available ENAVAIL = 119, /// Is a named type file EISNAM = 120, /// Remote I/O error EREMOTEIO = 121, /// Quota exceeded EDQUOT = 122, /// No medium found ENOMEDIUM = 123, /// Wrong medium type EMEDIUMTYPE = 124, /// Operation canceled ECANCELED = 125, /// Required key not available ENOKEY = 126, /// Key has expired EKEYEXPIRED = 127, /// Key has been revoked EKEYREVOKED = 128, /// Key was rejected by service EKEYREJECTED = 129, // for robust mutexes /// Owner died EOWNERDEAD = 130, /// State not recoverable ENOTRECOVERABLE = 131, /// Operation not possible due to RF-kill ERFKILL = 132, /// Memory page has hardware error EHWPOISON = 133, // nameserver query return codes /// DNS server returned answer with no data ENSROK = 0, /// DNS server returned answer with no data ENSRNODATA = 160, /// DNS server claims query was misformatted ENSRFORMERR = 161, /// DNS server returned general failure ENSRSERVFAIL = 162, /// Domain name not found ENSRNOTFOUND = 163, /// DNS server does not implement requested operation ENSRNOTIMP = 164, /// DNS server refused query ENSRREFUSED = 165, /// Misformatted DNS query ENSRBADQUERY = 166, /// Misformatted domain name ENSRBADNAME = 167, /// Unsupported address family ENSRBADFAMILY = 168, /// Misformatted DNS reply ENSRBADRESP = 169, /// Could not contact DNS servers ENSRCONNREFUSED = 170, /// Timeout while contacting DNS servers ENSRTIMEOUT = 171, /// End of file ENSROF = 172, /// Error reading file ENSRFILE = 173, /// Out of memory ENSRNOMEM = 174, /// Application terminated lookup ENSRDESTRUCTION = 175, /// Domain name is too long ENSRQUERYDOMAINTOOLONG = 176, /// Domain name is too long ENSRCNAMELOOP = 177, };
src/types.zig
const Print = @This(); const std = @import("std"); const assert = std.debug.assert; const bits = @import("bits.zig"); const leb128 = std.leb; const link = @import("../../link.zig"); const log = std.log.scoped(.codegen); const math = std.math; const mem = std.mem; const Air = @import("../../Air.zig"); const DebugInfoOutput = @import("../../codegen.zig").DebugInfoOutput; const DW = std.dwarf; const Encoder = bits.Encoder; const ErrorMsg = Module.ErrorMsg; const MCValue = @import("CodeGen.zig").MCValue; const Mir = @import("Mir.zig"); const Module = @import("../../Module.zig"); const Instruction = bits.Instruction; const Register = bits.Register; const Type = @import("../../type.zig").Type; const fmtIntSizeBin = std.fmt.fmtIntSizeBin; mir: Mir, pub fn printMir(print: *const Print, w: anytype, mir_to_air_map: std.AutoHashMap(Mir.Inst.Index, Air.Inst.Index), air: Air) !void { const instruction_bytes = print.mir.instructions.len * // Here we don't use @sizeOf(Mir.Inst.Data) because it would include // the debug safety tag but we want to measure release size. (@sizeOf(Mir.Inst.Tag) + 2 + 8); const extra_bytes = print.mir.extra.len * @sizeOf(u32); const total_bytes = @sizeOf(Mir) + instruction_bytes + extra_bytes; // zig fmt: off std.debug.print( \\# Total MIR bytes: {} \\# MIR Instructions: {d} ({}) \\# MIR Extra Data: {d} ({}) \\ , .{ fmtIntSizeBin(total_bytes), print.mir.instructions.len, fmtIntSizeBin(instruction_bytes), print.mir.extra.len, fmtIntSizeBin(extra_bytes), }); // zig fmt: on const mir_tags = print.mir.instructions.items(.tag); for (mir_tags) |tag, index| { const inst = @intCast(u32, index); if (mir_to_air_map.get(inst)) |air_index| { try w.print("air index %{} ({}) for following mir inst(s)\n", .{ air_index, air.instructions.items(.tag)[air_index] }); } try w.writeAll(" "); switch (tag) { .adc => try print.mirArith(.adc, inst, w), .add => try print.mirArith(.add, inst, w), .sub => try print.mirArith(.sub, inst, w), .xor => try print.mirArith(.xor, inst, w), .@"and" => try print.mirArith(.@"and", inst, w), .@"or" => try print.mirArith(.@"or", inst, w), .sbb => try print.mirArith(.sbb, inst, w), .cmp => try print.mirArith(.cmp, inst, w), .adc_scale_src => try print.mirArithScaleSrc(.adc, inst, w), .add_scale_src => try print.mirArithScaleSrc(.add, inst, w), .sub_scale_src => try print.mirArithScaleSrc(.sub, inst, w), .xor_scale_src => try print.mirArithScaleSrc(.xor, inst, w), .and_scale_src => try print.mirArithScaleSrc(.@"and", inst, w), .or_scale_src => try print.mirArithScaleSrc(.@"or", inst, w), .sbb_scale_src => try print.mirArithScaleSrc(.sbb, inst, w), .cmp_scale_src => try print.mirArithScaleSrc(.cmp, inst, w), .adc_scale_dst => try print.mirArithScaleDst(.adc, inst, w), .add_scale_dst => try print.mirArithScaleDst(.add, inst, w), .sub_scale_dst => try print.mirArithScaleDst(.sub, inst, w), .xor_scale_dst => try print.mirArithScaleDst(.xor, inst, w), .and_scale_dst => try print.mirArithScaleDst(.@"and", inst, w), .or_scale_dst => try print.mirArithScaleDst(.@"or", inst, w), .sbb_scale_dst => try print.mirArithScaleDst(.sbb, inst, w), .cmp_scale_dst => try print.mirArithScaleDst(.cmp, inst, w), .adc_scale_imm => try print.mirArithScaleImm(.adc, inst, w), .add_scale_imm => try print.mirArithScaleImm(.add, inst, w), .sub_scale_imm => try print.mirArithScaleImm(.sub, inst, w), .xor_scale_imm => try print.mirArithScaleImm(.xor, inst, w), .and_scale_imm => try print.mirArithScaleImm(.@"and", inst, w), .or_scale_imm => try print.mirArithScaleImm(.@"or", inst, w), .sbb_scale_imm => try print.mirArithScaleImm(.sbb, inst, w), .cmp_scale_imm => try print.mirArithScaleImm(.cmp, inst, w), .mov => try print.mirArith(.mov, inst, w), .mov_scale_src => try print.mirArithScaleSrc(.mov, inst, w), .mov_scale_dst => try print.mirArithScaleDst(.mov, inst, w), .mov_scale_imm => try print.mirArithScaleImm(.mov, inst, w), .movabs => try print.mirMovabs(inst, w), .lea => try print.mirLea(inst, w), .lea_rip => try print.mirLeaRip(inst, w), .imul_complex => try print.mirIMulComplex(inst, w), .push => try print.mirPushPop(.push, inst, w), .pop => try print.mirPushPop(.pop, inst, w), .jmp => try print.mirJmpCall(.jmp, inst, w), .call => try print.mirJmpCall(.call, inst, w), // .cond_jmp_greater_less => try print.mirCondJmp(.cond_jmp_greater_less, inst, w), // .cond_jmp_above_below => try print.mirCondJmp(.cond_jmp_above_below, inst, w), // .cond_jmp_eq_ne => try print.mirCondJmp(.cond_jmp_eq_ne, inst, w), // .cond_set_byte_greater_less => try print.mirCondSetByte(.cond_set_byte_greater_less, inst, w), // .cond_set_byte_above_below => try print.mirCondSetByte(.cond_set_byte_above_below, inst, w), // .cond_set_byte_eq_ne => try print.mirCondSetByte(.cond_set_byte_eq_ne, inst, w), // .@"test" => try print.mirTest(inst, w), .brk => try w.writeAll("brk\n"), .ret => try w.writeAll("ret\n"), .nop => try w.writeAll("nop\n"), .syscall => try w.writeAll("syscall\n"), .call_extern => try print.mirCallExtern(inst, w), .dbg_line, .dbg_prologue_end, .dbg_epilogue_begin, .arg_dbg_info => try w.print("{s}\n", .{@tagName(tag)}), .push_regs_from_callee_preserved_regs => try print.mirPushPopRegsFromCalleePreservedRegs(.push, inst, w), .pop_regs_from_callee_preserved_regs => try print.mirPushPopRegsFromCalleePreservedRegs(.pop, inst, w), else => { try w.print("TODO emit asm for {s}\n", .{@tagName(tag)}); }, } } } fn mirPushPop(print: *const Print, tag: Mir.Inst.Tag, inst: Mir.Inst.Index, w: anytype) !void { const ops = Mir.Ops.decode(print.mir.instructions.items(.ops)[inst]); switch (ops.flags) { 0b00 => { // PUSH/POP reg try w.print("{s} {s}", .{ @tagName(tag), @tagName(ops.reg1) }); }, 0b01 => { // PUSH/POP r/m64 const imm = print.mir.instructions.items(.data)[inst].imm; try w.print("{s} [{s} + {d}]", .{ @tagName(tag), @tagName(ops.reg1), imm }); }, 0b10 => { const imm = print.mir.instructions.items(.data)[inst].imm; // PUSH imm32 assert(tag == .push); try w.print("{s} {d}", .{ @tagName(tag), imm }); }, 0b11 => unreachable, } try w.writeByte('\n'); } fn mirPushPopRegsFromCalleePreservedRegs(print: *const Print, tag: Mir.Inst.Tag, inst: Mir.Inst.Index, w: anytype) !void { const callee_preserved_regs = bits.callee_preserved_regs; // PUSH/POP reg const regs = print.mir.instructions.items(.data)[inst].regs_to_push_or_pop; if (regs == 0) return w.writeAll("push/pop no regs from callee_preserved_regs\n"); if (tag == .push) { try w.writeAll("push "); for (callee_preserved_regs) |reg, i| { if ((regs >> @intCast(u5, i)) & 1 == 0) continue; try w.print("{s}, ", .{@tagName(reg)}); } } else { // pop in the reverse direction var i = callee_preserved_regs.len; try w.writeAll("pop "); while (i > 0) : (i -= 1) { if ((regs >> @intCast(u5, i - 1)) & 1 == 0) continue; const reg = callee_preserved_regs[i - 1]; try w.print("{s}, ", .{@tagName(reg)}); } } try w.writeByte('\n'); } fn mirJmpCall(print: *const Print, tag: Mir.Inst.Tag, inst: Mir.Inst.Index, w: anytype) !void { try w.print("{s} ", .{@tagName(tag)}); const ops = Mir.Ops.decode(print.mir.instructions.items(.ops)[inst]); const flag = @truncate(u1, ops.flags); if (flag == 0) { return w.writeAll("TODO target\n"); } if (ops.reg1 == .none) { // JMP/CALL [imm] const imm = print.mir.instructions.items(.data)[inst].imm; try w.print("[{x}]\n", .{imm}); return; } // JMP/CALL reg try w.print("{s}\n", .{@tagName(ops.reg1)}); } const CondType = enum { /// greater than or equal gte, /// greater than gt, /// less than lt, /// less than or equal lte, /// above or equal ae, /// above a, /// below b, /// below or equal be, /// not equal ne, /// equal eq, fn fromTagAndFlags(tag: Mir.Inst.Tag, flags: u2) CondType { return switch (tag) { .cond_jmp_greater_less, .cond_set_byte_greater_less, => switch (flags) { 0b00 => CondType.gte, 0b01 => CondType.gt, 0b10 => CondType.lt, 0b11 => CondType.lte, }, .cond_jmp_above_below, .cond_set_byte_above_below, => switch (flags) { 0b00 => CondType.ae, 0b01 => CondType.a, 0b10 => CondType.b, 0b11 => CondType.be, }, .cond_jmp_eq_ne, .cond_set_byte_eq_ne, => switch (@truncate(u1, flags)) { 0b0 => CondType.ne, 0b1 => CondType.eq, }, else => unreachable, }; } }; inline fn getCondOpCode(tag: Mir.Inst.Tag, cond: CondType) u8 { switch (cond) { .gte => return switch (tag) { .cond_jmp_greater_less => 0x8d, .cond_set_byte_greater_less => 0x9d, else => unreachable, }, .gt => return switch (tag) { .cond_jmp_greater_less => 0x8f, .cond_set_byte_greater_less => 0x9f, else => unreachable, }, .lt => return switch (tag) { .cond_jmp_greater_less => 0x8c, .cond_set_byte_greater_less => 0x9c, else => unreachable, }, .lte => return switch (tag) { .cond_jmp_greater_less => 0x8e, .cond_set_byte_greater_less => 0x9e, else => unreachable, }, .ae => return switch (tag) { .cond_jmp_above_below => 0x83, .cond_set_byte_above_below => 0x93, else => unreachable, }, .a => return switch (tag) { .cond_jmp_above_below => 0x87, .cond_set_byte_greater_less => 0x97, else => unreachable, }, .b => return switch (tag) { .cond_jmp_above_below => 0x82, .cond_set_byte_greater_less => 0x92, else => unreachable, }, .be => return switch (tag) { .cond_jmp_above_below => 0x86, .cond_set_byte_greater_less => 0x96, else => unreachable, }, .eq => return switch (tag) { .cond_jmp_eq_ne => 0x84, .cond_set_byte_eq_ne => 0x94, else => unreachable, }, .ne => return switch (tag) { .cond_jmp_eq_ne => 0x85, .cond_set_byte_eq_ne => 0x95, else => unreachable, }, } } fn mirCondJmp(print: *const Print, tag: Mir.Inst.Tag, inst: Mir.Inst.Index, w: anytype) !void { _ = w; // TODO const ops = Mir.Ops.decode(print.mir.instructions.items(.ops)[inst]); const target = print.mir.instructions.items(.data)[inst].inst; const cond = CondType.fromTagAndFlags(tag, ops.flags); const opc = getCondOpCode(tag, cond); const source = print.code.items.len; const encoder = try Encoder.init(print.code, 6); encoder.opcode_2byte(0x0f, opc); try print.relocs.append(print.bin_file.allocator, .{ .source = source, .target = target, .offset = print.code.items.len, .length = 6, }); encoder.imm32(0); } fn mirCondSetByte(print: *const Print, tag: Mir.Inst.Tag, inst: Mir.Inst.Index, w: anytype) !void { _ = w; // TODO const ops = Mir.Ops.decode(print.mir.instructions.items(.ops)[inst]); const cond = CondType.fromTagAndFlags(tag, ops.flags); const opc = getCondOpCode(tag, cond); const encoder = try Encoder.init(print.code, 4); encoder.rex(.{ .w = true, .b = ops.reg1.isExtended(), }); encoder.opcode_2byte(0x0f, opc); encoder.modRm_direct(0x0, ops.reg1.lowId()); } fn mirTest(print: *const Print, inst: Mir.Inst.Index, w: anytype) !void { _ = w; // TODO const tag = print.mir.instructions.items(.tag)[inst]; assert(tag == .@"test"); const ops = Mir.Ops.decode(print.mir.instructions.items(.ops)[inst]); switch (ops.flags) { 0b00 => blk: { if (ops.reg2 == .none) { // TEST r/m64, imm32 const imm = print.mir.instructions.items(.data)[inst].imm; if (ops.reg1.to64() == .rax) { // TODO reduce the size of the instruction if the immediate // is smaller than 32 bits const encoder = try Encoder.init(print.code, 6); encoder.rex(.{ .w = true, }); encoder.opcode_1byte(0xa9); encoder.imm32(imm); break :blk; } const opc: u8 = if (ops.reg1.size() == 8) 0xf6 else 0xf7; const encoder = try Encoder.init(print.code, 7); encoder.rex(.{ .w = true, .b = ops.reg1.isExtended(), }); encoder.opcode_1byte(opc); encoder.modRm_direct(0, ops.reg1.lowId()); encoder.imm8(@intCast(i8, imm)); break :blk; } // TEST r/m64, r64 return print.fail("TODO TEST r/m64, r64", .{}); }, else => return print.fail("TODO more TEST alternatives", .{}), } } const EncType = enum { /// OP r/m64, imm32 mi, /// OP r/m64, r64 mr, /// OP r64, r/m64 rm, }; const OpCode = struct { opc: u8, /// Only used if `EncType == .mi`. modrm_ext: u3, }; inline fn getArithOpCode(tag: Mir.Inst.Tag, enc: EncType) OpCode { switch (enc) { .mi => return switch (tag) { .adc => .{ .opc = 0x81, .modrm_ext = 0x2 }, .add => .{ .opc = 0x81, .modrm_ext = 0x0 }, .sub => .{ .opc = 0x81, .modrm_ext = 0x5 }, .xor => .{ .opc = 0x81, .modrm_ext = 0x6 }, .@"and" => .{ .opc = 0x81, .modrm_ext = 0x4 }, .@"or" => .{ .opc = 0x81, .modrm_ext = 0x1 }, .sbb => .{ .opc = 0x81, .modrm_ext = 0x3 }, .cmp => .{ .opc = 0x81, .modrm_ext = 0x7 }, .mov => .{ .opc = 0xc7, .modrm_ext = 0x0 }, else => unreachable, }, .mr => { const opc: u8 = switch (tag) { .adc => 0x11, .add => 0x01, .sub => 0x29, .xor => 0x31, .@"and" => 0x21, .@"or" => 0x09, .sbb => 0x19, .cmp => 0x39, .mov => 0x89, else => unreachable, }; return .{ .opc = opc, .modrm_ext = undefined }; }, .rm => { const opc: u8 = switch (tag) { .adc => 0x13, .add => 0x03, .sub => 0x2b, .xor => 0x33, .@"and" => 0x23, .@"or" => 0x0b, .sbb => 0x1b, .cmp => 0x3b, .mov => 0x8b, else => unreachable, }; return .{ .opc = opc, .modrm_ext = undefined }; }, } } fn mirArith(print: *const Print, tag: Mir.Inst.Tag, inst: Mir.Inst.Index, w: anytype) !void { const ops = Mir.Ops.decode(print.mir.instructions.items(.ops)[inst]); try w.writeAll(@tagName(tag)); try w.writeByte(' '); switch (ops.flags) { 0b00 => { if (ops.reg2 == .none) { const imm = print.mir.instructions.items(.data)[inst].imm; try w.print("{s}, {d}", .{ @tagName(ops.reg1), imm }); } else try w.print("{s}, {s}", .{ @tagName(ops.reg1), @tagName(ops.reg2) }); }, 0b01 => { const imm = print.mir.instructions.items(.data)[inst].imm; if (ops.reg2 == .none) { try w.print("{s}, [ds:{d}]", .{ @tagName(ops.reg1), imm }); } else { try w.print("{s}, [{s} + {d}]", .{ @tagName(ops.reg1), @tagName(ops.reg2), imm }); } }, 0b10 => { const imm = print.mir.instructions.items(.data)[inst].imm; if (ops.reg2 == .none) { try w.print("[{s} + 0], {d}", .{ @tagName(ops.reg1), imm }); } else { try w.print("[{s} + {d}], {s}", .{ @tagName(ops.reg1), imm, @tagName(ops.reg2) }); } }, 0b11 => { if (ops.reg2 == .none) { const payload = print.mir.instructions.items(.data)[inst].payload; const imm_pair = print.mir.extraData(Mir.ImmPair, payload).data; try w.print("[{s} + {d}], {d}", .{ @tagName(ops.reg1), imm_pair.dest_off, imm_pair.operand }); } try w.writeAll("TODO"); }, } try w.writeByte('\n'); } fn mirArithScaleSrc(print: *const Print, tag: Mir.Inst.Tag, inst: Mir.Inst.Index, w: anytype) !void { const ops = Mir.Ops.decode(print.mir.instructions.items(.ops)[inst]); const scale = ops.flags; // OP reg1, [reg2 + scale*rcx + imm32] const imm = print.mir.instructions.items(.data)[inst].imm; try w.print("{s} {s}, [{s} + {d}*rcx + {d}]\n", .{ @tagName(tag), @tagName(ops.reg1), @tagName(ops.reg2), scale, imm }); } fn mirArithScaleDst(print: *const Print, tag: Mir.Inst.Tag, inst: Mir.Inst.Index, w: anytype) !void { const ops = Mir.Ops.decode(print.mir.instructions.items(.ops)[inst]); const scale = ops.flags; const imm = print.mir.instructions.items(.data)[inst].imm; if (ops.reg2 == .none) { // OP [reg1 + scale*rax + 0], imm32 try w.print("{s} [{s} + {d}*rcx + 0], {d}\n", .{ @tagName(tag), @tagName(ops.reg1), scale, imm }); } // OP [reg1 + scale*rax + imm32], reg2 try w.print("{s} [{s} + {d}*rcx + {d}], {s}\n", .{ @tagName(tag), @tagName(ops.reg1), scale, imm, @tagName(ops.reg2) }); } fn mirArithScaleImm(print: *const Print, tag: Mir.Inst.Tag, inst: Mir.Inst.Index, w: anytype) !void { const ops = Mir.Ops.decode(print.mir.instructions.items(.ops)[inst]); const scale = ops.flags; const payload = print.mir.instructions.items(.data)[inst].payload; const imm_pair = print.mir.extraData(Mir.ImmPair, payload).data; try w.print("{s} [{s} + {d}*rcx + {d}], {d}\n", .{ @tagName(tag), @tagName(ops.reg1), scale, imm_pair.dest_off, imm_pair.operand }); } fn mirMovabs(print: *const Print, inst: Mir.Inst.Index, w: anytype) !void { const tag = print.mir.instructions.items(.tag)[inst]; assert(tag == .movabs); const ops = Mir.Ops.decode(print.mir.instructions.items(.ops)[inst]); const is_64 = ops.reg1.size() == 64; const imm: i128 = if (is_64) blk: { const payload = print.mir.instructions.items(.data)[inst].payload; const imm64 = print.mir.extraData(Mir.Imm64, payload).data; break :blk imm64.decode(); } else print.mir.instructions.items(.data)[inst].imm; if (ops.flags == 0b00) { // movabs reg, imm64 try w.print("movabs {s}, {d}\n", .{ @tagName(ops.reg1), imm }); } if (ops.reg1 == .none) { try w.writeAll("movabs moffs64, rax\n"); } else { // movabs rax, moffs64 try w.writeAll("movabs rax, moffs64\n"); } } fn mirIMulComplex(print: *const Print, inst: Mir.Inst.Index, w: anytype) !void { const tag = print.mir.instructions.items(.tag)[inst]; assert(tag == .imul_complex); const ops = Mir.Ops.decode(print.mir.instructions.items(.ops)[inst]); switch (ops.flags) { 0b00 => { try w.print("imul {s}, {s}\n", .{ @tagName(ops.reg1), @tagName(ops.reg2) }); }, 0b10 => { const imm = print.mir.instructions.items(.data)[inst].imm; try w.print("imul {s}, {s}, {d}\n", .{ @tagName(ops.reg1), @tagName(ops.reg2), imm }); }, else => return w.writeAll("TODO implement imul\n"), } } fn mirLea(print: *const Print, inst: Mir.Inst.Index, w: anytype) !void { const tag = print.mir.instructions.items(.tag)[inst]; assert(tag == .lea); const ops = Mir.Ops.decode(print.mir.instructions.items(.ops)[inst]); assert(ops.flags == 0b01); const imm = print.mir.instructions.items(.data)[inst].imm; try w.print("lea {s} [{s} + {d}]\n", .{ @tagName(ops.reg1), @tagName(ops.reg2), imm }); } fn mirLeaRip(print: *const Print, inst: Mir.Inst.Index, w: anytype) !void { _ = print; _ = inst; return w.writeAll("TODO lea_rip\n"); } fn mirCallExtern(print: *const Print, inst: Mir.Inst.Index, w: anytype) !void { _ = print; _ = inst; return w.writeAll("TODO call_extern"); }
src/arch/x86_64/PrintMir.zig
const build_options = @import("build_options"); const std = @import("std"); const heap = std.heap; const io = std.io; const log = std.log; const mem = std.mem; const net = std.net; const FrameHeader = @import("frame.zig").FrameHeader; const FrameFlags = @import("frame.zig").FrameFlags; const RawFrame = @import("frame.zig").RawFrame; const RawFrameReader = @import("frame.zig").RawFrameReader; const RawFrameWriter = @import("frame.zig").RawFrameWriter; const PrimitiveReader = @import("primitive/reader.zig").PrimitiveReader; const PrimitiveWriter = @import("primitive/writer.zig").PrimitiveWriter; usingnamespace @import("primitive_types.zig"); const lz4 = @import("lz4.zig"); const snappy = comptime if (build_options.with_snappy) @import("snappy.zig"); // Ordered by Opcode usingnamespace @import("frames/error.zig"); usingnamespace @import("frames/startup.zig"); usingnamespace @import("frames/ready.zig"); usingnamespace @import("frames/auth.zig"); usingnamespace @import("frames/options.zig"); usingnamespace @import("frames/supported.zig"); usingnamespace @import("frames/query.zig"); usingnamespace @import("frames/result.zig"); usingnamespace @import("frames/prepare.zig"); usingnamespace @import("frames/execute.zig"); usingnamespace @import("frames/register.zig"); usingnamespace @import("frames/event.zig"); usingnamespace @import("frames/batch.zig"); pub const Frame = union(Opcode) { Error: ErrorFrame, Startup: StartupFrame, Ready: ReadyFrame, Authenticate: AuthenticateFrame, Options: void, Supported: SupportedFrame, Query: QueryFrame, Result: ResultFrame, Prepare: PrepareFrame, Execute: ExecuteFrame, Register: void, Event: EventFrame, Batch: BatchFrame, AuthChallenge: AuthChallengeFrame, AuthResponse: AuthResponseFrame, AuthSuccess: AuthSuccessFrame, }; pub const Connection = struct { const Self = @This(); pub const InitOptions = struct { /// the protocl version to use. protocol_version: ProtocolVersion = ProtocolVersion{ .version = @as(u8, 4) }, /// The compression algorithm to use if possible. compression: ?CompressionAlgorithm = null, /// The username to use for authentication if required. username: ?[]const u8 = null, /// The password to use for authentication if required. password: ?[]const u8 = null, /// If this is provided, init will populate some information about failures. /// This will provide more detail than an error can. diags: ?*Diagnostics = null, pub const Diagnostics = struct { /// The error message returned by the Cassandra node. message: []const u8 = "", }; }; const BufferedReaderType = io.BufferedReader(4096, std.net.Stream.Reader); const BufferedWriterType = io.BufferedWriter(4096, std.net.Stream.Writer); const RawFrameReaderType = RawFrameReader(BufferedReaderType.Reader); const RawFrameWriterType = RawFrameWriter(BufferedWriterType.Writer); /// Contains the state that is negotiated with a node as part of the handshake. const NegotiatedState = struct { cql_version: CQLVersion, }; allocator: *mem.Allocator, options: InitOptions, socket: std.net.Stream, buffered_reader: BufferedReaderType, buffered_writer: BufferedWriterType, read_lock: if (std.io.is_async) std.event.Lock else void, write_lock: if (std.io.is_async) std.event.Lock else void, /// Helpers types needed to decode the CQL protocol. raw_frame_reader: RawFrameReaderType, raw_frame_writer: RawFrameWriterType, primitive_reader: PrimitiveReader, primitive_writer: PrimitiveWriter, // Negotiated with the server negotiated_state: NegotiatedState, pub fn initIp4(self: *Self, allocator: *mem.Allocator, seed_address: net.Address, options: InitOptions) !void { self.allocator = allocator; self.options = options; self.socket = try net.tcpConnectToAddress(seed_address); errdefer self.socket.close(); self.buffered_reader = BufferedReaderType{ .unbuffered_reader = self.socket.reader() }; self.buffered_writer = BufferedWriterType{ .unbuffered_writer = self.socket.writer() }; if (std.io.is_async) { self.read_lock = std.event.Lock{}; self.write_lock = std.event.Lock{}; } self.raw_frame_reader = RawFrameReaderType.init(self.buffered_reader.reader()); self.raw_frame_writer = RawFrameWriterType.init(self.buffered_writer.writer()); self.primitive_reader = PrimitiveReader.init(); var dummy_diags = InitOptions.Diagnostics{}; var diags = options.diags orelse &dummy_diags; try self.handshake(diags); } pub fn close(self: *Self) void { self.socket.close(); } fn handshake(self: *Self, diags: *InitOptions.Diagnostics) !void { // Sequence diagram to establish the connection: // // +---------+ +---------+ // | Client | | Server | // +---------+ +---------+ // | | // | OPTIONS | // |-------------------------->| // | | // | SUPPORTED | // |<--------------------------| // | | // | STARTUP | // |-------------------------->| // | | // | (READY|AUTHENTICATE) | // |<--------------------------| // | | // | AUTH_RESPONSE | // |-------------------------->| // | | var buffer: [4096]u8 = undefined; var fba = std.heap.FixedBufferAllocator.init(&buffer); // Write OPTIONS, expect SUPPORTED try self.writeFrame(&fba.allocator, .{ .opcode = .Options }); fba.reset(); switch (try self.readFrame(&fba.allocator, null)) { .Supported => |frame| self.negotiated_state.cql_version = frame.cql_versions[0], .Error => |err| { diags.message = err.message; return error.HandshakeFailed; }, else => return error.InvalidServerResponse, } fba.reset(); // Write STARTUP, expect either READY or AUTHENTICATE const startup_frame = StartupFrame{ .cql_version = self.negotiated_state.cql_version, .compression = self.options.compression, }; try self.writeFrame(&fba.allocator, .{ .opcode = .Startup, .no_compression = true, .body = startup_frame, }); switch (try self.readFrame(&fba.allocator, null)) { .Ready => return, .Authenticate => |frame| { try self.authenticate(&fba.allocator, diags, frame.authenticator); }, .Error => |err| { diags.message = err.message; return error.HandshakeFailed; }, else => return error.InvalidServerResponse, } } fn authenticate(self: *Self, allocator: *mem.Allocator, diags: *InitOptions.Diagnostics, authenticator: []const u8) !void { // TODO(vincent): handle authenticator classes // TODO(vincent): handle auth challenges if (self.options.username == null) { return error.NoUsername; } if (self.options.password == null) { return error.NoPassword; } // Write AUTH_RESPONSE { var buf: [512]u8 = undefined; const token = try std.fmt.bufPrint(&buf, "\x00{s}\x00{s}", .{ self.options.username.?, self.options.password.? }); var frame = AuthResponseFrame{ .token = token }; try self.writeFrame(allocator, .{ .opcode = .AuthResponse, .body = frame, }); } // Read either AUTH_CHALLENGE, AUTH_SUCCESS or ERROR switch (try self.readFrame(allocator, null)) { .AuthChallenge => unreachable, .AuthSuccess => return, .Error => |err| { diags.message = err.message; return error.AuthenticationFailed; }, else => return error.InvalidServerResponse, } } /// writeFrame writes a single frame to the TCP connection. /// /// A frame can be: /// * an anonymous struct with just a .opcode field (therefore no frame body). /// * an anonymous struct with a .opcode field and a .body field. /// /// If the .body field is present, it must me a type implementing either of the following write function: /// /// fn write(protocol_version: ProtocolVersion, primitive_writer: *PrimitiveWriter) !void /// fn write(primitive_writer: *PrimitiveWriter) !void /// /// Some frames don't care about the protocol version so this is why the second signature is supported. /// /// Additionally this method takes care of compression if enabled. /// /// This method is not thread safe. pub fn writeFrame(self: *Self, allocator: *mem.Allocator, frame: anytype) !void { // Lock the writer if necessary var heldWriteLock: std.event.Lock.Held = undefined; if (std.io.is_async) { heldWriteLock = self.write_lock.acquire(); } defer if (std.io.is_async) heldWriteLock.release(); // Reset primitive writer // TODO(vincent): for async we probably should do something else for the primitive writer. try self.primitive_writer.reset(allocator); defer self.primitive_writer.deinit(allocator); // Prepare the raw frame var raw_frame = RawFrame{ .header = FrameHeader{ .version = self.options.protocol_version, .flags = 0, .stream = 0, .opcode = frame.opcode, .body_len = 0, }, .body = &[_]u8{}, }; if (self.options.protocol_version.is(5)) { raw_frame.header.flags |= FrameFlags.UseBeta; } const FrameType = @TypeOf(frame); if (@hasField(FrameType, "body")) { // Encode body const TypeOfWriteFn = @TypeOf(frame.body.write); const typeInfo = @typeInfo(TypeOfWriteFn); if (typeInfo.BoundFn.args.len == 3) { try frame.body.write(self.options.protocol_version, &self.primitive_writer); } else { try frame.body.write(&self.primitive_writer); } // This is the actual bytes of the encoded body. const written = self.primitive_writer.getWritten(); // Default to using the uncompressed body. raw_frame.header.body_len = @intCast(u32, written.len); raw_frame.body = written; // Compress the body if we can use it. if (!@hasField(FrameType, "no_compression")) { if (self.options.compression) |compression| { switch (compression) { .LZ4 => { const compressed_data = try lz4.compress(allocator, written); raw_frame.header.flags |= FrameFlags.Compression; raw_frame.header.body_len = @intCast(u32, compressed_data.len); raw_frame.body = compressed_data; }, .Snappy => { comptime if (!build_options.with_snappy) return error.InvalidCompressedFrame; const compressed_data = try snappy.compress(allocator, written); raw_frame.header.flags |= FrameFlags.Compression; raw_frame.header.body_len = @intCast(u32, compressed_data.len); raw_frame.body = compressed_data; }, } } } } try self.raw_frame_writer.write(raw_frame); try self.buffered_writer.flush(); } pub const ReadFrameOptions = struct { frame_allocator: *mem.Allocator, }; pub fn readFrame(self: *Self, allocator: *mem.Allocator, options: ?ReadFrameOptions) !Frame { const raw_frame = try self.readRawFrame(allocator); defer raw_frame.deinit(allocator); self.primitive_reader.reset(raw_frame.body); var frame_allocator = if (options) |opts| opts.frame_allocator else allocator; return switch (raw_frame.header.opcode) { .Error => Frame{ .Error = try ErrorFrame.read(frame_allocator, &self.primitive_reader) }, .Startup => Frame{ .Startup = try StartupFrame.read(frame_allocator, &self.primitive_reader) }, .Ready => Frame{ .Ready = ReadyFrame{} }, .Options => Frame{ .Options = {} }, .Supported => Frame{ .Supported = try SupportedFrame.read(frame_allocator, &self.primitive_reader) }, .Result => Frame{ .Result = try ResultFrame.read(frame_allocator, self.options.protocol_version, &self.primitive_reader) }, .Register => Frame{ .Register = {} }, .Event => Frame{ .Event = try EventFrame.read(frame_allocator, &self.primitive_reader) }, .Authenticate => Frame{ .Authenticate = try AuthenticateFrame.read(frame_allocator, &self.primitive_reader) }, .AuthChallenge => Frame{ .AuthChallenge = try AuthChallengeFrame.read(frame_allocator, &self.primitive_reader) }, .AuthSuccess => Frame{ .AuthSuccess = try AuthSuccessFrame.read(frame_allocator, &self.primitive_reader) }, else => std.debug.panic("invalid read frame {}\n", .{raw_frame.header.opcode}), }; } fn readRawFrame(self: *Self, allocator: *mem.Allocator) !RawFrame { var raw_frame = try self.raw_frame_reader.read(allocator); if (raw_frame.header.flags & FrameFlags.Compression == FrameFlags.Compression) { const compression = self.options.compression orelse return error.InvalidCompressedFrame; switch (compression) { .LZ4 => { const decompressed_data = try lz4.decompress(allocator, raw_frame.body); raw_frame.body = decompressed_data; }, .Snappy => { comptime if (!build_options.with_snappy) return error.InvalidCompressedFrame; const decompressed_data = try snappy.decompress(allocator, raw_frame.body); raw_frame.body = decompressed_data; }, } } return raw_frame; } };
src/connection.zig
const std = @import("std"); const nvg = @import("nanovg"); const gui = @import("gui.zig"); const event = @import("event.zig"); const Point = @import("geometry.zig").Point; const Window = @This(); allocator: std.mem.Allocator, application: *gui.Application, id: u32, width: f32, height: f32, is_modal: bool = false, is_active: bool = true, parent: ?*gui.Window = null, children: std.ArrayList(*gui.Window), main_widget: ?*gui.Widget = null, focused_widget: ?*gui.Widget = null, hovered_widget: ?*gui.Widget = null, automatic_cursor_tracking_widget: ?*gui.Widget = null, cursorFn: ?fn (nvg) void = null, mouse_pos: Point(f32) = Point(f32).make(0, 0), close_request_context: usize = 0, onCloseRequestFn: ?fn (usize) bool = null, // true: yes, close window. false: no, don't close window. closed_context: usize = 0, onClosedFn: ?fn (usize) void = null, const Self = @This(); pub fn init(allocator: std.mem.Allocator, application: *gui.Application) !*Self { var self = try allocator.create(Self); self.* = Self{ .allocator = allocator, .application = application, .id = 0, .width = 0, .height = 0, .children = std.ArrayList(*Window).init(allocator), }; return self; } pub fn deinit(self: *Self) void { if (self.parent) |parent| { // remove reference from parent parent.removeChild(self); self.parent = null; } for (self.children.items) |child| { child.parent = null; } self.children.deinit(); self.allocator.destroy(self); } pub const CreateOptions = struct { resizable: bool = true, parent_id: ?u32 = null, }; pub fn createChildWindow(self: *Self, title: [:0]const u8, width: f32, height: f32, options: CreateOptions) !*gui.Window { const child_window = try self.application.createWindow(title, width, height, CreateOptions{ .resizable = options.resizable, .parent_id = self.id, }); child_window.parent = self; try self.children.append(child_window); return child_window; } pub fn close(self: *Self) void { self.application.requestWindowClose(self); } pub fn setMainWidget(self: *Self, widget: ?*gui.Widget) void { if (self.main_widget == widget) return; if (self.main_widget) |main_widget| { main_widget.window = null; } self.main_widget = widget; if (self.main_widget) |main_widget| { main_widget.window = self; } } pub fn setFocusedWidget(self: *Self, widget: ?*gui.Widget, source: gui.FocusSource) void { if (self.focused_widget == widget) return; if (self.focused_widget) |focused_widget| { var blur_event = event.FocusEvent{ .event = .{ .type = .Blur }, .source = source }; focused_widget.dispatchEvent(&blur_event.event); } self.focused_widget = widget; if (self.focused_widget) |focused_widget| { var focus_event = event.FocusEvent{ .event = .{ .type = .Focus }, .source = source }; focused_widget.dispatchEvent(&focus_event.event); } } fn setHoveredWidget(self: *Self, widget: ?*gui.Widget) void { if (self.hovered_widget == widget) return; if (self.hovered_widget) |hovered_widget| { var leave_event = event.Event{ .type = .Leave }; hovered_widget.dispatchEvent(&leave_event); } self.hovered_widget = widget; if (self.hovered_widget) |hovered_widget| { var enter_event = event.Event{ .type = .Enter }; hovered_widget.dispatchEvent(&enter_event); } } pub fn isBlockedByModal(self: *Self) bool { for (self.children.items) |child| { if (child.is_modal) return true; if (child.isBlockedByModal()) return true; } return false; } pub fn removeChild(self: *Self, child: *gui.Window) void { if (std.mem.indexOfScalar(*gui.Window, self.children.items, child)) |i| { _ = self.children.swapRemove(i); } } pub fn collectFocusableWidgets(self: Self, focusable_widgets: *std.ArrayList(*gui.Widget), source: event.FocusSource) !void { const main_widget = self.main_widget orelse return error.NoMainWidget; const collect_focusable_widgets = struct { fn collect(widget: *gui.Widget, list: *std.ArrayList(*gui.Widget), s: event.FocusSource) error{OutOfMemory}!void { for (widget.children.items) |child| { if (child.acceptsFocus(s)) try list.append(child); try collect(child, list, s); } } }.collect; try collect_focusable_widgets(main_widget, focusable_widgets, source); } pub fn handleEvent(self: *Self, e: *event.Event) void { if (self.isBlockedByModal()) { if (e.type != .Leave) return; } const mouse_event = @fieldParentPtr(event.MouseEvent, "event", e); const touch_event = @fieldParentPtr(event.TouchEvent, "event", e); switch (e.type) { .MouseMove, .MouseDown, .MouseUp, .MouseWheel => self.handleMouseEvent(mouse_event), .TouchPan, .TouchZoom => self.handleTouchEvent(touch_event), .KeyDown, .KeyUp, .TextInput => self.handleKeyEvent(e), .Enter => self.setHoveredWidget(self.main_widget), .Leave => self.setHoveredWidget(null), else => { if (self.main_widget) |main_widget| { main_widget.handleEvent(e); } }, } } fn handleMouseEvent(self: *Self, mouse_event: *event.MouseEvent) void { self.mouse_pos = Point(f32).make(mouse_event.x, mouse_event.y); if (self.automatic_cursor_tracking_widget) |widget| { if (mouse_event.event.type == .MouseUp and mouse_event.state == 0) { self.automatic_cursor_tracking_widget = null; } const window_relative_rect = widget.getWindowRelativeRect(); var local_event = mouse_event.*; local_event.x -= window_relative_rect.x; local_event.y -= window_relative_rect.y; widget.dispatchEvent(&local_event.event); } else if (self.main_widget) |main_widget| { const position = Point(f32).make(mouse_event.x, mouse_event.y); const result = main_widget.hitTest(position); var local_event = mouse_event.*; local_event.x = result.local_position.x; local_event.y = result.local_position.y; self.setHoveredWidget(result.widget); if (mouse_event.event.type == .MouseDown) { self.automatic_cursor_tracking_widget = result.widget; } result.widget.dispatchEvent(&local_event.event); } } fn handleTouchEvent(self: *Self, touch_event: *event.TouchEvent) void { self.mouse_pos = Point(f32).make(touch_event.x, touch_event.y); if (self.main_widget) |main_widget| { const position = Point(f32).make(touch_event.x, touch_event.y); const result = main_widget.hitTest(position); var local_event = touch_event.*; local_event.x = result.local_position.x; local_event.y = result.local_position.y; self.setHoveredWidget(result.widget); result.widget.dispatchEvent(&local_event.event); } } fn handleKeyEvent(self: Self, key_event: *event.Event) void { if (self.focused_widget) |focused_widget| { return focused_widget.dispatchEvent(key_event); } if (self.main_widget) |main_widget| { // is root -> no need to dispatch return main_widget.handleEvent(key_event); } } pub fn setSize(self: *Self, width: f32, height: f32) void { if (self.width == width and self.height == height) return; self.width = width; self.height = height; if (self.main_widget) |main_widget| { main_widget.setSize(width, height); } } pub fn setTitle(self: *Self, title: [:0]const u8) void { gui.Application.setWindowTitle(self.id, title); } pub fn setCursor(self: *Self, cursor: ?fn (nvg) void) void { gui.Application.showCursor(cursor == null); self.cursorFn = cursor; } pub fn draw(self: Self, vg: nvg) void { if (self.main_widget) |main_widget| { main_widget.draw(vg); } if (self.cursorFn) |cursor| { vg.save(); vg.translate(self.mouse_pos.x, self.mouse_pos.y); cursor(vg); vg.restore(); } }
src/gui/Window.zig
const std = @import("std"); const Cpu = @import("cpu.zig").Cpu; const Precision = @import("console.zig").Precision; pub fn Addressing(comptime precision: Precision) type { return switch (precision) { .fast => enum { accumulator, absolute, absoluteX, absoluteY, immediate, implied, indirect, indirectX, indirectY, relative, zeroPage, zeroPageX, zeroPageY, pub fn op_size(self: @This()) u2 { return switch (self) { .accumulator => 1, .absolute => 3, .absoluteX => 3, .absoluteY => 3, .immediate => 2, .implied => 1, .indirect => 3, .indirectX => 2, .indirectY => 2, .relative => 2, .zeroPage => 2, .zeroPageX => 2, .zeroPageY => 2, }; } }, .accurate => enum { special, absolute, absoluteX, absoluteY, immediate, implied, indirectX, indirectY, relative, zeroPage, zeroPageX, zeroPageY, }, }; } pub fn Instruction(comptime precision: Precision) type { switch (precision) { .fast => return struct { op: Op(.fast), addressing: Addressing(.fast), cycles: u3, var_cycles: bool = false, pub const decode = decodeFast; }, .accurate => return struct { op: Op(.accurate), addressing: Addressing(.accurate), access: Access, pub const decode = decodeAccurate; }, } } // TODO: lut? fn decodeFast(opcode: u8) Instruction(.fast) { const OpFast = Op(.fast); const AddrFast = Addressing(.fast); return switch (opcode) { 0x69 => .{ .op = OpFast.op_adc, .addressing = AddrFast.immediate, .cycles = 2 }, 0x65 => .{ .op = OpFast.op_adc, .addressing = AddrFast.zeroPage, .cycles = 3 }, 0x75 => .{ .op = OpFast.op_adc, .addressing = AddrFast.zeroPageX, .cycles = 4 }, 0x6d => .{ .op = OpFast.op_adc, .addressing = AddrFast.absolute, .cycles = 4 }, 0x7d => .{ .op = OpFast.op_adc, .addressing = AddrFast.absoluteX, .cycles = 4, .var_cycles = true }, 0x79 => .{ .op = OpFast.op_adc, .addressing = AddrFast.absoluteY, .cycles = 4, .var_cycles = true }, 0x61 => .{ .op = OpFast.op_adc, .addressing = AddrFast.indirectX, .cycles = 6 }, 0x71 => .{ .op = OpFast.op_adc, .addressing = AddrFast.indirectY, .cycles = 5, .var_cycles = true }, 0x29 => .{ .op = OpFast.op_and, .addressing = AddrFast.immediate, .cycles = 2 }, 0x25 => .{ .op = OpFast.op_and, .addressing = AddrFast.zeroPage, .cycles = 3 }, 0x35 => .{ .op = OpFast.op_and, .addressing = AddrFast.zeroPageX, .cycles = 4 }, 0x2d => .{ .op = OpFast.op_and, .addressing = AddrFast.absolute, .cycles = 4 }, 0x3d => .{ .op = OpFast.op_and, .addressing = AddrFast.absoluteX, .cycles = 4, .var_cycles = true }, 0x39 => .{ .op = OpFast.op_and, .addressing = AddrFast.absoluteY, .cycles = 4, .var_cycles = true }, 0x21 => .{ .op = OpFast.op_and, .addressing = AddrFast.indirectX, .cycles = 6 }, 0x31 => .{ .op = OpFast.op_and, .addressing = AddrFast.indirectY, .cycles = 5, .var_cycles = true }, 0x0a => .{ .op = OpFast.op_asl, .addressing = AddrFast.accumulator, .cycles = 2 }, 0x06 => .{ .op = OpFast.op_asl, .addressing = AddrFast.zeroPage, .cycles = 5 }, 0x16 => .{ .op = OpFast.op_asl, .addressing = AddrFast.zeroPageX, .cycles = 6 }, 0x0e => .{ .op = OpFast.op_asl, .addressing = AddrFast.absolute, .cycles = 6 }, 0x1e => .{ .op = OpFast.op_asl, .addressing = AddrFast.absoluteX, .cycles = 7 }, 0x10 => .{ .op = OpFast.op_bpl, .addressing = AddrFast.relative, .cycles = 2 }, 0x30 => .{ .op = OpFast.op_bmi, .addressing = AddrFast.relative, .cycles = 2 }, 0x50 => .{ .op = OpFast.op_bvc, .addressing = AddrFast.relative, .cycles = 2 }, 0x70 => .{ .op = OpFast.op_bvs, .addressing = AddrFast.relative, .cycles = 2 }, 0x90 => .{ .op = OpFast.op_bcc, .addressing = AddrFast.relative, .cycles = 2 }, 0xb0 => .{ .op = OpFast.op_bcs, .addressing = AddrFast.relative, .cycles = 2 }, 0xd0 => .{ .op = OpFast.op_bne, .addressing = AddrFast.relative, .cycles = 2 }, 0xf0 => .{ .op = OpFast.op_beq, .addressing = AddrFast.relative, .cycles = 2 }, 0x24 => .{ .op = OpFast.op_bit, .addressing = AddrFast.zeroPage, .cycles = 3 }, 0x2c => .{ .op = OpFast.op_bit, .addressing = AddrFast.absolute, .cycles = 4 }, 0x00 => .{ .op = OpFast.op_brk, .addressing = AddrFast.implied, .cycles = 7 }, 0x18 => .{ .op = OpFast.op_clc, .addressing = AddrFast.implied, .cycles = 2 }, 0xd8 => .{ .op = OpFast.op_cld, .addressing = AddrFast.implied, .cycles = 2 }, 0x58 => .{ .op = OpFast.op_cli, .addressing = AddrFast.implied, .cycles = 2 }, 0xb8 => .{ .op = OpFast.op_clv, .addressing = AddrFast.implied, .cycles = 2 }, 0xc9 => .{ .op = OpFast.op_cmp, .addressing = AddrFast.immediate, .cycles = 2 }, 0xc5 => .{ .op = OpFast.op_cmp, .addressing = AddrFast.zeroPage, .cycles = 3 }, 0xd5 => .{ .op = OpFast.op_cmp, .addressing = AddrFast.zeroPageX, .cycles = 4 }, 0xcd => .{ .op = OpFast.op_cmp, .addressing = AddrFast.absolute, .cycles = 4 }, 0xdd => .{ .op = OpFast.op_cmp, .addressing = AddrFast.absoluteX, .cycles = 4, .var_cycles = true }, 0xd9 => .{ .op = OpFast.op_cmp, .addressing = AddrFast.absoluteY, .cycles = 4, .var_cycles = true }, 0xc1 => .{ .op = OpFast.op_cmp, .addressing = AddrFast.indirectX, .cycles = 6 }, 0xd1 => .{ .op = OpFast.op_cmp, .addressing = AddrFast.indirectY, .cycles = 5, .var_cycles = true }, 0xe0 => .{ .op = OpFast.op_cpx, .addressing = AddrFast.immediate, .cycles = 2 }, 0xe4 => .{ .op = OpFast.op_cpx, .addressing = AddrFast.zeroPage, .cycles = 3 }, 0xec => .{ .op = OpFast.op_cpx, .addressing = AddrFast.absolute, .cycles = 4 }, 0xc0 => .{ .op = OpFast.op_cpy, .addressing = AddrFast.immediate, .cycles = 2 }, 0xc4 => .{ .op = OpFast.op_cpy, .addressing = AddrFast.zeroPage, .cycles = 3 }, 0xcc => .{ .op = OpFast.op_cpy, .addressing = AddrFast.absolute, .cycles = 4 }, 0xc6 => .{ .op = OpFast.op_dec, .addressing = AddrFast.zeroPage, .cycles = 5 }, 0xd6 => .{ .op = OpFast.op_dec, .addressing = AddrFast.zeroPageX, .cycles = 6 }, 0xce => .{ .op = OpFast.op_dec, .addressing = AddrFast.absolute, .cycles = 6 }, 0xde => .{ .op = OpFast.op_dec, .addressing = AddrFast.absoluteX, .cycles = 7 }, 0xca => .{ .op = OpFast.op_dex, .addressing = AddrFast.implied, .cycles = 2 }, 0x88 => .{ .op = OpFast.op_dey, .addressing = AddrFast.implied, .cycles = 2 }, 0x49 => .{ .op = OpFast.op_eor, .addressing = AddrFast.immediate, .cycles = 2 }, 0x45 => .{ .op = OpFast.op_eor, .addressing = AddrFast.zeroPage, .cycles = 3 }, 0x55 => .{ .op = OpFast.op_eor, .addressing = AddrFast.zeroPageX, .cycles = 4 }, 0x4d => .{ .op = OpFast.op_eor, .addressing = AddrFast.absolute, .cycles = 4 }, 0x5d => .{ .op = OpFast.op_eor, .addressing = AddrFast.absoluteX, .cycles = 4, .var_cycles = true }, 0x59 => .{ .op = OpFast.op_eor, .addressing = AddrFast.absoluteY, .cycles = 4, .var_cycles = true }, 0x41 => .{ .op = OpFast.op_eor, .addressing = AddrFast.indirectX, .cycles = 6 }, 0x51 => .{ .op = OpFast.op_eor, .addressing = AddrFast.indirectY, .cycles = 5, .var_cycles = true }, 0xe6 => .{ .op = OpFast.op_inc, .addressing = AddrFast.zeroPage, .cycles = 5 }, 0xf6 => .{ .op = OpFast.op_inc, .addressing = AddrFast.zeroPageX, .cycles = 6 }, 0xee => .{ .op = OpFast.op_inc, .addressing = AddrFast.absolute, .cycles = 6 }, 0xfe => .{ .op = OpFast.op_inc, .addressing = AddrFast.absoluteX, .cycles = 7 }, 0xe8 => .{ .op = OpFast.op_inx, .addressing = AddrFast.implied, .cycles = 2 }, 0xc8 => .{ .op = OpFast.op_iny, .addressing = AddrFast.implied, .cycles = 2 }, 0x4c => .{ .op = OpFast.op_jmp, .addressing = AddrFast.absolute, .cycles = 3 }, 0x6c => .{ .op = OpFast.op_jmp, .addressing = AddrFast.indirect, .cycles = 5 }, 0x20 => .{ .op = OpFast.op_jsr, .addressing = AddrFast.absolute, .cycles = 6 }, 0xa9 => .{ .op = OpFast.op_lda, .addressing = AddrFast.immediate, .cycles = 2 }, 0xa5 => .{ .op = OpFast.op_lda, .addressing = AddrFast.zeroPage, .cycles = 3 }, 0xb5 => .{ .op = OpFast.op_lda, .addressing = AddrFast.zeroPageX, .cycles = 4 }, 0xad => .{ .op = OpFast.op_lda, .addressing = AddrFast.absolute, .cycles = 4 }, 0xbd => .{ .op = OpFast.op_lda, .addressing = AddrFast.absoluteX, .cycles = 4, .var_cycles = true }, 0xb9 => .{ .op = OpFast.op_lda, .addressing = AddrFast.absoluteY, .cycles = 4, .var_cycles = true }, 0xa1 => .{ .op = OpFast.op_lda, .addressing = AddrFast.indirectX, .cycles = 6 }, 0xb1 => .{ .op = OpFast.op_lda, .addressing = AddrFast.indirectY, .cycles = 5, .var_cycles = true }, 0xa2 => .{ .op = OpFast.op_ldx, .addressing = AddrFast.immediate, .cycles = 2 }, 0xa6 => .{ .op = OpFast.op_ldx, .addressing = AddrFast.zeroPage, .cycles = 3 }, 0xb6 => .{ .op = OpFast.op_ldx, .addressing = AddrFast.zeroPageY, .cycles = 4 }, 0xae => .{ .op = OpFast.op_ldx, .addressing = AddrFast.absolute, .cycles = 4 }, 0xbe => .{ .op = OpFast.op_ldx, .addressing = AddrFast.absoluteY, .cycles = 4, .var_cycles = true }, 0xa0 => .{ .op = OpFast.op_ldy, .addressing = AddrFast.immediate, .cycles = 2 }, 0xa4 => .{ .op = OpFast.op_ldy, .addressing = AddrFast.zeroPage, .cycles = 3 }, 0xb4 => .{ .op = OpFast.op_ldy, .addressing = AddrFast.zeroPageX, .cycles = 4 }, 0xac => .{ .op = OpFast.op_ldy, .addressing = AddrFast.absolute, .cycles = 4 }, 0xbc => .{ .op = OpFast.op_ldy, .addressing = AddrFast.absoluteX, .cycles = 4, .var_cycles = true }, 0x4a => .{ .op = OpFast.op_lsr, .addressing = AddrFast.accumulator, .cycles = 2 }, 0x46 => .{ .op = OpFast.op_lsr, .addressing = AddrFast.zeroPage, .cycles = 5 }, 0x56 => .{ .op = OpFast.op_lsr, .addressing = AddrFast.zeroPageX, .cycles = 6 }, 0x4e => .{ .op = OpFast.op_lsr, .addressing = AddrFast.absolute, .cycles = 6 }, 0x5e => .{ .op = OpFast.op_lsr, .addressing = AddrFast.absoluteX, .cycles = 7 }, 0xea => .{ .op = OpFast.op_nop, .addressing = AddrFast.implied, .cycles = 2 }, 0x09 => .{ .op = OpFast.op_ora, .addressing = AddrFast.immediate, .cycles = 2 }, 0x05 => .{ .op = OpFast.op_ora, .addressing = AddrFast.zeroPage, .cycles = 3 }, 0x15 => .{ .op = OpFast.op_ora, .addressing = AddrFast.zeroPageX, .cycles = 4 }, 0x0d => .{ .op = OpFast.op_ora, .addressing = AddrFast.absolute, .cycles = 4 }, 0x1d => .{ .op = OpFast.op_ora, .addressing = AddrFast.absoluteX, .cycles = 4, .var_cycles = true }, 0x19 => .{ .op = OpFast.op_ora, .addressing = AddrFast.absoluteY, .cycles = 4, .var_cycles = true }, 0x01 => .{ .op = OpFast.op_ora, .addressing = AddrFast.indirectX, .cycles = 6 }, 0x11 => .{ .op = OpFast.op_ora, .addressing = AddrFast.indirectY, .cycles = 5, .var_cycles = true }, 0x48 => .{ .op = OpFast.op_pha, .addressing = AddrFast.implied, .cycles = 3 }, 0x08 => .{ .op = OpFast.op_php, .addressing = AddrFast.implied, .cycles = 3 }, 0x68 => .{ .op = OpFast.op_pla, .addressing = AddrFast.implied, .cycles = 4 }, 0x28 => .{ .op = OpFast.op_plp, .addressing = AddrFast.implied, .cycles = 4 }, 0x2a => .{ .op = OpFast.op_rol, .addressing = AddrFast.accumulator, .cycles = 2 }, 0x26 => .{ .op = OpFast.op_rol, .addressing = AddrFast.zeroPage, .cycles = 5 }, 0x36 => .{ .op = OpFast.op_rol, .addressing = AddrFast.zeroPageX, .cycles = 6 }, 0x2e => .{ .op = OpFast.op_rol, .addressing = AddrFast.absolute, .cycles = 6 }, 0x3e => .{ .op = OpFast.op_rol, .addressing = AddrFast.absoluteX, .cycles = 7 }, 0x6a => .{ .op = OpFast.op_ror, .addressing = AddrFast.accumulator, .cycles = 2 }, 0x66 => .{ .op = OpFast.op_ror, .addressing = AddrFast.zeroPage, .cycles = 5 }, 0x76 => .{ .op = OpFast.op_ror, .addressing = AddrFast.zeroPageX, .cycles = 6 }, 0x6e => .{ .op = OpFast.op_ror, .addressing = AddrFast.absolute, .cycles = 6 }, 0x7e => .{ .op = OpFast.op_ror, .addressing = AddrFast.absoluteX, .cycles = 7 }, 0x40 => .{ .op = OpFast.op_rti, .addressing = AddrFast.implied, .cycles = 6 }, 0x60 => .{ .op = OpFast.op_rts, .addressing = AddrFast.implied, .cycles = 6 }, 0xe9 => .{ .op = OpFast.op_sbc, .addressing = AddrFast.immediate, .cycles = 2 }, 0xe5 => .{ .op = OpFast.op_sbc, .addressing = AddrFast.zeroPage, .cycles = 3 }, 0xf5 => .{ .op = OpFast.op_sbc, .addressing = AddrFast.zeroPageX, .cycles = 4 }, 0xed => .{ .op = OpFast.op_sbc, .addressing = AddrFast.absolute, .cycles = 4 }, 0xfd => .{ .op = OpFast.op_sbc, .addressing = AddrFast.absoluteX, .cycles = 4, .var_cycles = true }, 0xf9 => .{ .op = OpFast.op_sbc, .addressing = AddrFast.absoluteY, .cycles = 4, .var_cycles = true }, 0xe1 => .{ .op = OpFast.op_sbc, .addressing = AddrFast.indirectX, .cycles = 6 }, 0xf1 => .{ .op = OpFast.op_sbc, .addressing = AddrFast.indirectY, .cycles = 5, .var_cycles = true }, 0x38 => .{ .op = OpFast.op_sec, .addressing = AddrFast.implied, .cycles = 2 }, 0xf8 => .{ .op = OpFast.op_sed, .addressing = AddrFast.implied, .cycles = 2 }, 0x78 => .{ .op = OpFast.op_sei, .addressing = AddrFast.implied, .cycles = 2 }, 0x85 => .{ .op = OpFast.op_sta, .addressing = AddrFast.zeroPage, .cycles = 3 }, 0x95 => .{ .op = OpFast.op_sta, .addressing = AddrFast.zeroPageX, .cycles = 4 }, 0x8d => .{ .op = OpFast.op_sta, .addressing = AddrFast.absolute, .cycles = 4 }, 0x9d => .{ .op = OpFast.op_sta, .addressing = AddrFast.absoluteX, .cycles = 5 }, 0x99 => .{ .op = OpFast.op_sta, .addressing = AddrFast.absoluteY, .cycles = 5 }, 0x81 => .{ .op = OpFast.op_sta, .addressing = AddrFast.indirectX, .cycles = 6 }, 0x91 => .{ .op = OpFast.op_sta, .addressing = AddrFast.indirectY, .cycles = 6 }, 0x86 => .{ .op = OpFast.op_stx, .addressing = AddrFast.zeroPage, .cycles = 3 }, 0x96 => .{ .op = OpFast.op_stx, .addressing = AddrFast.zeroPageY, .cycles = 4 }, 0x8e => .{ .op = OpFast.op_stx, .addressing = AddrFast.absolute, .cycles = 4 }, 0x84 => .{ .op = OpFast.op_sty, .addressing = AddrFast.zeroPage, .cycles = 3 }, 0x94 => .{ .op = OpFast.op_sty, .addressing = AddrFast.zeroPageX, .cycles = 4 }, 0x8c => .{ .op = OpFast.op_sty, .addressing = AddrFast.absolute, .cycles = 4 }, 0xaa => .{ .op = OpFast.op_tax, .addressing = AddrFast.implied, .cycles = 2 }, 0xa8 => .{ .op = OpFast.op_tay, .addressing = AddrFast.implied, .cycles = 2 }, 0xba => .{ .op = OpFast.op_tsx, .addressing = AddrFast.implied, .cycles = 2 }, 0x8a => .{ .op = OpFast.op_txa, .addressing = AddrFast.implied, .cycles = 2 }, 0x9a => .{ .op = OpFast.op_txs, .addressing = AddrFast.implied, .cycles = 2 }, 0x98 => .{ .op = OpFast.op_tya, .addressing = AddrFast.implied, .cycles = 2 }, else => .{ .op = OpFast.op_ill, .addressing = AddrFast.implied, .cycles = 0 }, }; } const op_lut = [256]Op(.accurate){ .op_brk, .op_ora, .op_kil, .op_slo, .op_nop, .op_ora, .op_asl, .op_slo, .op_php, .op_ora, .op_asl, .op_anc, .op_nop, .op_ora, .op_asl, .op_slo, .op_bpl, .op_ora, .op_kil, .op_slo, .op_nop, .op_ora, .op_asl, .op_slo, .op_clc, .op_ora, .op_nop, .op_slo, .op_nop, .op_ora, .op_asl, .op_slo, .op_jsr, .op_and, .op_kil, .op_rla, .op_bit, .op_and, .op_rol, .op_rla, .op_plp, .op_and, .op_rol, .op_anc, .op_bit, .op_and, .op_rol, .op_rla, .op_bmi, .op_and, .op_kil, .op_rla, .op_nop, .op_and, .op_rol, .op_rla, .op_sec, .op_and, .op_nop, .op_rla, .op_nop, .op_and, .op_rol, .op_rla, .op_rti, .op_eor, .op_kil, .op_sre, .op_nop, .op_eor, .op_lsr, .op_sre, .op_pha, .op_eor, .op_lsr, .op_alr, .op_jmp, .op_eor, .op_lsr, .op_sre, .op_bvc, .op_eor, .op_kil, .op_sre, .op_nop, .op_eor, .op_lsr, .op_sre, .op_cli, .op_eor, .op_nop, .op_sre, .op_nop, .op_eor, .op_lsr, .op_sre, .op_rts, .op_adc, .op_kil, .op_rra, .op_nop, .op_adc, .op_ror, .op_rra, .op_pla, .op_adc, .op_ror, .op_arr, .op_jmp, .op_adc, .op_ror, .op_rra, .op_bvs, .op_adc, .op_kil, .op_rra, .op_nop, .op_adc, .op_ror, .op_rra, .op_sei, .op_adc, .op_nop, .op_rra, .op_nop, .op_adc, .op_ror, .op_rra, .op_nop, .op_sta, .op_nop, .op_sax, .op_sty, .op_sta, .op_stx, .op_sax, .op_dey, .op_nop, .op_txa, .op_xaa, .op_sty, .op_sta, .op_stx, .op_sax, .op_bcc, .op_sta, .op_kil, .op_ahx, .op_sty, .op_sta, .op_stx, .op_sax, .op_tya, .op_sta, .op_txs, .op_tas, .op_shy, .op_sta, .op_shx, .op_ahx, .op_ldy, .op_lda, .op_ldx, .op_lax, .op_ldy, .op_lda, .op_ldx, .op_lax, .op_tay, .op_lda, .op_tax, .op_lax, .op_ldy, .op_lda, .op_ldx, .op_lax, .op_bcs, .op_lda, .op_kil, .op_lax, .op_ldy, .op_lda, .op_ldx, .op_lax, .op_clv, .op_lda, .op_tsx, .op_las, .op_ldy, .op_lda, .op_ldx, .op_lax, .op_cpy, .op_cmp, .op_nop, .op_dcp, .op_cpy, .op_cmp, .op_dec, .op_dcp, .op_iny, .op_cmp, .op_dex, .op_axs, .op_cpy, .op_cmp, .op_dec, .op_dcp, .op_bne, .op_cmp, .op_kil, .op_dcp, .op_nop, .op_cmp, .op_dec, .op_dcp, .op_cld, .op_cmp, .op_nop, .op_dcp, .op_nop, .op_cmp, .op_dec, .op_dcp, .op_cpx, .op_sbc, .op_nop, .op_isc, .op_cpx, .op_sbc, .op_inc, .op_isc, .op_inx, .op_sbc, .op_nop, .op_sbc, .op_cpx, .op_sbc, .op_inc, .op_isc, .op_beq, .op_sbc, .op_kil, .op_isc, .op_nop, .op_sbc, .op_inc, .op_isc, .op_sed, .op_sbc, .op_nop, .op_isc, .op_nop, .op_sbc, .op_inc, .op_isc, }; const addr_lut = blk: { const intToEnum = [12]Addressing(.accurate){ .special, // = 0 .absolute, // = 1 .absoluteX, // = 2 .absoluteY, // = 3 .immediate, // = 4 .implied, // = 5 .indirectX, // = 6 .indirectY, // = 7 .relative, // = 8 .zeroPage, // = 9 .zeroPageX, // = 10 .zeroPageY, // = 11 }; const numbered = [256]comptime_int{ 0, 6, 5, 6, 9, 9, 9, 9, 0, 4, 5, 4, 1, 1, 1, 1, 8, 7, 5, 7, 10, 10, 10, 10, 5, 3, 5, 3, 2, 2, 2, 2, 0, 6, 5, 6, 9, 9, 9, 9, 0, 4, 5, 4, 1, 1, 1, 1, 8, 7, 5, 7, 10, 10, 10, 10, 5, 3, 5, 3, 2, 2, 2, 2, 0, 6, 5, 6, 9, 9, 9, 9, 0, 4, 5, 4, 0, 1, 1, 1, 8, 7, 5, 7, 10, 10, 10, 10, 5, 3, 5, 3, 2, 2, 2, 2, 0, 6, 5, 6, 9, 9, 9, 9, 0, 4, 5, 4, 0, 1, 1, 1, 8, 7, 5, 7, 10, 10, 10, 10, 5, 3, 5, 3, 2, 2, 2, 2, 4, 6, 4, 6, 9, 9, 9, 9, 5, 4, 5, 4, 1, 1, 1, 1, 8, 7, 5, 7, 10, 10, 11, 11, 5, 3, 5, 3, 2, 2, 3, 3, 4, 6, 4, 6, 9, 9, 9, 9, 5, 4, 5, 4, 1, 1, 1, 1, 8, 7, 5, 7, 10, 10, 11, 11, 5, 3, 5, 3, 2, 2, 3, 3, 4, 6, 4, 6, 9, 9, 9, 9, 5, 4, 5, 4, 1, 1, 1, 1, 8, 7, 5, 7, 10, 10, 10, 10, 5, 3, 5, 3, 2, 2, 2, 2, 4, 6, 4, 6, 9, 9, 9, 9, 5, 4, 5, 4, 1, 1, 1, 1, 8, 7, 5, 7, 10, 10, 10, 10, 5, 3, 5, 3, 2, 2, 2, 2, }; var result = [1]Addressing(.accurate){undefined} ** 256; for (numbered) |n, i| { result[i] = intToEnum[n]; } break :blk result; }; /// Most instructions fall into the category of /// read only, read-modify-write, or read-write pub const Access = enum { special, read, rmw, write, }; const access_lut = blk: { @setEvalBranchQuota(2000); var result = [1]Access{undefined} ** 256; for (result) |*r, i| { const access = switch (addr_lut[i]) { .special => .special, .implied, .immediate, .relative => .read, else => switch (op_lut[i]) { .op_jmp => .special, .op_lda, .op_ldx, .op_ldy, .op_eor, .op_and, .op_ora, .op_adc => .read, .op_sbc, .op_cmp, .op_cpx, .op_cpy, .op_bit, .op_lax, .op_nop => .read, .op_las, .op_tas => .read, .op_asl, .op_lsr, .op_rol, .op_ror, .op_inc, .op_dec, .op_slo => .rmw, .op_sre, .op_rla, .op_rra, .op_isc, .op_dcp => .rmw, .op_sta, .op_stx, .op_sty, .op_sax, .op_ahx, .op_shx, .op_shy => .write, else => @compileError("Haven't implemented op " ++ opToString(op_lut[i])), }, }; r.* = access; } break :blk result; }; fn decodeAccurate(opcode: u8) Instruction(.accurate) { return Instruction(.accurate){ .op = op_lut[opcode], .addressing = addr_lut[opcode], .access = access_lut[opcode], }; } /// Merge T2 fields into T1 /// Surely there must be a stdlib function for this? fn MergedEnum(comptime T1: type, comptime T2: type) type { const type_info1 = @typeInfo(T1); const type_info2 = @typeInfo(T2); const total_fields = type_info1.Enum.fields.len + type_info2.Enum.fields.len; var fields = [1]std.builtin.TypeInfo.EnumField{undefined} ** total_fields; var i: usize = 0; for (type_info1.Enum.fields) |field| { fields[i] = .{ .name = field.name, .value = i }; i += 1; } for (type_info2.Enum.fields) |field| { fields[i] = .{ .name = field.name, .value = i }; i += 1; } const bits = std.math.log2_int_ceil(usize, total_fields); return @Type(.{ .Enum = .{ .layout = .Auto, .tag_type = @Type(.{ .Int = .{ .signedness = .unsigned, .bits = bits } }), .fields = fields[0..], .decls = ([0]std.builtin.TypeInfo.Declaration{})[0..], .is_exhaustive = true, } }); } pub fn opToString(op: anytype) []const u8 { const enum_strs = comptime blk: { const enum_fields = @typeInfo(@TypeOf(op)).Enum.fields; var arr = [_]([3]u8){undefined} ** enum_fields.len; for (arr) |*idx, i| { _ = std.ascii.upperString(idx[0..], enum_fields[i].name[3..]); } break :blk arr; }; return enum_strs[@enumToInt(op)][0..]; } pub fn Op(comptime precision: Precision) type { const Ill = enum { op_ill, }; // zig fmt: off const Documented = enum { op_adc, op_and, op_asl, op_bpl, op_bmi, op_bvc, op_bvs, op_bcc, op_bcs, op_bne, op_beq, op_bit, op_brk, op_clc, op_cld, op_cli, op_clv, op_cmp, op_cpx, op_cpy, op_dec, op_dex, op_dey, op_eor, op_inc, op_inx, op_iny, op_jmp, op_jsr, op_lda, op_ldx, op_ldy, op_lsr, op_nop, op_ora, op_pha, op_php, op_pla, op_plp, op_rol, op_ror, op_rti, op_rts, op_sbc, op_sec, op_sed, op_sei, op_sta, op_stx, op_sty, op_tax, op_tay, op_tsx, op_txa, op_txs, op_tya, }; // zig fmt: on const Undocumented = enum { /// SAH, SHA op_ahx, /// ASR op_alr, /// AAC op_anc, op_arr, /// SBX op_axs, /// DCM op_dcp, /// INS, ISB op_isc, op_kil, /// LAE, LAR, AST op_las, op_lax, op_rla, op_rra, /// AAX, AXS op_sax, /// SXA, SXH, XAS op_shx, op_shy, /// ASO op_slo, /// LSE op_sre, /// SHS, SSH, XAS op_tas, /// ANE, AXA op_xaa, }; switch (precision) { .fast => return MergedEnum(Ill, Documented), .accurate => return MergedEnum(Documented, Undocumented), } }
src/instruction.zig
const std = @import("std"); const string = []const u8; const input = @embedFile("../input/day12.txt"); const List = std.ArrayList(string); const Map = std.StringHashMap(List); pub fn main() !void { // // part 1 { var iter = std.mem.split(u8, input, "\n"); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const alloc = &arena.allocator; var paths = Map.init(alloc); defer paths.deinit(); while (iter.next()) |line| { if (line.len == 0) continue; const index = std.mem.indexOfScalar(u8, line, '-').?; const left = line[0..index]; const right = line[index + 1 ..]; try addPath(alloc, &paths, left, right); try addPath(alloc, &paths, right, left); } const count = try allPathsFrom(alloc, &paths, "start", null, null); std.debug.print("{d}\n", .{count}); } // part 2 { var iter = std.mem.split(u8, input, "\n"); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const alloc = &arena.allocator; var paths = Map.init(alloc); defer paths.deinit(); while (iter.next()) |line| { if (line.len == 0) continue; const index = std.mem.indexOfScalar(u8, line, '-').?; const left = line[0..index]; const right = line[index + 1 ..]; try addPath(alloc, &paths, left, right); try addPath(alloc, &paths, right, left); } var small_caves = List.init(alloc); defer small_caves.deinit(); var iter2 = paths.keyIterator(); while (iter2.next()) |k| { if (std.ascii.isUpper(k.*[0])) continue; // skip big caves if (std.mem.eql(u8, k.*, "start")) continue; if (std.mem.eql(u8, k.*, "end")) continue; try small_caves.append(k.*); } var count: u32 = 0; count += try allPathsFrom(alloc, &paths, "start", null, null); for (small_caves.items) |item| { count += try allPathsFrom(alloc, &paths, "start", null, item); } std.debug.print("{d}\n", .{count}); } } fn addPath(alloc: *std.mem.Allocator, paths: *Map, from: string, to: string) !void { if (paths.getEntry(from)) |entry| { try entry.value_ptr.append(to); } else { var list = try alloc.create(List); list.* = List.init(alloc); try list.append(to); try paths.put(from, list.*); } } fn allPathsFrom(alloc: *std.mem.Allocator, paths: *Map, start: string, visited: ?[]const string, can_visit_again: ?string) std.mem.Allocator.Error!u32 { if (visited) |_| { if (std.mem.eql(u8, start, "end")) { if (can_visit_again) |_| { return @boolToInt(itemCount(visited.?, can_visit_again.?) > 1); } return 1; } var count: u32 = 0; const available = paths.get(start).?; for (available.items) |new_node| { if (std.ascii.isLower(new_node[0])) { // small cave var allowed: u32 = 1; if (can_visit_again) |_| { if (std.mem.eql(u8, new_node, can_visit_again.?)) { allowed += 1; } } if (itemCount(visited.?, new_node) >= allowed) { // visited before continue; // skip } } var list = List.init(alloc); defer list.deinit(); try list.appendSlice(visited.?); try list.append(new_node); count += try allPathsFrom(alloc, paths, new_node, list.items, can_visit_again); } return count; } return try allPathsFrom(alloc, paths, start, &[_]string{start}, can_visit_again); } fn itemCount(haystack: []const string, needle: string) u32 { var count: u32 = 0; for (haystack) |item| { if (std.mem.eql(u8, item, needle)) { count += 1; } } return count; }
src/day12.zig
const std = @import("std"); const os = std.os; const Buffer = @import("Buffer.zig"); const WireConnection = @This(); socket: std.net.Stream, in: Buffer, out: Buffer, pub fn init(socket: std.net.Stream) WireConnection { return .{ .socket = socket, .in = Buffer.init(), .out = Buffer.init(), }; } pub fn read(conn: *WireConnection) !void { if (conn.in.bytes.writableLength() == 0) return error.BufferFull; const write_slices = conn.in.bytes.writableSlices(); // TODO: next line should be const not var var vecs = [2]os.iovec{ .{ .iov_base = write_slices[0].ptr, .iov_len = write_slices[0].len }, .{ .iov_base = write_slices[1].ptr, .iov_len = write_slices[1].len }, }; const vec_slice = if (write_slices[1].len == 0) vecs[0..1] else vecs[0..2]; var msghdr = std.os.msghdr{ .name = null, .namelen = 0, .iov = vec_slice.ptr, .iovlen = @intCast(i32, vec_slice.len), .control = null, .controllen = 0, .flags = 0, }; switch (try recvmsg(conn.socket.handle, &msghdr, std.os.MSG.DONTWAIT | std.os.MSG.CMSG_CLOEXEC)) { 0 => return error.Disconnected, else => |n| { conn.in.bytes.head +%= @intCast(u12, n); }, } } pub fn flush(conn: *WireConnection) !void { if (conn.out.bytes.readableLength() == 0) return; const read_slices = conn.out.bytes.readableSlices(); // TODO: next line should be const not var var vecs: [2]os.iovec_const = .{ .{ .iov_base = read_slices[0].ptr, .iov_len = read_slices[0].len }, .{ .iov_base = read_slices[1].ptr, .iov_len = read_slices[1].len }, }; const vec_slice = if (read_slices[1].len == 0) vecs[0..1] else vecs[0..2]; const msghdr = std.os.msghdr_const{ .name = null, .namelen = 0, .iov = vec_slice.ptr, .iovlen = @intCast(i32, vec_slice.len), .control = null, .controllen = 0, .flags = 0, }; switch (try std.os.sendmsg(conn.socket.handle, msghdr, std.os.MSG.DONTWAIT | std.os.MSG.CMSG_CLOEXEC)) { 0 => return error.Disconnected, else => |n| { conn.out.bytes.tail +%= @intCast(u12, n); }, } } test "WireConnection" { std.testing.refAllDecls(WireConnection); } // TODO: this should be upstream (with windows support and errors) fn recvmsg(sockfd: std.os.socket_t, msg: *std.os.msghdr, flags: u32) !usize { while (true) { const rc = std.os.system.recvmsg(sockfd, @ptrCast(*std.x.os.Socket.Message, msg), @intCast(c_int, flags)); return switch (std.os.errno(rc)) { .SUCCESS => return @intCast(usize, rc), .AGAIN => continue, else => |err| return std.os.unexpectedErrno(err), }; } }
src/common/WireConnection.zig
const std = @import("std"); const expect = std.testing.expect; const test_allocator = std.testing.allocator; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = &gpa.allocator; var file = try std.fs.cwd().openFile("input.txt", .{}); defer file.close(); const contents = try file.reader().readAllAlloc(allocator, 409600); defer allocator.free(contents); var values = try parseInput(allocator, contents); defer allocator.free(values); const stdout = std.io.getStdOut().writer(); const part1 = findTwo(&values); try stdout.print("Part 1: {d}\n", .{part1}); const part2 = findThree(&values); try stdout.print("Part 2: {d}\n", .{part2}); } fn parseInput(allocator: *std.mem.Allocator, str: []const u8) ![]const u64 { var nums = std.ArrayList(u64).init(allocator); defer nums.deinit(); var iter = std.mem.split(u8, str, "\n"); while (iter.next()) |str_value| { std.log.debug("line: {s}", .{str_value}); const value = std.fmt.parseInt(u64, str_value, 10) catch |err| { std.log.debug("error: {}", .{err}); continue; }; try nums.append(value); } return nums.toOwnedSlice(); } fn findTwo(values: *[]const u64) u64 { for (values.*) |v1, idx1| { for (values.*) |v2, idx2| { if (idx1 == idx2) continue; if (2020 == (v1 + v2)) { return (v1 * v2); } } } unreachable; } fn findThree(values: *[]const u64) u64 { for (values.*) |v1, idx1| { for (values.*) |v2, idx2| { if (idx1 == idx2) continue; for (values.*) |v3, idx3| { if (idx2 == idx3) continue; if (2020 == (v1 + v2 + v3)) { return (v1 * v2 * v3); } } } } unreachable; } test "day1" { const test_input = \\1721 \\979 \\366 \\299 \\675 \\1456 ; var values = try parseInput(test_allocator, test_input); defer test_allocator.free(values); const test_values = [_]u64{ 1721, 979, 366, 299, 675, 1456 }; try expect(std.mem.eql(u64, &test_values, values)); try expect(514579 == findTwo(&values)); try expect(241861950 == findThree(&values)); }
day01/src/main.zig
const std = @import("std"); const assert = std.debug.assert; const builtin = std.builtin; const crypto = std.crypto; const mem = std.mem; const StringifyOptions = std.json.StringifyOptions; pub const config = @import("config.zig"); pub const Account = packed struct { id: u128, custom: u128, flags: AccountFlags, unit: u64, debit_reserved: u64, debit_accepted: u64, credit_reserved: u64, credit_accepted: u64, debit_reserved_limit: u64, debit_accepted_limit: u64, credit_reserved_limit: u64, credit_accepted_limit: u64, padding: u64 = 0, timestamp: u64 = 0, pub fn exceeds(balance: u64, amount: u64, limit: u64) bool { return limit > 0 and balance + amount > limit; } pub fn exceeds_debit_reserved_limit(self: *const Account, amount: u64) bool { return Account.exceeds(self.debit_reserved, amount, self.debit_reserved_limit); } pub fn exceeds_debit_accepted_limit(self: *const Account, amount: u64) bool { return Account.exceeds(self.debit_accepted, amount, self.debit_accepted_limit); } pub fn exceeds_credit_reserved_limit(self: *const Account, amount: u64) bool { return Account.exceeds(self.credit_reserved, amount, self.credit_reserved_limit); } pub fn exceeds_credit_accepted_limit(self: *const Account, amount: u64) bool { return Account.exceeds(self.credit_accepted, amount, self.credit_accepted_limit); } pub fn jsonStringify(self: Account, options: StringifyOptions, writer: anytype) !void { try writer.writeAll("{"); try std.fmt.format(writer, "\"id\":{},", .{self.id}); try std.fmt.format(writer, "\"custom\":\"{x:0>32}\",", .{self.custom}); try writer.writeAll("\"flags\":"); try std.json.stringify(self.flags, .{}, writer); try writer.writeAll(","); try std.fmt.format(writer, "\"unit\":{},", .{self.unit}); try std.fmt.format(writer, "\"debit_reserved\":{},", .{self.debit_reserved}); try std.fmt.format(writer, "\"debit_accepted\":{},", .{self.debit_accepted}); try std.fmt.format(writer, "\"credit_reserved\":{},", .{self.credit_reserved}); try std.fmt.format(writer, "\"credit_accepted\":{},", .{self.credit_accepted}); try std.fmt.format(writer, "\"debit_reserved_limit\":{},", .{self.debit_reserved_limit}); try std.fmt.format(writer, "\"debit_accepted_limit\":{},", .{self.debit_accepted_limit}); try std.fmt.format(writer, "\"credit_reserved_limit\":{},", .{self.credit_reserved_limit}); try std.fmt.format(writer, "\"credit_accepted_limit\":{},", .{self.credit_accepted_limit}); try std.fmt.format(writer, "\"timestamp\":\"{}\"", .{self.timestamp}); try writer.writeAll("}"); } }; pub const AccountFlags = packed struct { padding: u64 = 0, pub fn jsonStringify(self: AccountFlags, options: StringifyOptions, writer: anytype) !void { try writer.writeAll("{}"); } }; pub const Transfer = packed struct { id: u128, debit_account_id: u128, credit_account_id: u128, custom_1: u128, custom_2: u128, custom_3: u128, flags: TransferFlags, amount: u64, timeout: u64, timestamp: u64 = 0, pub fn jsonStringify(self: Transfer, options: StringifyOptions, writer: anytype) !void { try writer.writeAll("{"); try std.fmt.format(writer, "\"id\":{},", .{self.id}); try std.fmt.format(writer, "\"debit_account_id\":{},", .{self.debit_account_id}); try std.fmt.format(writer, "\"credit_account_id\":{},", .{self.credit_account_id}); try std.fmt.format(writer, "\"custom_1\":\"{x:0>32}\",", .{self.custom_1}); try std.fmt.format(writer, "\"custom_2\":\"{x:0>32}\",", .{self.custom_2}); try std.fmt.format(writer, "\"custom_3\":\"{x:0>32}\",", .{self.custom_3}); try writer.writeAll("\"flags\":"); try std.json.stringify(self.flags, .{}, writer); try writer.writeAll(","); try std.fmt.format(writer, "\"amount\":{},", .{self.amount}); try std.fmt.format(writer, "\"timeout\":{},", .{self.timeout}); try std.fmt.format(writer, "\"timestamp\":{}", .{self.timestamp}); try writer.writeAll("}"); } }; pub const TransferFlags = packed struct { accept: bool = false, reject: bool = false, auto_commit: bool = false, condition: bool = false, padding: u60 = 0, pub fn jsonStringify(self: TransferFlags, options: StringifyOptions, writer: anytype) !void { try writer.writeAll("{"); try std.fmt.format(writer, "\"accept\":{},", .{self.accept}); try std.fmt.format(writer, "\"reject\":{},", .{self.reject}); try std.fmt.format(writer, "\"auto_commit\":{},", .{self.auto_commit}); try std.fmt.format(writer, "\"condition\":{}", .{self.condition}); try writer.writeAll("}"); } }; pub const Commit = packed struct { id: u128, custom_1: u128, custom_2: u128, custom_3: u128, flags: CommitFlags, timestamp: u64 = 0, pub fn jsonStringify(self: Commit, options: StringifyOptions, writer: anytype) !void { try writer.writeAll("{"); try std.fmt.format(writer, "\"id\":{},", .{self.id}); try std.fmt.format(writer, "\"custom_1\":{},", .{self.custom_1}); try std.fmt.format(writer, "\"custom_2\":{},", .{self.custom_2}); try std.fmt.format(writer, "\"custom_3\":{},", .{self.custom_3}); try writer.writeAll("\"flags\":"); try std.json.stringify(self.flags, .{}, writer); try writer.writeAll(","); try std.fmt.format(writer, "\"timestamp\":{}", .{self.timestamp}); try writer.writeAll("}"); } }; pub const CommitFlags = packed struct { accept: bool = false, reject: bool = false, preimage: bool = false, padding: u61 = 0, pub fn jsonStringify(self: CommitFlags, options: StringifyOptions, writer: anytype) !void { try writer.writeAll("{"); try std.fmt.format(writer, "\"accept\":{},", .{self.accept}); try std.fmt.format(writer, "\"reject\":{},", .{self.reject}); try std.fmt.format(writer, "\"preimage\":{}", .{self.preimage}); try writer.writeAll("}"); } }; pub const CreateAccountResult = packed enum(u32) { ok, exists, exists_with_different_unit, exists_with_different_limits, exists_with_different_custom_field, exists_with_different_flags, reserved_field_custom, reserved_field_padding, reserved_field_timestamp, reserved_flag_padding, exceeds_debit_reserved_limit, exceeds_debit_accepted_limit, exceeds_credit_reserved_limit, exceeds_credit_accepted_limit, debit_reserved_limit_exceeds_debit_accepted_limit, credit_reserved_limit_exceeds_credit_accepted_limit, }; pub const CreateTransferResult = packed enum(u32) { ok, exists, exists_with_different_debit_account_id, exists_with_different_credit_account_id, exists_with_different_custom_fields, exists_with_different_amount, exists_with_different_timeout, exists_with_different_flags, exists_and_already_committed_and_accepted, exists_and_already_committed_and_rejected, reserved_field_custom, reserved_field_timestamp, reserved_flag_padding, reserved_flag_accept, reserved_flag_reject, debit_account_not_found, credit_account_not_found, accounts_are_the_same, accounts_have_different_units, amount_is_zero, exceeds_debit_reserved_limit, exceeds_debit_accepted_limit, exceeds_credit_reserved_limit, exceeds_credit_accepted_limit, auto_commit_must_accept, auto_commit_cannot_timeout, }; pub const CommitTransferResult = packed enum(u32) { ok, reserved_field_custom, reserved_field_timestamp, reserved_flag_padding, commit_must_accept_or_reject, commit_cannot_accept_and_reject, transfer_not_found, transfer_expired, already_auto_committed, already_committed, already_committed_but_accepted, already_committed_but_rejected, debit_account_not_found, credit_account_not_found, debit_amount_was_not_reserved, credit_amount_was_not_reserved, exceeds_debit_accepted_limit, exceeds_credit_accepted_limit, condition_requires_preimage, preimage_requires_condition, preimage_invalid, }; pub const CreateAccountResults = packed struct { index: u32, result: CreateAccountResult, pub fn jsonStringify( self: CreateAccountResults, options: StringifyOptions, writer: anytype, ) !void { try writer.writeAll("{"); try std.fmt.format(writer, "\"index\":{},", .{self.index}); try std.fmt.format(writer, "\"result\":\"{}\"", .{@tagName(self.result)}); try writer.writeAll("}"); } }; pub const CreateTransferResults = packed struct { index: u32, result: CreateTransferResult, pub fn jsonStringify( self: CreateTransferResults, options: StringifyOptions, writer: anytype, ) !void { try writer.writeAll("{"); try std.fmt.format(writer, "\"index\":{},", .{self.index}); try std.fmt.format(writer, "\"result\":\"{}\"", .{@tagName(self.result)}); try writer.writeAll("}"); } }; pub const CommitTransferResults = packed struct { index: u32, result: CommitTransferResult, pub fn jsonStringify( self: CommitTransferResults, options: StringifyOptions, writer: anytype, ) !void { try writer.writeAll("{"); try std.fmt.format(writer, "\"index\":{},", .{self.index}); try std.fmt.format(writer, "\"result\":\"{}\"", .{@tagName(self.result)}); try writer.writeAll("}"); } }; comptime { if (builtin.os.tag != .linux) @compileError("linux required for io_uring"); // We require little-endian architectures everywhere for efficient network deserialization: if (builtin.endian != builtin.Endian.Little) @compileError("big-endian systems not supported"); } const testing = std.testing; test "data structure sizes" { testing.expectEqual(@as(usize, 8), @sizeOf(AccountFlags)); testing.expectEqual(@as(usize, 128), @sizeOf(Account)); testing.expectEqual(@as(usize, 8), @sizeOf(TransferFlags)); testing.expectEqual(@as(usize, 128), @sizeOf(Transfer)); testing.expectEqual(@as(usize, 8), @sizeOf(CommitFlags)); testing.expectEqual(@as(usize, 80), @sizeOf(Commit)); testing.expectEqual(@as(usize, 8), @sizeOf(CreateAccountResults)); testing.expectEqual(@as(usize, 8), @sizeOf(CreateTransferResults)); testing.expectEqual(@as(usize, 8), @sizeOf(CommitTransferResults)); }
src/tigerbeetle.zig
const std = @import("std"); // dross-zig const Vector2 = @import("../core/vector2.zig").Vector2; const TextureRegion = @import("../renderer/texture_region.zig").TextureRegion; const Frame2d = @import("frame_2d.zig").Frame2d; const Animation2d = @import("animation_2d.zig").Animation2d; const Renderer = @import("renderer.zig").Renderer; const Math = @import("../math/math.zig").Math; // ----------------------------------------- // - Animator2d - // ----------------------------------------- /// Animation2d bundles individual Frame2d instances and /// controls the flow of them. pub const Animator2d = struct { /// Cache for the animations animations: std.StringHashMap(*Animation2d) = undefined, /// The current animation current_animation: ?*Animation2d = undefined, /// The time when the frame began frame_timer: f32 = 0.0, /// The playback speed of the animation playback_speed: f32 = 1.0, /// If the animator is currently playing animation_playing: bool = false, const Self = @This(); /// Allocates and builds a new Animation2d instance. /// Comments: The caller will own the allocated memory. pub fn new(allocator: *std.mem.Allocator) !*Self { var self = try allocator.create(Animator2d); self.animations = std.StringHashMap(*Animation2d).init(allocator); self.current_animation = null; self.frame_timer = 0.0; self.playback_speed = 1.0; self.animation_playing = false; return self; } /// Cleans up and de-allocates the Animation2d. pub fn free(allocator: *std.mem.Allocator, self: *Self) void { var iter = self.animations.iterator(); while (iter.next()) |entry_animation| { Animation2d.free(allocator, entry_animation.value); } self.animations.deinit(); allocator.destroy(self); } /// Update logic pub fn update(self: *Self, delta: f32) void { if (!self.animation_playing) return; const frame_duration = self.current_animation.?.frame().duration(); if (self.frame_timer >= frame_duration) { // Go to next frame const end_of_animation = self.current_animation.?.next(); if (end_of_animation) { self.current_animation.?.onAnimationEnd(); } if (!self.current_animation.?.loop()) { self.stop(); } self.reset(); } else { self.frame_timer += delta; } } /// Appends a new Animation to the Animator2d's animation list. /// Comments: Ownership of the Animation2d is transferred to the /// Animator2d. pub fn addAnimation(self: *Self, new_animation: *Animation2d) !void { // NOTE(devon): May be an issue with lifetime here try self.animations.put(new_animation.name(), new_animation); } /// Begins the animation. If `force_restart` is true, then /// the animation will restart from the beginning if it is /// already playing. pub fn play(self: *Self, animation_name: []const u8, force_restart: bool) void { if (self.animation_playing and !std.mem.eql(u8, animation_name, self.current_animation.?.name())) { self.current_animation.?.stop(); self.current_animation.?.reset(); } self.current_animation = self.animations.get(animation_name) orelse @panic("[Animator2D]: Requested animation does not exist!"); self.current_animation.?.play(force_restart); self.animation_playing = true; } /// Stops the animation from playing, maintaining the current /// frame. pub fn stop(self: *Self) void { if (self.current_animation == undefined) return; self.current_animation.?.stop(); self.animation_playing = false; } /// Resets fn reset(self: *Self) void { self.frame_timer = 0.0; } /// Returns if the Animation2d is currently playing pub fn playing(self: *Self) bool { return self.animation_playing; } /// Returns the current Animation2d pub fn animation(self: *Self) ?*Animation2d { return self.current_animation; } };
src/animation/animator_2d.zig
const std = @import("std"); const unicode = @import("unicode"); const mem = std.mem; const Allocator = mem.Allocator; const ArrayList = std.ArrayList; pub const FOLD_CASE: u16 = 1; // case-insensitive match pub const LITERAL: u16 = 2; // treat pattern as literal string pub const CLASS_NL: u16 = 4; // allow character classes like [^a-z] and [[:space:]] to match newline pub const DOT_NL: u16 = 8; // allow . to match newline pub const ONE_LINE: u16 = 16; // treat ^ and $ as only matching at beginning and end of text pub const NON_GREEDY: u16 = 32; // make repetition operators default to non-greedy pub const PERLX: u16 = 64; // allow Perl extensions pub const UNICODE_GROUPS: u16 = 128; // allow \p{Han}, \P{Han} for Unicode group and negation pub const WAS_DOLLAR: u16 = 256; // regexp OpEndText was $, not \z pub const SIMPLE: u16 = 512; // regexp contains no counted repetition pub const MATCH_NL = ClassNL | DotNL; pub const PERL = ClassNL | OneLine | PerlX | UnicodeGroups; // as close to Perl as possible pub const POSIX: u16 = 0; // POSIX syntax pub const OpPseudo = 128; pub const Context = struct { allocator: *mem.Allocator, arena: std.heap.ArenaAllocator, pub fn init(a: *mem.Allocator) Context { return Context{ .allocator = a, .arena = std.heap.ArenaAllocator.init(a), }; } /// returns arena allocator. pub fn ar(self: *const Context) *Allocator { return &self.arena.allocator; } /// returns general allocator. pub fn ga(self: *const Context) *Allocator { return self.allocator; } fn deinit(self: *const Context) void { self.arena.deinit(); } }; pub const Regexp = struct { op: Op, flags: u16, sub: ArrayList(*Regexp), sub0: [1]?*Regexp, rune: ArrayList(i32), rune0: [2]i32, min: isize, max: isize, cap: isize, name: ?[]const u8, ctx: *const Context, pub const Op = enum { NoMatch, // matches no strings EmptyMatch, // matches empty string Literal, // matches Runes sequence CharClass, // matches Runes interpreted as range pair list AnyCharNotNL, // matches any character except newline AnyChar, // matches any character BeginLine, // matches empty string at beginning of line EndLine, // matches empty string at end of line BeginText, // matches empty string at beginning of text EndText, // matches empty string at end of text WordBoundary, // matches word boundary `\b` NoWordBoundary, // matches word non-boundary `\B` Capture, // capturing subexpression with index Cap, optional name Name Star, // matches Sub[0] zero or more times Plus, // matches Sub[0] one or more times Quest, // matches Sub[0] zero or one times Repeat, // matches Sub[0] at least Min times, at most Max (Max == -1 is no limit) Concat, // matches concatenation of Subs Alternate, // matches alternation of Subs }; pub fn init(ctx: *const Context) !Regexp { return Regexp{ .op = .NoMatch, .flags = 0, .sub = null, .rune = ArrayList(i32).init(ctx.ga()), .rune0 = [_]i32{ 0, 0 }, .min = 0, .max = 0, .cap = 0, .name = null, .ctx = ctx, }; } pub fn equal(x: *Regexp, y: *Regexp) bool { if (x.op != y.op) { return false; } switch (x.op) { .EndText => { if ((x.flags & WAS_DOLLAR) != (y.flags & WAS_DOLLAR)) { return false; } }, .Literal, .CharClass => { if ((x.rune == null) != (y.rune == null)) { return false; } if (x.rune != null and y.rune != null) { if (x.rune.?.len != y.rune.?.len) { return false; } for (x.rune.?.toSlice()) |v, i| { if (v != y.rune.?.at(i)) { return false; } } } }, .Alternate, .Concat => { if ((x.sub == null) != (y.sub == null)) { return false; } if (x.sub != null and y.sub != null) { if (x.rune.?.len != y.rune.?.len) { return false; } for (x.rune.?.toSlice()) |v, i| { if (v.equal(y.rune.?.at(i))) { return false; } } } }, .Star, .Plus, .Quest => { if ((flags & NON_GREEDY) != (y.flags & NON_GREEDY) or !(x.sub.?.at(0).equal(y.sub.?.at(0)))) { return false; } }, .Repeat => { if ((x.flags & NON_GREEDY) != (y.flags & NON_GREEDY) or (x.min != y.min) or x.max != y.max or !(x.sub.?.at(0).equal(y.sub.?.at(0)))) { return false; } }, .Capture => { if ((x.cap != y.cap) or equalName(x, y) or !(x.sub.?.at(0).equal(x.sub.at(0)))) { return false; } }, } return true; } fn equalName(x: *Regexp, y: *Regexp) bool { if ((x.name == null) and (y.name == null)) { return true; } if ((x.name == null) != (y.name == null)) { return false; } return mem.eql(u8, x.name.?, y.name.?); } /// returns a regexp equivalent to re but without counted repetitions /// and with various other simplifications, such as rewriting /(?:a+)+/ to /a+/. /// The resulting regexp will execute correctly but its string representation /// will not produce the same parse tree, because capturing parentheses /// may have been duplicated or removed. For example, the simplified form /// for /(x){1,2}/ is /(x)(x)?/ but both parentheses capture as $1. /// The returned regexp may share structure with or be the original. pub fn simplify(re: *Regexp) !*Regexp { switch (re.op) { .Capture, .Concat, .Alternate => { var nre = re; const subs = re.sub.toSlice(); for (subs) |sub, i| { var nsub = try sub.simplify(); if (nre == re and nsub != sub) { nre = try re.ctx.ar().create(Regexp); nre.* = init(re.ctx); try nre.sub.appendSlice(subs[0..i]); } if (nre != re) { try nre.sub.append(nsub); } } return nre; }, } } /// simplify1 implements Simplify for the unary OpStar, /// OpPlus, and OpQuest operators. It returns the simple regexp /// equivalent to /// /// Regexp{.op=ops, .flags= flags, .sub= {sub}} /// /// under the assumption that sub is already simple, and /// without first allocating that structure. If the regexp /// to be returned turns out to be equivalent to re, simplify1 /// returns re instead. /// /// simplify1 is factored out of Simplify because the implementation /// for other operators generates these unary expressions. /// Letting them call simplify1 makes sure the expressions they /// generate are simple. fn simplify1( ctx: *const Context, ops: Op, flags: u16, sub: *Regexp, re: ?*Regexp, ) !*Regexp { // Special case: repeat the empty string as much as // you want, but it's still the empty string. if (sub.op == .EmptyMatch) { return sub; } if (ops == sub.op and (flags & NON_GREEDY == sub.flags & NON_GREEDY)) { return sub; } if (re) |rex| { if (rex.op == ops and rex.flags & NON_GREEDY == flags & NON_GREEDY and sub.equal(rex.sub.at(0))) { return re.?; } } var res = try ctx.ar().create(Regexp); res.* = init(ctx); res.op = ops; res.flags = flags; try res.sub.append(sub); return res; } }; pub const Prog = struct { inst: ArrayList(Inst), start: usize, num_cap: usize, pub const EMPTY_BEGIN_LINE: u8 = 1; pub const EMPTY_END_LINE: u8 = 2; pub const EMPTY_BEGIN_TEXT: u8 = 4; pub const EMPTY_END_TEXT: u8 = 8; pub const EMPTY_WORD_BOUNDARY: u8 = 16; pub const EMPTY_NO_WORD_BOUNDARY: u8 = 32; const Inst = struct { op: Op, out: u32, arg: u32, rune: ?ArrayList(i32), const Op = enum { Alt, AltMatch, Capture, EmptyWidth, Match, Fail, Nop, Rune, Rune1, RuneAny, RuneAnyNotNL, }; }; }; const PerlGroup = struct { pub const code1 = [_]i32{ // /* \d */ 0x30, 0x39, }; pub const code2 = [_]i32{ // /* \s */ 0x9, 0xa, 0xc, 0xd, 0x20, 0x20, }; pub const code3 = [_]i32{ // /* \w */ 0x30, 0x39, 0x41, 0x5a, 0x5f, 0x5f, 0x61, 0x7a, }; pub const code4 = [_]i32{ // /* [:alnum:] */ 0x30, 0x39, 0x41, 0x5a, 0x61, 0x7a, }; pub const code5 = [_]i32{ // /* [:alpha:] */ 0x41, 0x5a, 0x61, 0x7a, }; pub const code6 = [_]i32{ // /* [:ascii:] */ 0x0, 0x7f, }; pub const code7 = [_]i32{ // /* [:blank:] */ 0x9, 0x9, 0x20, 0x20, }; pub const code8 = [_]i32{ // /* [:cntrl:] */ 0x0, 0x1f, 0x7f, 0x7f, }; pub const code9 = [_]i32{ // /* [:digit:] */ 0x30, 0x39, }; pub const code10 = [_]i32{ // /* [:graph:] */ 0x21, 0x7e, }; pub const code11 = [_]i32{ // /* [:lower:] */ 0x61, 0x7a, }; pub const code12 = [_]i32{ // /* [:print:] */ 0x20, 0x7e, }; pub const code13 = [_]i32{ // /* [:punct:] */ 0x21, 0x2f, 0x3a, 0x40, 0x5b, 0x60, 0x7b, 0x7e, }; pub const code14 = [_]i32{ // /* [:space:] */ 0x9, 0xd, 0x20, 0x20, }; pub const code15 = [_]i32{ // /* [:upper:] */ 0x41, 0x5a, }; pub const code16 = [_]i32{ // /* [:word:] */ 0x30, 0x39, 0x41, 0x5a, 0x5f, 0x5f, 0x61, 0x7a, }; pub const code17 = [_]i32{ // /* [:xdigit:] */ 0x30, 0x39, 0x41, 0x46, 0x61, 0x66, }; fn eql(a: []const u8, b: []const u8) bool { return mem.eql(u8, a, b); } pub fn perl(name: []const u8) ?CharGroup { if (eql(name, \\\d )) { return CharGroup{ .sign = .Plus, .class = code1[0..] }; } if (eql(name, \\\D )) { return CharGroup{ .sign = .Minus, .class = code1[0..] }; } if (eql(name, \\\s )) { return CharGroup{ .sign = .Plus, .class = code2[0..] }; } if (eql(name, \\\S )) { return CharGroup{ .sign = .Minus, .class = code2[0..] }; } if (eql(name, \\\w )) { return CharGroup{ .sign = .Plus, .class = code3[0..] }; } if (eql(name, \\\W )) { return CharGroup{ .sign = .Minus, .class = code3[0..] }; } return null; } pub fn posix(name: []const u8) ?CharGroup { if (eql(name, \\[:alnum:] )) { return CharGroup{ .sign = .Plus, .class = code4[0..] }; } if (eql(name, \\[:^alnum:] )) { return CharGroup{ .sign = .Minus, .class = code4[0..] }; } if (eql(name, \\[:alpha:] )) { return CharGroup{ .sign = .Plus, .class = code5[0..] }; } if (eql(name, \\[:^alpha:] )) { return CharGroup{ .sign = .Minus, .class = code5[0..] }; } if (eql(name, \\[:ascii:] )) { return CharGroup{ .sign = .Plus, .class = code6[0..] }; } if (eql(name, \\[:^ascii:] )) { return CharGroup{ .sign = .Minus, .class = code6[0..] }; } if (eql(name, \\[:blank:] )) { return CharGroup{ .sign = .Plus, .class = code7[0..] }; } if (eql(name, \\[:^blank:] )) { return CharGroup{ .sign = .Minus, .class = code7[0..] }; } if (eql(name, \\[:cntrl:] )) { return CharGroup{ .sign = .Plus, .class = code8[0..] }; } if (eql(name, \\[:^cntrl:] )) { return CharGroup{ .sign = .Minus, .class = code8[0..] }; } if (eql(name, \\[:digit:] )) { return CharGroup{ .sign = .Plus, .class = code9[0..] }; } if (eql(name, \\[:^digit:] )) { return CharGroup{ .sign = .Minus, .class = code9[0..] }; } if (eql(name, \\[:graph:] )) { return CharGroup{ .sign = .Plus, .class = code10[0..] }; } if (eql(name, \\[:^graph:] )) { return CharGroup{ .sign = .Minus, .class = code10[0..] }; } if (eql(name, \\[:lower:] )) { return CharGroup{ .sign = .Plus, .class = code11[0..] }; } if (eql(name, \\[:^lower:] )) { return CharGroup{ .sign = .Minus, .class = code11[0..] }; } if (eql(name, \\[:print:] )) { return CharGroup{ .sign = .Plus, .class = code12[0..] }; } if (eql(name, \\[:^print:] )) { return CharGroup{ .sign = .Minus, .class = code12[0..] }; } if (eql(name, \\[:punct:] )) { return CharGroup{ .sign = .Plus, .class = code13[0..] }; } if (eql(name, \\[:^punct:] )) { return CharGroup{ .sign = .Minus, .class = code13[0..] }; } if (eql(name, \\[:space:] )) { return CharGroup{ .sign = .Plus, .class = code14[0..] }; } if (eql(name, \\[:^space:] )) { return CharGroup{ .sign = .Minus, .class = code14[0..] }; } if (eql(name, \\[:upper:] )) { return CharGroup{ .sign = .Plus, .class = code15[0..] }; } if (eql(name, \\[:^upper:] )) { return CharGroup{ .sign = .Minus, .class = code15[0..] }; } if (eql(name, \\[:word:] )) { return CharGroup{ .sign = .Plus, .class = code16[0..] }; } if (eql(name, \\[:^word:] )) { return CharGroup{ .sign = .Minus, .class = code16[0..] }; } if (eql(name, \\[:xdigit:] )) { return CharGroup{ .sign = .Plus, .class = code17[0..] }; } if (eql(name, \\[:^xdigit:] )) { return CharGroup{ .sign = .Minus, .class = code17[0..] }; } } }; const CharGroup = struct { sign: Sign, class: []const i32, pub const Sign = enum { Plus, Minus, }; }; const min_fold = 0x0041; const max_fold = 0x1e94; const Parser = struct { ctx: Context, flags: u16, stack: std.ArrayList(*Regexp), free: ?*Regexp, num_cap: usize, whole_regexp: []const u8, // creates a new Regext object on the arena allocator help by self and // resurns it. fn newRexep(self: *Parser, op: Op) !*Regexp { var re = self.free; if (re != null) { self.free = re.sub0[0]; re.?.* = Regexp.init(self.ctx); } else { re = try self.ctx.ar().create(Regexp); re.?.* = Regexp.init(self.ctx); } r.op = op; return r; } fn reuse(self: *Parser, re: *Regexp) void { re.sub0[0] = self.free; self.free = re; } fn push(self: *Parser, re: *Regexp) !?*Regexp { if (re.op == .CharClass and re.rune.len == 2 and re.rune.at(0) == re.rune.at(1)) { if (try self.maybeConcat(re.rune.at(0), self.flags & ~FOLD_CASE)) { return null; } re.op = .Literal; try re.rune.resize(0); re.flags = self.flags & ~FOLD_CASE; } else if (re.op == .CharClass and re.rune.len == 4 and re.rune.at(0) == re.rune.at(1) and re.rune.at(2) == re.rune.at(3) and foldEql(re.rune.at(0), re.rune.at(2)) and foldEql(re.rune.at(2), re.rune.at(0)) or re.op == .CharClass and re.rune.len == 2 and re.rune.at(0) + 1 == re.rune.at(1) and foldEql(re.rune.at(0), re.rune.at(1)) and foldEql(re.rune.at(1), re.rune.at(0))) { if (try self.maybeConcat(re.rune.at(0), self.flags | FOLD_CASE)) { return null; } re.op = .Literal; try re.rune.resize(0); re.flags = self.flags | FOLD_CASE; } else { try self.maybeConcat(-1, 0); } try self.stack.append(re); return re; } fn foldEql(a: i32, b: i32) bool { return @intCast(i32, unicode.simpleFold(@intCast(u32, a))) == b; } fn maybeConcat(self: *Parser, rune: i32, flags: u16) !bool { const stack = self.stack.toSlice(); const n = stack.len; if (n < 2) { return false; } var re1 = stack[n - 1]; var re2 = stack[m - 2]; if (re1.op != .Literal or re2.op != .Literal or (re1.flags & FOLD_CASE) != (re2.flags & FOLD_CASE)) { return false; } try re2.rune.append(rune); if (rune >= 0) { try re1.rune.resize(1); try re1.rune.set(0, rune); r1.flags = flags; return true; } try self.stack.resize(n - 1); self.reuse(re1); return false; } fn newLiteral(self: *Parser, rune: i32, flags: u16) !*Regexp { var re = try self.newRexep(.Literal); re.flags = flags; if (flags & FOLD_CASE != 0) { re.rune0[0] = @intCast(i32, minFoldRune(rune)); try re.rune.resize(1); re.rune.set(0, rune); } else { re.rune0[0] = rune; try re.rune.resize(1); re.rune.set(0, rune); } return re; } fn minFoldRune(r: u32) u32 { if (r < min_fold or r < max_fold) { return r; } var min = r; var r0 = r; var x = unicode.simpleFold(x); while (x != r0) : (x = unicode.simpleFold(x)) { if (min > r) { min = r; } } return min; } fn literal(self: *Parser, rune: i32) !?*Regexp { return self.push(try self.newLiteral(rune, self.flags)); } fn op(self: *Parser, kind: Op) !*Regexp { var re = try self.newRexep(kind); re.flags = self.flags; return self.push(re); } /// repeat replaces the top stack element with itself repeated according to /// op, min, max. /// before is the regexp suffix starting at the repetition operator. /// after is the regexp suffix following after the repetition operator. /// repeat returns an updated 'after' and an error, if any. fn repeat( self: *Parser, ops: Op, min: isize, max: isize, before: []const u8, after: []const u8, last_repeat: []const u8, ) ![]const u8 { var flags = self.flags; var a = after; if (flags & PERLX != 0) { if (a.len > 0 and a[0] == '?') { a = a[1..]; flags = flags ^ NON_GREEDY; } if (last_repeat.len == 0) { // In Perl it is not allowed to stack repetition operators: // a** is a syntax error, not a doubled star, and a++ means // something else entirely, which we don't support! return error.InvalidRepeatOp; } } const n = self.stack.len; if (n == 0) { return error.MissingRepeatArgument; } var sub = self.stack.at(n - 1); if (@enumToInt(sub.op) >= OpPseudo) { return error.MissingRepeatArgument; } var re = try self.newRexep(ops); re.min = min; re.max = max; re.flags = flags; try re.sub.append(sub); self.stack.set(n - 1, re); if (ops == .Repeat and (min >= 2 or max >= 2) and !repeatIsValid(re, 1000)) { return error.InvalidRepeatSize; } return a; } /// repeatIsValid reports whether the repetition re is valid. /// Valid means that the combination of the top-level repetition /// and any inner repetitions does not exceed n copies of the /// innermost thing. /// This function rewalks the regexp tree and is called for every repetition, /// so we have to worry about inducing quadratic behavior in the parser. /// We avoid this by only calling repeatIsValid when min or max >= 2. /// In that case the depth of any >= 2 nesting can only get to 9 without /// triggering a parse error, so each subtree can only be rewalked 9 times. fn repeatIsValid(re: *Regexp, n: isize) bool { if (re.op == .Repeat) { var m = re.max; if (m == 0) { return true; } if (m < 0) { m = re.min; } if (m > n) { return false; } if (m > 0) { const x = @divFloor(n, m); for (re.sub.toSlice()) |sub| { if (!repeatIsValid(sub, x)) { return false; } } return true; } } for (re.sub.toSlice()) |sub| { if (!repeatIsValid(sub, n)) { return false; } } return true; } fn concat(self: *Parser) !?*Regexp { try self.maybeConcat(-1, 0); // Scan down to find pseudo-operator | or (. var i = self.stack.len; while (i > 0 and self.stack.at(i - 1).op < OpPseudo) { if (i > 0) i -= 1; } const subs = self.stack.toSlice()[i..]; try self.stack.resize(i); if (subs.len == 0) { return self.push(try self.newRexep(.EmptyMatch)); } return self.push(try self.collapse(subs, .Concat)); } /// cleanAlt cleans re for eventual inclusion in an alternation. fn cleanAlt(re: *Regexp) void { if (re.op == .CharClass) { re.rune = clearClass(&re.rune); if (re.rune.len == 2 and re.rune.at(0) == 0 and re.rune.at(1) == unicode.utf8.max_rune) { re.rune.resize(0) catch unreachable; re.op = .AnyChar; return; } if (re.rune.len == 4 and re.rune.at(0) == 0 and re.rune.at(1) == ('\n' - 1) and re.rune.at(2) == ('\n' + 1) and re.rune.at(3) == unicode.utf8.max_rune) { re.rune.resize(0) catch unreachable; re.op = .AnyCharNotNL; return; } } } };
src/regexp/syntax/syntax.zig
const builtin = @import("builtin"); const std = @import("std"); const debug = std.debug; const mem = std.mem; const testing = std.testing; const native_endian = builtin.target.cpu.arch.endian(); pub const li128 = Int(i128, .Little); pub const li16 = Int(i16, .Little); pub const li32 = Int(i32, .Little); pub const li64 = Int(i64, .Little); pub const lu128 = Int(u128, .Little); pub const lu16 = Int(u16, .Little); pub const lu32 = Int(u32, .Little); pub const lu64 = Int(u64, .Little); pub const bi128 = Int(i128, .Big); pub const bi16 = Int(i16, .Big); pub const bi32 = Int(i32, .Big); pub const bu128 = Int(u128, .Big); pub const bu16 = Int(u16, .Big); pub const bu32 = Int(u32, .Big); pub const bu64 = Int(u64, .Big); /// A data structure representing an integer of a specific endianess pub fn Int(comptime _Inner: type, comptime _endian: std.builtin.Endian) type { comptime debug.assert(@typeInfo(_Inner) == .Int); return packed struct { inner: Inner, pub const Inner = _Inner; pub const endian = _endian; pub fn init(v: Inner) @This() { return .{ .inner = swap(v) }; } /// Converts the integer to native endianess and returns it. pub fn value(int: @This()) Inner { return swap(int.inner); } pub fn format( self: @This(), comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype, ) !void { return std.fmt.formatIntValue(self.value(), fmt, options, writer); } fn swap(v: Inner) Inner { return if (_endian != native_endian) @byteSwap(Inner, v) else v; } }; } test "Int" { const value: u32 = 0x12345678; const numLittle = Int(u32, .Little).init(value); const numBig = Int(u32, .Big).init(value); try testing.expectEqual(value, numLittle.value()); try testing.expectEqual(value, numBig.value()); try testing.expectEqualSlices(u8, &[_]u8{ 0x78, 0x56, 0x34, 0x12 }, @ptrCast(*const [4]u8, &numLittle)); try testing.expectEqualSlices(u8, &[_]u8{ 0x12, 0x34, 0x56, 0x78 }, @ptrCast(*const [4]u8, &numBig)); switch (native_endian) { .Big => { try testing.expectEqual(@as(u32, 0x78563412), numLittle.inner); try testing.expectEqual(value, numBig.inner); }, .Little => { try testing.expectEqual(@as(u32, 0x78563412), numBig.inner); try testing.expectEqual(value, numLittle.inner); }, } }
src/core/rom/int.zig
const std = @import("std"); const print = std.debug.print; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day07.txt"); pub fn main() !void { var timer = try std.time.Timer.start(); var crabs = std.ArrayList(u16).init(gpa); defer { crabs.deinit(); } var iterator = std.mem.tokenize(data, ", \r\n"); while (iterator.next()) |crab| { try crabs.append(try std.fmt.parseInt(u16, crab, 10)); } var max_crab : u16 = 0; { var index : usize = 0; while (index < crabs.items.len) : (index += 1) { const crab = crabs.items[index]; if (max_crab < crab) { max_crab = crab; } } } { var least_fuel : u32 = std.math.maxInt(u32); var crab : u16 = 0; while (crab < max_crab) : (crab += 1) { var fuel : u32 = 0; var index : usize = 0; while (index < crabs.items.len) : (index += 1) { const other = crabs.items[index]; fuel += if (crab < other) other - crab else crab - other; if (fuel > least_fuel) { break; } } if (fuel < least_fuel) { least_fuel = fuel; } } print("🎁 Least fuel: {}\n", .{least_fuel}); print("Day 07 - part 01 took {:15}ns\n", .{timer.lap()}); timer.reset(); } { var least_fuel : u32 = std.math.maxInt(u32); var crab : u16 = 0; while (crab < max_crab) : (crab += 1) { var fuel : u32 = 0; var index : usize = 0; while (index < crabs.items.len) : (index += 1) { const other = crabs.items[index]; const cost : u32 = if (crab < other) other - crab else crab - other; // Used Wolfram Alpha to solve the sequence here: // `0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, ...` fuel += (cost * (cost + 1)) / 2; } if (fuel < least_fuel) { least_fuel = fuel; } } print("🎁 Least fuel: {}\n", .{least_fuel}); print("Day 07 - part 02 took {:15}ns\n", .{timer.lap()}); print("❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️\n", .{}); } }
src/day07.zig
const std = @import("std"); const math = std.math; const meta = std.meta; pub fn formatInt(value: anytype, writer: anytype) @TypeOf(writer).Error!void { comptime std.debug.assert(meta.trait.isIntegral(@TypeOf(value))); const Int = switch (@typeInfo(@TypeOf(value))) { .Int => @TypeOf(value), .ComptimeInt => blk: { // Coerce comptime_int into an appropriate integer type. // // The `Fitted` type is converted into a i8 so that @rem(value, // 100) can be computed in `formatDecimal`. // // Unsigned comptime_ints with less than 7 bits and signed // comptime_ints with less than 8 bits cause a compile error since // 100 cannot be coerced into such types. const Fitted = math.IntFittingRange(value, value); break :blk if (meta.bitCount(Fitted) < 8) i8 else Fitted; }, else => unreachable, }; const int = @as(Int, value); // This buffer should be large enough to hold all digits of T and a sign. // // TODO: Change to digits10 + 1 for better space efficiency. var buf: [math.max(meta.bitCount(Int), 1) + 1]u8 = undefined; var start = switch (@typeInfo(Int).Int.signedness) { .signed => blk: { var start = formatDecimal(abs(int), &buf); if (value < 0) { start -= 1; buf[start] = '-'; } break :blk start; }, .unsigned => formatDecimal(int, &buf), }; try writer.writeAll(buf[start..]); } /// Returns the absolute value of `x`. /// /// The return type of `abs` is the smallest type between u32, u64, and u128 /// that can store all possible absolute values of the type of `x`. For /// example, if the type of `x` is i8, then the greatest absolute value /// possible is 128. 128 can be stored as a u32, and u32 is smaller than u64 /// and u128, so u32 is the return type. /// /// For positive integers, `x` is simply casted to the return type and /// returned. /// /// For negative integers, if `x` is greater than the smallest possible value /// of @TypeOf(x), then the negation of `x` is casted to the return type and is /// returned. Otherwise, the wrapped difference between `x` and 1 is casted to /// the return type and the sum between the difference and 1 is returned. fn abs(x: anytype) U32Or64Or128(@TypeOf(x)) { const T = @TypeOf(x); comptime std.debug.assert(@typeInfo(T) == .Int); const Unsigned = U32Or64Or128(T); if (x > 0) return @intCast(Unsigned, x); if (x > math.minInt(T)) { return @intCast(Unsigned, -x); } else { return @intCast(Unsigned, x -% 1) + 1; } } /// Returns the smallest type between u32, u64, and u128 that can hold all /// positive values of T. fn U32Or64Or128(comptime T: type) type { comptime std.debug.assert(@typeInfo(T) == .Int); comptime std.debug.assert(@typeInfo(T).Int.bits <= 128); const max = math.maxInt(T); const max_u32 = math.maxInt(u32); const max_u64 = math.maxInt(u64); const max_u128 = math.maxInt(u128); if (max <= max_u32) return u32; if (max <= max_u64) return u64; if (max <= max_u128) return u128; // UNREACHABLE: It is asserted above that the number of bits in T is less // than or equal to 128. unreachable; } fn formatDecimal(value: anytype, buf: []u8) usize { comptime std.debug.assert(@typeInfo(@TypeOf(value)) == .Int); var v = value; var index: usize = buf.len; while (v >= 100) : (v = @divTrunc(v, 100)) { index -= 2; std.mem.copy(u8, buf[index..], digits2(@intCast(usize, @rem(v, 100)))[0..2]); } if (v < 10) { index -= 1; buf[index] = '0' + @intCast(u8, v); } else { index -= 2; std.mem.copy(u8, buf[index..], digits2(@intCast(usize, v))[0..2]); } return index; } /// Converts values in the range [0, 100) to a string. fn digits2(value: usize) []const u8 { return ("0001020304050607080910111213141516171819" ++ "2021222324252627282930313233343536373839" ++ "4041424344454647484950515253545556575859" ++ "6061626364656667686970717273747576777879" ++ "8081828384858687888990919293949596979899")[value * 2 ..]; } /// Returns the number of digits in `value`. fn countDigits(value: anytype) usize { comptime std.debug.assert(@typeInfo(@TypeOf(value)) == .Int); const bits = comptime math.log2(10); var n: usize = 1; { var v = value >> bits; while (v != 0) : (n += 1) v >>= bits; } return n; }
src/ser/impl/formatter/details/fmt.zig
const std = @import("../std.zig"); const mem = std.mem; const testing = std.testing; /// Compares two arrays in constant time (for a given length) and returns whether they are equal. /// This function was designed to compare short cryptographic secrets (MACs, signatures). /// For all other applications, use mem.eql() instead. pub fn timingSafeEql(comptime T: type, a: T, b: T) bool { switch (@typeInfo(T)) { .Array => |info| { const C = info.child; if (@typeInfo(C) != .Int) { @compileError("Elements to be compared must be integers"); } var acc = @as(C, 0); for (a) |x, i| { acc |= x ^ b[i]; } comptime const s = @typeInfo(C).Int.bits; comptime const Cu = std.meta.Int(.unsigned, s); comptime const Cext = std.meta.Int(.unsigned, s + 1); return @bitCast(bool, @truncate(u1, (@as(Cext, @bitCast(Cu, acc)) -% 1) >> s)); }, .Vector => |info| { const C = info.child; if (@typeInfo(C) != .Int) { @compileError("Elements to be compared must be integers"); } const acc = @reduce(.Or, a ^ b); comptime const s = @typeInfo(C).Int.bits; comptime const Cu = std.meta.Int(.unsigned, s); comptime const Cext = std.meta.Int(.unsigned, s + 1); return @bitCast(bool, @truncate(u1, (@as(Cext, @bitCast(Cu, acc)) -% 1) >> s)); }, else => { @compileError("Only arrays and vectors can be compared"); }, } } /// Sets a slice to zeroes. /// Prevents the store from being optimized out. pub fn secureZero(comptime T: type, s: []T) void { // NOTE: We do not use a volatile slice cast here since LLVM cannot // see that it can be replaced by a memset. const ptr = @ptrCast([*]volatile u8, s.ptr); const length = s.len * @sizeOf(T); @memset(ptr, 0, length); } test "crypto.utils.timingSafeEql" { var a: [100]u8 = undefined; var b: [100]u8 = undefined; try std.crypto.randomBytes(a[0..]); try std.crypto.randomBytes(b[0..]); testing.expect(!timingSafeEql([100]u8, a, b)); mem.copy(u8, a[0..], b[0..]); testing.expect(timingSafeEql([100]u8, a, b)); } test "crypto.utils.timingSafeEql (vectors)" { var a: [100]u8 = undefined; var b: [100]u8 = undefined; try std.crypto.randomBytes(a[0..]); try std.crypto.randomBytes(b[0..]); const v1: std.meta.Vector(100, u8) = a; const v2: std.meta.Vector(100, u8) = b; testing.expect(!timingSafeEql(std.meta.Vector(100, u8), v1, v2)); const v3: std.meta.Vector(100, u8) = a; testing.expect(timingSafeEql(std.meta.Vector(100, u8), v1, v3)); } test "crypto.utils.secureZero" { var a = [_]u8{0xfe} ** 8; var b = [_]u8{0xfe} ** 8; mem.set(u8, a[0..], 0); secureZero(u8, b[0..]); testing.expectEqualSlices(u8, a[0..], b[0..]); }
lib/std/crypto/utils.zig
const std = @import("../index.zig"); const math = std.math; const assert = std.debug.assert; const builtin = @import("builtin"); const TypeId = builtin.TypeId; pub fn sqrt(x: var) (if (@typeId(@typeOf(x)) == TypeId.Int) @IntType(false, @typeOf(x).bit_count / 2) else @typeOf(x)) { const T = @typeOf(x); switch (@typeId(T)) { TypeId.ComptimeFloat => return T(@sqrt(f64, x)), // TODO upgrade to f128 TypeId.Float => return @sqrt(T, x), TypeId.ComptimeInt => comptime { if (x > @maxValue(u128)) { @compileError("sqrt not implemented for comptime_int greater than 128 bits"); } if (x < 0) { @compileError("sqrt on negative number"); } return T(sqrt_int(u128, x)); }, TypeId.Int => return sqrt_int(T, x), else => @compileError("sqrt not implemented for " ++ @typeName(T)), } } test "math.sqrt" { assert(sqrt(f32(0.0)) == @sqrt(f32, 0.0)); assert(sqrt(f64(0.0)) == @sqrt(f64, 0.0)); } test "math.sqrt32" { const epsilon = 0.000001; assert(@sqrt(f32, 0.0) == 0.0); assert(math.approxEq(f32, @sqrt(f32, 2.0), 1.414214, epsilon)); assert(math.approxEq(f32, @sqrt(f32, 3.6), 1.897367, epsilon)); assert(@sqrt(f32, 4.0) == 2.0); assert(math.approxEq(f32, @sqrt(f32, 7.539840), 2.745877, epsilon)); assert(math.approxEq(f32, @sqrt(f32, 19.230934), 4.385309, epsilon)); assert(@sqrt(f32, 64.0) == 8.0); assert(math.approxEq(f32, @sqrt(f32, 64.1), 8.006248, epsilon)); assert(math.approxEq(f32, @sqrt(f32, 8942.230469), 94.563370, epsilon)); } test "math.sqrt64" { const epsilon = 0.000001; assert(@sqrt(f64, 0.0) == 0.0); assert(math.approxEq(f64, @sqrt(f64, 2.0), 1.414214, epsilon)); assert(math.approxEq(f64, @sqrt(f64, 3.6), 1.897367, epsilon)); assert(@sqrt(f64, 4.0) == 2.0); assert(math.approxEq(f64, @sqrt(f64, 7.539840), 2.745877, epsilon)); assert(math.approxEq(f64, @sqrt(f64, 19.230934), 4.385309, epsilon)); assert(@sqrt(f64, 64.0) == 8.0); assert(math.approxEq(f64, @sqrt(f64, 64.1), 8.006248, epsilon)); assert(math.approxEq(f64, @sqrt(f64, 8942.230469), 94.563367, epsilon)); } test "math.sqrt32.special" { assert(math.isPositiveInf(@sqrt(f32, math.inf(f32)))); assert(@sqrt(f32, 0.0) == 0.0); assert(@sqrt(f32, -0.0) == -0.0); assert(math.isNan(@sqrt(f32, -1.0))); assert(math.isNan(@sqrt(f32, math.nan(f32)))); } test "math.sqrt64.special" { assert(math.isPositiveInf(@sqrt(f64, math.inf(f64)))); assert(@sqrt(f64, 0.0) == 0.0); assert(@sqrt(f64, -0.0) == -0.0); assert(math.isNan(@sqrt(f64, -1.0))); assert(math.isNan(@sqrt(f64, math.nan(f64)))); } fn sqrt_int(comptime T: type, value: T) @IntType(false, T.bit_count / 2) { var op = value; var res: T = 0; var one: T = 1 << (T.bit_count - 2); // "one" starts at the highest power of four <= than the argument. while (one > op) { one >>= 2; } while (one != 0) { if (op >= res + one) { op -= res + one; res += 2 * one; } res >>= 1; one >>= 2; } const ResultType = @IntType(false, T.bit_count / 2); return @intCast(ResultType, res); } test "math.sqrt_int" { assert(sqrt_int(u32, 3) == 1); assert(sqrt_int(u32, 4) == 2); assert(sqrt_int(u32, 5) == 2); assert(sqrt_int(u32, 8) == 2); assert(sqrt_int(u32, 9) == 3); assert(sqrt_int(u32, 10) == 3); }
std/math/sqrt.zig
const Emit = @This(); const std = @import("std"); const Mir = @import("Mir.zig"); const link = @import("../../link.zig"); const Module = @import("../../Module.zig"); const leb128 = std.leb; /// Contains our list of instructions mir: Mir, /// Reference to the file handler bin_file: *link.File, /// Possible error message. When set, the value is allocated and /// must be freed manually. error_msg: ?*Module.ErrorMsg = null, /// The binary representation that will be emit by this module. code: *std.ArrayList(u8), /// List of allocated locals. locals: []const u8, /// The declaration that code is being generated for. decl: *Module.Decl, const InnerError = error{ OutOfMemory, EmitFail, }; pub fn emitMir(emit: *Emit) InnerError!void { const mir_tags = emit.mir.instructions.items(.tag); // write the locals in the prologue of the function body // before we emit the function body when lowering MIR try emit.emitLocals(); for (mir_tags) |tag, index| { const inst = @intCast(u32, index); switch (tag) { // block instructions .block => try emit.emitBlock(tag, inst), .loop => try emit.emitBlock(tag, inst), // branch instructions .br_if => try emit.emitLabel(tag, inst), .br_table => try emit.emitBrTable(inst), .br => try emit.emitLabel(tag, inst), // relocatables .call => try emit.emitCall(inst), .call_indirect => try emit.emitCallIndirect(inst), .global_get => try emit.emitGlobal(tag, inst), .global_set => try emit.emitGlobal(tag, inst), .function_index => try emit.emitFunctionIndex(inst), .memory_address => try emit.emitMemAddress(inst), // immediates .f32_const => try emit.emitFloat32(inst), .f64_const => try emit.emitFloat64(inst), .i32_const => try emit.emitImm32(inst), .i64_const => try emit.emitImm64(inst), // memory instructions .i32_load => try emit.emitMemArg(tag, inst), .i64_load => try emit.emitMemArg(tag, inst), .f32_load => try emit.emitMemArg(tag, inst), .f64_load => try emit.emitMemArg(tag, inst), .i32_load8_s => try emit.emitMemArg(tag, inst), .i32_load8_u => try emit.emitMemArg(tag, inst), .i32_load16_s => try emit.emitMemArg(tag, inst), .i32_load16_u => try emit.emitMemArg(tag, inst), .i64_load8_s => try emit.emitMemArg(tag, inst), .i64_load8_u => try emit.emitMemArg(tag, inst), .i64_load16_s => try emit.emitMemArg(tag, inst), .i64_load16_u => try emit.emitMemArg(tag, inst), .i64_load32_s => try emit.emitMemArg(tag, inst), .i64_load32_u => try emit.emitMemArg(tag, inst), .i32_store => try emit.emitMemArg(tag, inst), .i64_store => try emit.emitMemArg(tag, inst), .f32_store => try emit.emitMemArg(tag, inst), .f64_store => try emit.emitMemArg(tag, inst), .i32_store8 => try emit.emitMemArg(tag, inst), .i32_store16 => try emit.emitMemArg(tag, inst), .i64_store8 => try emit.emitMemArg(tag, inst), .i64_store16 => try emit.emitMemArg(tag, inst), .i64_store32 => try emit.emitMemArg(tag, inst), // Instructions with an index that do not require relocations .local_get => try emit.emitLabel(tag, inst), .local_set => try emit.emitLabel(tag, inst), .local_tee => try emit.emitLabel(tag, inst), .memory_grow => try emit.emitLabel(tag, inst), .memory_size => try emit.emitLabel(tag, inst), // no-ops .end => try emit.emitTag(tag), .@"return" => try emit.emitTag(tag), .@"unreachable" => try emit.emitTag(tag), .select => try emit.emitTag(tag), // arithmetic .i32_eqz => try emit.emitTag(tag), .i32_eq => try emit.emitTag(tag), .i32_ne => try emit.emitTag(tag), .i32_lt_s => try emit.emitTag(tag), .i32_lt_u => try emit.emitTag(tag), .i32_gt_s => try emit.emitTag(tag), .i32_gt_u => try emit.emitTag(tag), .i32_le_s => try emit.emitTag(tag), .i32_le_u => try emit.emitTag(tag), .i32_ge_s => try emit.emitTag(tag), .i32_ge_u => try emit.emitTag(tag), .i64_eqz => try emit.emitTag(tag), .i64_eq => try emit.emitTag(tag), .i64_ne => try emit.emitTag(tag), .i64_lt_s => try emit.emitTag(tag), .i64_lt_u => try emit.emitTag(tag), .i64_gt_s => try emit.emitTag(tag), .i64_gt_u => try emit.emitTag(tag), .i64_le_s => try emit.emitTag(tag), .i64_le_u => try emit.emitTag(tag), .i64_ge_s => try emit.emitTag(tag), .i64_ge_u => try emit.emitTag(tag), .f32_eq => try emit.emitTag(tag), .f32_ne => try emit.emitTag(tag), .f32_lt => try emit.emitTag(tag), .f32_gt => try emit.emitTag(tag), .f32_le => try emit.emitTag(tag), .f32_ge => try emit.emitTag(tag), .f64_eq => try emit.emitTag(tag), .f64_ne => try emit.emitTag(tag), .f64_lt => try emit.emitTag(tag), .f64_gt => try emit.emitTag(tag), .f64_le => try emit.emitTag(tag), .f64_ge => try emit.emitTag(tag), .i32_add => try emit.emitTag(tag), .i32_sub => try emit.emitTag(tag), .i32_mul => try emit.emitTag(tag), .i32_div_s => try emit.emitTag(tag), .i32_div_u => try emit.emitTag(tag), .i32_and => try emit.emitTag(tag), .i32_or => try emit.emitTag(tag), .i32_xor => try emit.emitTag(tag), .i32_shl => try emit.emitTag(tag), .i32_shr_s => try emit.emitTag(tag), .i32_shr_u => try emit.emitTag(tag), .i64_add => try emit.emitTag(tag), .i64_sub => try emit.emitTag(tag), .i64_mul => try emit.emitTag(tag), .i64_div_s => try emit.emitTag(tag), .i64_div_u => try emit.emitTag(tag), .i64_and => try emit.emitTag(tag), .i64_or => try emit.emitTag(tag), .i64_xor => try emit.emitTag(tag), .i64_shl => try emit.emitTag(tag), .i64_shr_s => try emit.emitTag(tag), .i64_shr_u => try emit.emitTag(tag), .f32_abs => try emit.emitTag(tag), .f32_neg => try emit.emitTag(tag), .f32_ceil => try emit.emitTag(tag), .f32_floor => try emit.emitTag(tag), .f32_trunc => try emit.emitTag(tag), .f32_nearest => try emit.emitTag(tag), .f32_sqrt => try emit.emitTag(tag), .f32_add => try emit.emitTag(tag), .f32_sub => try emit.emitTag(tag), .f32_mul => try emit.emitTag(tag), .f32_div => try emit.emitTag(tag), .f32_min => try emit.emitTag(tag), .f32_max => try emit.emitTag(tag), .f32_copysign => try emit.emitTag(tag), .f64_abs => try emit.emitTag(tag), .f64_neg => try emit.emitTag(tag), .f64_ceil => try emit.emitTag(tag), .f64_floor => try emit.emitTag(tag), .f64_trunc => try emit.emitTag(tag), .f64_nearest => try emit.emitTag(tag), .f64_sqrt => try emit.emitTag(tag), .f64_add => try emit.emitTag(tag), .f64_sub => try emit.emitTag(tag), .f64_mul => try emit.emitTag(tag), .f64_div => try emit.emitTag(tag), .f64_min => try emit.emitTag(tag), .f64_max => try emit.emitTag(tag), .f64_copysign => try emit.emitTag(tag), .i32_wrap_i64 => try emit.emitTag(tag), .i64_extend_i32_s => try emit.emitTag(tag), .i64_extend_i32_u => try emit.emitTag(tag), .i32_extend8_s => try emit.emitTag(tag), .i32_extend16_s => try emit.emitTag(tag), .i64_extend8_s => try emit.emitTag(tag), .i64_extend16_s => try emit.emitTag(tag), .i64_extend32_s => try emit.emitTag(tag), .f32_demote_f64 => try emit.emitTag(tag), .f64_promote_f32 => try emit.emitTag(tag), .i32_reinterpret_f32 => try emit.emitTag(tag), .i64_reinterpret_f64 => try emit.emitTag(tag), .f32_reinterpret_i32 => try emit.emitTag(tag), .f64_reinterpret_i64 => try emit.emitTag(tag), .i32_trunc_f32_s => try emit.emitTag(tag), .i32_trunc_f32_u => try emit.emitTag(tag), .i32_trunc_f64_s => try emit.emitTag(tag), .i32_trunc_f64_u => try emit.emitTag(tag), .i64_trunc_f32_s => try emit.emitTag(tag), .i64_trunc_f32_u => try emit.emitTag(tag), .i64_trunc_f64_s => try emit.emitTag(tag), .i64_trunc_f64_u => try emit.emitTag(tag), .f32_convert_i32_s => try emit.emitTag(tag), .f32_convert_i32_u => try emit.emitTag(tag), .f32_convert_i64_s => try emit.emitTag(tag), .f32_convert_i64_u => try emit.emitTag(tag), .f64_convert_i32_s => try emit.emitTag(tag), .f64_convert_i32_u => try emit.emitTag(tag), .f64_convert_i64_s => try emit.emitTag(tag), .f64_convert_i64_u => try emit.emitTag(tag), .i32_rem_s => try emit.emitTag(tag), .i32_rem_u => try emit.emitTag(tag), .i64_rem_s => try emit.emitTag(tag), .i64_rem_u => try emit.emitTag(tag), .i32_popcnt => try emit.emitTag(tag), .i64_popcnt => try emit.emitTag(tag), .i32_clz => try emit.emitTag(tag), .i32_ctz => try emit.emitTag(tag), .i64_clz => try emit.emitTag(tag), .i64_ctz => try emit.emitTag(tag), .extended => try emit.emitExtended(inst), } } } fn offset(self: Emit) u32 { return @intCast(u32, self.code.items.len); } fn fail(emit: *Emit, comptime format: []const u8, args: anytype) InnerError { @setCold(true); std.debug.assert(emit.error_msg == null); // TODO: Determine the source location. emit.error_msg = try Module.ErrorMsg.create(emit.bin_file.allocator, emit.decl.srcLoc(), format, args); return error.EmitFail; } fn emitLocals(emit: *Emit) !void { const writer = emit.code.writer(); try leb128.writeULEB128(writer, @intCast(u32, emit.locals.len)); // emit the actual locals amount for (emit.locals) |local| { try leb128.writeULEB128(writer, @as(u32, 1)); try writer.writeByte(local); } } fn emitTag(emit: *Emit, tag: Mir.Inst.Tag) !void { try emit.code.append(@enumToInt(tag)); } fn emitBlock(emit: *Emit, tag: Mir.Inst.Tag, inst: Mir.Inst.Index) !void { const block_type = emit.mir.instructions.items(.data)[inst].block_type; try emit.code.append(@enumToInt(tag)); try emit.code.append(block_type); } fn emitBrTable(emit: *Emit, inst: Mir.Inst.Index) !void { const extra_index = emit.mir.instructions.items(.data)[inst].payload; const extra = emit.mir.extraData(Mir.JumpTable, extra_index); const labels = emit.mir.extra[extra.end..][0..extra.data.length]; const writer = emit.code.writer(); try emit.code.append(std.wasm.opcode(.br_table)); try leb128.writeULEB128(writer, extra.data.length - 1); // Default label is not part of length/depth for (labels) |label| { try leb128.writeULEB128(writer, label); } } fn emitLabel(emit: *Emit, tag: Mir.Inst.Tag, inst: Mir.Inst.Index) !void { const label = emit.mir.instructions.items(.data)[inst].label; try emit.code.append(@enumToInt(tag)); try leb128.writeULEB128(emit.code.writer(), label); } fn emitGlobal(emit: *Emit, tag: Mir.Inst.Tag, inst: Mir.Inst.Index) !void { const label = emit.mir.instructions.items(.data)[inst].label; try emit.code.append(@enumToInt(tag)); var buf: [5]u8 = undefined; leb128.writeUnsignedFixed(5, &buf, label); const global_offset = emit.offset(); try emit.code.appendSlice(&buf); // globals can have index 0 as it represents the stack pointer try emit.decl.link.wasm.relocs.append(emit.bin_file.allocator, .{ .index = label, .offset = global_offset, .relocation_type = .R_WASM_GLOBAL_INDEX_LEB, }); } fn emitImm32(emit: *Emit, inst: Mir.Inst.Index) !void { const value: i32 = emit.mir.instructions.items(.data)[inst].imm32; try emit.code.append(std.wasm.opcode(.i32_const)); try leb128.writeILEB128(emit.code.writer(), value); } fn emitImm64(emit: *Emit, inst: Mir.Inst.Index) !void { const extra_index = emit.mir.instructions.items(.data)[inst].payload; const value = emit.mir.extraData(Mir.Imm64, extra_index); try emit.code.append(std.wasm.opcode(.i64_const)); try leb128.writeILEB128(emit.code.writer(), @bitCast(i64, value.data.toU64())); } fn emitFloat32(emit: *Emit, inst: Mir.Inst.Index) !void { const value: f32 = emit.mir.instructions.items(.data)[inst].float32; try emit.code.append(std.wasm.opcode(.f32_const)); try emit.code.writer().writeIntLittle(u32, @bitCast(u32, value)); } fn emitFloat64(emit: *Emit, inst: Mir.Inst.Index) !void { const extra_index = emit.mir.instructions.items(.data)[inst].payload; const value = emit.mir.extraData(Mir.Float64, extra_index); try emit.code.append(std.wasm.opcode(.f64_const)); try emit.code.writer().writeIntLittle(u64, value.data.toU64()); } fn emitMemArg(emit: *Emit, tag: Mir.Inst.Tag, inst: Mir.Inst.Index) !void { const extra_index = emit.mir.instructions.items(.data)[inst].payload; const mem_arg = emit.mir.extraData(Mir.MemArg, extra_index).data; try emit.code.append(@enumToInt(tag)); // wasm encodes alignment as power of 2, rather than natural alignment const encoded_alignment = @ctz(u32, mem_arg.alignment); try leb128.writeULEB128(emit.code.writer(), encoded_alignment); try leb128.writeULEB128(emit.code.writer(), mem_arg.offset); } fn emitCall(emit: *Emit, inst: Mir.Inst.Index) !void { const label = emit.mir.instructions.items(.data)[inst].label; try emit.code.append(std.wasm.opcode(.call)); const call_offset = emit.offset(); var buf: [5]u8 = undefined; leb128.writeUnsignedFixed(5, &buf, label); try emit.code.appendSlice(&buf); if (label != 0) { try emit.decl.link.wasm.relocs.append(emit.bin_file.allocator, .{ .offset = call_offset, .index = label, .relocation_type = .R_WASM_FUNCTION_INDEX_LEB, }); } } fn emitCallIndirect(emit: *Emit, inst: Mir.Inst.Index) !void { const type_index = emit.mir.instructions.items(.data)[inst].label; try emit.code.append(std.wasm.opcode(.call_indirect)); // NOTE: If we remove unused function types in the future for incremental // linking, we must also emit a relocation for this `type_index` try leb128.writeULEB128(emit.code.writer(), type_index); try leb128.writeULEB128(emit.code.writer(), @as(u32, 0)); // TODO: Emit relocation for table index } fn emitFunctionIndex(emit: *Emit, inst: Mir.Inst.Index) !void { const symbol_index = emit.mir.instructions.items(.data)[inst].label; try emit.code.append(std.wasm.opcode(.i32_const)); const index_offset = emit.offset(); var buf: [5]u8 = undefined; leb128.writeUnsignedFixed(5, &buf, symbol_index); try emit.code.appendSlice(&buf); if (symbol_index != 0) { try emit.decl.link.wasm.relocs.append(emit.bin_file.allocator, .{ .offset = index_offset, .index = symbol_index, .relocation_type = .R_WASM_TABLE_INDEX_SLEB, }); } } fn emitMemAddress(emit: *Emit, inst: Mir.Inst.Index) !void { const extra_index = emit.mir.instructions.items(.data)[inst].payload; const mem = emit.mir.extraData(Mir.Memory, extra_index).data; const mem_offset = emit.offset() + 1; const is_wasm32 = emit.bin_file.options.target.cpu.arch == .wasm32; if (is_wasm32) { try emit.code.append(std.wasm.opcode(.i32_const)); var buf: [5]u8 = undefined; leb128.writeUnsignedFixed(5, &buf, mem.pointer); try emit.code.appendSlice(&buf); } else { try emit.code.append(std.wasm.opcode(.i64_const)); var buf: [10]u8 = undefined; leb128.writeUnsignedFixed(10, &buf, mem.pointer); try emit.code.appendSlice(&buf); } if (mem.pointer != 0) { try emit.decl.link.wasm.relocs.append(emit.bin_file.allocator, .{ .offset = mem_offset, .index = mem.pointer, .relocation_type = if (is_wasm32) .R_WASM_MEMORY_ADDR_LEB else .R_WASM_MEMORY_ADDR_LEB64, .addend = mem.offset, }); } } fn emitExtended(emit: *Emit, inst: Mir.Inst.Index) !void { const opcode = emit.mir.instructions.items(.secondary)[inst]; switch (@intToEnum(std.wasm.PrefixedOpcode, opcode)) { .memory_fill => try emit.emitMemFill(), else => |tag| return emit.fail("TODO: Implement extension instruction: {s}\n", .{@tagName(tag)}), } } fn emitMemFill(emit: *Emit) !void { try emit.code.append(0xFC); try emit.code.append(0x0B); // When multi-memory proposal reaches phase 4, we // can emit a different memory index here. // For now we will always emit index 0. try leb128.writeULEB128(emit.code.writer(), @as(u32, 0)); }
src/arch/wasm/Emit.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const ArrayListUnmanaged = std.ArrayListUnmanaged; const File = std.fs.File; const bufferedWriter = std.io.bufferedWriter; const math = std.math; const Linenoise = @import("main.zig").Linenoise; const History = @import("history.zig").History; const unicode = @import("unicode.zig"); const width = unicode.width; const term = @import("term.zig"); const getColumns = term.getColumns; const key_tab = 9; const key_esc = 27; const Bias = enum { left, right, }; fn binarySearchBestEffort( comptime T: type, key: T, items: []const T, context: anytype, comptime compareFn: fn (context: @TypeOf(context), lhs: T, rhs: T) math.Order, bias: Bias, ) usize { var left: usize = 0; var right: usize = items.len; while (left < right) { // Avoid overflowing in the midpoint calculation const mid = left + (right - left) / 2; // Compare the key with the midpoint element switch (compareFn(context, key, items[mid])) { .eq => return mid, .gt => left = mid + 1, .lt => right = mid, } } // At this point, it is guaranteed that left >= right. In order // for the bias to work, we need to return the exact opposite return switch (bias) { .left => right, .right => left, }; } fn compareLeft(context: []const u8, avail_space: usize, index: usize) math.Order { const width_slice = width(context[0..index]); return math.order(avail_space, width_slice); } fn compareRight(context: []const u8, avail_space: usize, index: usize) math.Order { const width_slice = width(context[index..]); return math.order(width_slice, avail_space); } const StartOrEnd = enum { start, end, }; /// Start mode: Calculates the optimal start position such that /// buf[start..] fits in the available space taking into account /// unicode codepoint widths /// /// xxxxxxxxxxxxxxxxxxxxxxx buf /// [------------------] available_space /// ^ start /// /// End mode: Calculates the optimal end position so that buf[0..end] /// fits /// /// xxxxxxxxxxxxxxxxxxxxxxx buf /// [----------] available_space /// ^ end fn calculateStartOrEnd( allocator: Allocator, comptime mode: StartOrEnd, buf: []const u8, avail_space: usize, ) !usize { // Create a mapping from unicode codepoint indices to buf // indices var map = try std.ArrayListUnmanaged(usize).initCapacity(allocator, buf.len); defer map.deinit(allocator); var utf8 = (try std.unicode.Utf8View.init(buf)).iterator(); while (utf8.nextCodepointSlice()) |codepoint| { map.appendAssumeCapacity(@ptrToInt(codepoint.ptr) - @ptrToInt(buf.ptr)); } const codepoint_start = binarySearchBestEffort( usize, avail_space, map.items, buf, switch (mode) { .start => compareRight, .end => compareLeft, }, // When calculating start or end, if in doubt, choose a // smaller buffer as we don't want to overflow the line. For // calculating start, this means that we would rather have an // index more to the right. switch (mode) { .start => .right, .end => .left, }, ); return map.items[codepoint_start]; } pub const LinenoiseState = struct { allocator: Allocator, ln: *Linenoise, stdin: File, stdout: File, buf: ArrayListUnmanaged(u8) = .{}, prompt: []const u8, pos: usize = 0, old_pos: usize = 0, cols: usize, max_rows: usize = 0, const Self = @This(); pub fn init(ln: *Linenoise, in: File, out: File, prompt: []const u8) Self { return Self{ .allocator = ln.allocator, .ln = ln, .stdin = in, .stdout = out, .prompt = prompt, .cols = getColumns(in, out) catch 80, }; } pub fn browseCompletions(self: *Self) !?u8 { var input_buf: [1]u8 = undefined; var c: ?u8 = null; const fun = self.ln.completions_callback orelse return null; const completions = try fun(self.allocator, self.buf.items); defer { for (completions) |x| self.allocator.free(x); self.allocator.free(completions); } if (completions.len == 0) { try term.beep(); } else { var finished = false; var i: usize = 0; while (!finished) { if (i < completions.len) { // Change to completion nr. i // First, save buffer so we can restore it later const old_buf = self.buf.toOwnedSlice(self.allocator); const old_pos = self.pos; // Show suggested completion self.buf = .{}; try self.buf.appendSlice(self.allocator, completions[i]); self.pos = self.buf.items.len; try self.refreshLine(); // Restore original buffer into state self.buf.deinit(self.allocator); self.buf = ArrayList(u8).fromOwnedSlice(self.allocator, old_buf).moveToUnmanaged(); self.pos = old_pos; } else { // Return to original line try self.refreshLine(); } // Read next key const nread = try self.stdin.read(&input_buf); c = if (nread == 1) input_buf[0] else return error.NothingRead; switch (c.?) { key_tab => { // Next completion i = (i + 1) % (completions.len + 1); if (i == completions.len) try term.beep(); }, key_esc => { // Stop browsing completions, return to buffer displayed // prior to browsing completions if (i < completions.len) try self.refreshLine(); finished = true; }, else => { // Stop browsing completions, potentially use suggested // completion if (i < completions.len) { // Replace buffer with text in the selected // completion self.buf.deinit(self.allocator); self.buf = .{}; try self.buf.appendSlice(self.allocator, completions[i]); self.pos = self.buf.items.len; } finished = true; }, } } } return c; } fn getHint(self: *Self) !?[]const u8 { if (self.ln.hints_callback) |fun| { return try fun(self.allocator, self.buf.items); } return null; } fn refreshSingleLine(self: *Self) !void { var buf = bufferedWriter(self.stdout.writer()); var writer = buf.writer(); const hint = try self.getHint(); defer if (hint) |str| self.allocator.free(str); // Calculate widths const pos = width(self.buf.items[0..self.pos]); const prompt_width = width(self.prompt); const hint_width = if (hint) |str| width(str) else 0; const buf_width = width(self.buf.items); // Don't show hint/prompt when there is no space const show_prompt = prompt_width < self.cols; const display_prompt_width = if (show_prompt) prompt_width else 0; const show_hint = display_prompt_width + hint_width < self.cols; const display_hint_width = if (show_hint) hint_width else 0; // buffer -> display_buf mapping const avail_space = self.cols - display_prompt_width - display_hint_width - 1; const whole_buffer_fits = buf_width <= avail_space; var start: usize = undefined; var end: usize = undefined; if (whole_buffer_fits) { start = 0; end = self.buf.items.len; } else { if (pos < avail_space) { start = 0; end = try calculateStartOrEnd( self.allocator, .end, self.buf.items, avail_space, ); } else { end = self.pos; start = try calculateStartOrEnd( self.allocator, .start, self.buf.items[0..end], avail_space, ); } } const display_buf = self.buf.items[start..end]; // Move cursor to left edge try writer.writeAll("\r"); // Write prompt if (show_prompt) try writer.writeAll(self.prompt); // Write current buffer content if (self.ln.mask_mode) { for (display_buf) |_| { try writer.writeAll("*"); } } else { try writer.writeAll(display_buf); } // Show hints if (show_hint) { if (hint) |str| { try writer.writeAll(str); } } // Erase to the right try writer.writeAll("\x1b[0K"); // Move cursor to original position const cursor_pos = if (pos > avail_space) self.cols - display_hint_width - 1 else display_prompt_width + pos; try writer.print("\r\x1b[{}C", .{cursor_pos}); // Write buffer try buf.flush(); } fn refreshMultiLine(self: *Self) !void { var buf = bufferedWriter(self.stdout.writer()); var writer = buf.writer(); const hint = try self.getHint(); defer if (hint) |str| self.allocator.free(str); // Calculate widths const pos = width(self.buf.items[0..self.pos]); const prompt_width = width(self.prompt); const hint_width = if (hint) |str| width(str) else 0; const buf_width = width(self.buf.items); const total_width = prompt_width + buf_width + hint_width; var rows = (total_width + self.cols - 1) / self.cols; const old_rpos = (prompt_width + self.old_pos + self.cols) / self.cols; const old_max_rows = self.max_rows; if (rows > self.max_rows) { self.max_rows = rows; } // Go to the last row if (old_max_rows > old_rpos) { try writer.print("\x1B[{}B", .{old_max_rows - old_rpos}); } // Clear every row from bottom to top if (old_max_rows > 0) { var j: usize = 0; while (j < old_max_rows - 1) : (j += 1) { try writer.writeAll("\r\x1B[0K\x1B[1A"); } } // Clear the top line try writer.writeAll("\r\x1B[0K"); // Write prompt try writer.writeAll(self.prompt); // Write current buffer content if (self.ln.mask_mode) { for (self.buf.items) |_| { try writer.writeAll("*"); } } else { try writer.writeAll(self.buf.items); } // Show hints if applicable if (hint) |str| { try writer.writeAll(str); } // Reserve a newline if we filled all columns if (self.pos > 0 and self.pos == self.buf.items.len and total_width % self.cols == 0) { try writer.writeAll("\n\r"); rows += 1; if (rows > self.max_rows) { self.max_rows = rows; } } // Move cursor to right position: const rpos = (prompt_width + pos + self.cols) / self.cols; // First, y position (move up if necessary) if (rows > rpos) { try writer.print("\x1B[{}A", .{rows - rpos}); } // Then, x position (move right if necessary) const col = (prompt_width + pos) % self.cols; if (col > 0) { try writer.print("\r\x1B[{}C", .{col}); } else { try writer.writeAll("\r"); } self.old_pos = pos; try buf.flush(); } pub fn refreshLine(self: *Self) !void { if (self.ln.multiline_mode) { try self.refreshMultiLine(); } else { try self.refreshSingleLine(); } } pub fn editInsert(self: *Self, c: []const u8) !void { try self.buf.resize(self.allocator, self.buf.items.len + c.len); if (self.buf.items.len > 0 and self.pos < self.buf.items.len - c.len) { std.mem.copyBackwards( u8, self.buf.items[self.pos + c.len .. self.buf.items.len], self.buf.items[self.pos .. self.buf.items.len - c.len], ); } std.mem.copy( u8, self.buf.items[self.pos .. self.pos + c.len], c, ); self.pos += c.len; try self.refreshLine(); } fn prevCodepointLen(self: *Self, pos: usize) usize { if (pos >= 1 and @clz(u8, ~self.buf.items[pos - 1]) == 0) { return 1; } else if (pos >= 2 and @clz(u8, ~self.buf.items[pos - 2]) == 2) { return 2; } else if (pos >= 3 and @clz(u8, ~self.buf.items[pos - 3]) == 3) { return 3; } else if (pos >= 4 and @clz(u8, ~self.buf.items[pos - 4]) == 4) { return 4; } else { return 0; } } pub fn editMoveLeft(self: *Self) !void { if (self.pos == 0) return; self.pos -= self.prevCodepointLen(self.pos); try self.refreshLine(); } pub fn editMoveRight(self: *Self) !void { if (self.pos < self.buf.items.len) { const utf8_len = std.unicode.utf8ByteSequenceLength(self.buf.items[self.pos]) catch 1; self.pos += utf8_len; try self.refreshLine(); } } pub fn editMoveWordEnd(self: *Self) !void { if (self.pos < self.buf.items.len) { while (self.pos < self.buf.items.len and self.buf.items[self.pos] == ' ') self.pos += 1; while (self.pos < self.buf.items.len and self.buf.items[self.pos] != ' ') self.pos += 1; try self.refreshLine(); } } pub fn editMoveWordStart(self: *Self) !void { if (self.buf.items.len > 0 and self.pos > 0) { while (self.pos > 0 and self.buf.items[self.pos - 1] == ' ') self.pos -= 1; while (self.pos > 0 and self.buf.items[self.pos - 1] != ' ') self.pos -= 1; try self.refreshLine(); } } pub fn editMoveHome(self: *Self) !void { if (self.pos > 0) { self.pos = 0; try self.refreshLine(); } } pub fn editMoveEnd(self: *Self) !void { if (self.pos < self.buf.items.len) { self.pos = self.buf.items.len; try self.refreshLine(); } } pub const HistoryDirection = enum { next, prev, }; pub fn editHistoryNext(self: *Self, dir: HistoryDirection) !void { if (self.ln.history.hist.items.len > 0) { // Update the current history with the current line const old_index = self.ln.history.current; const current_entry = self.ln.history.hist.items[old_index]; self.ln.history.allocator.free(current_entry); self.ln.history.hist.items[old_index] = try self.ln.history.allocator.dupe(u8, self.buf.items); // Update history index const new_index = switch (dir) { .next => if (old_index < self.ln.history.hist.items.len - 1) old_index + 1 else self.ln.history.hist.items.len - 1, .prev => if (old_index > 0) old_index - 1 else 0, }; self.ln.history.current = new_index; // Copy history entry to the current line buffer self.buf.deinit(self.allocator); self.buf = .{}; try self.buf.appendSlice(self.allocator, self.ln.history.hist.items[new_index]); self.pos = self.buf.items.len; try self.refreshLine(); } } pub fn editDelete(self: *Self) !void { if (self.buf.items.len > 0 and self.pos < self.buf.items.len) { const utf8_len = std.unicode.utf8CodepointSequenceLength(self.buf.items[self.pos]) catch 1; std.mem.copy(u8, self.buf.items[self.pos..], self.buf.items[self.pos + utf8_len ..]); try self.buf.resize(self.allocator, self.buf.items.len - utf8_len); try self.refreshLine(); } } pub fn editBackspace(self: *Self) !void { if (self.buf.items.len == 0 or self.pos == 0) return; const len = self.prevCodepointLen(self.pos); std.mem.copy(u8, self.buf.items[self.pos - len ..], self.buf.items[self.pos..]); self.pos -= len; try self.buf.resize(self.allocator, self.buf.items.len - len); try self.refreshLine(); } pub fn editSwapPrev(self: *Self) !void { const prev_len = self.prevCodepointLen(self.pos); const prevprev_len = self.prevCodepointLen(self.pos - prev_len); if (prev_len == 0 or prevprev_len == 0) return; var tmp: [4]u8 = undefined; std.mem.copy(u8, &tmp, self.buf.items[self.pos - (prev_len + prevprev_len) .. self.pos - prev_len]); std.mem.copy(u8, self.buf.items[self.pos - (prev_len + prevprev_len) ..], self.buf.items[self.pos - prev_len .. self.pos]); std.mem.copy(u8, self.buf.items[self.pos - prevprev_len ..], tmp[0..prevprev_len]); try self.refreshLine(); } pub fn editDeletePrevWord(self: *Self) !void { if (self.buf.items.len > 0 and self.pos > 0) { const old_pos = self.pos; while (self.pos > 0 and self.buf.items[self.pos - 1] == ' ') self.pos -= 1; while (self.pos > 0 and self.buf.items[self.pos - 1] != ' ') self.pos -= 1; const diff = old_pos - self.pos; const new_len = self.buf.items.len - diff; std.mem.copy(u8, self.buf.items[self.pos..new_len], self.buf.items[old_pos..]); try self.buf.resize(self.allocator, new_len); try self.refreshLine(); } } pub fn editKillLineForward(self: *Self) !void { try self.buf.resize(self.allocator, self.pos); try self.refreshLine(); } pub fn editKillLineBackward(self: *Self) !void { const new_len = self.buf.items.len - self.pos; std.mem.copy(u8, self.buf.items, self.buf.items[self.pos..]); self.pos = 0; try self.buf.resize(self.allocator, new_len); try self.refreshLine(); } };
src/state.zig
const std = @import("std"); const fs = std.fs; const mem = std.mem; const ascii = std.ascii; const log = std.log; const web = @import("zhp.zig"); const responses = web.responses; const Datetime = web.datetime.Datetime; pub var default_stylesheet = @embedFile("templates/style.css"); pub const IndexHandler = struct { pub fn get(self: *IndexHandler, request: *web.Request, response: *web.Response) !void { try response.stream.writeAll( \\No routes are defined \\Please add a list of routes in your main zig file. ); } }; pub const ServerErrorHandler = struct { const TemplateContext = struct { style: []const u8, request: *web.Request, }; const template = web.template.FileTemplate(TemplateContext , "templates/error.html"); server_request: *web.ServerRequest, pub fn dispatch(self: *ServerErrorHandler, request: *web.Request, response: *web.Response) anyerror!void { const app = web.Application.instance.?; response.status = responses.INTERNAL_SERVER_ERROR; // Clear any existing data try response.body.resize(0); if (app.options.debug) { // Split the template on the key const context = TemplateContext{.style=default_stylesheet, .request=request}; inline for (template.sections) |part| { if (part.is("stacktrace")) { // Dump stack trace if (self.server_request.err) |err| { try response.stream.print("error: {s}\n", .{err}); } if (@errorReturnTrace()) |trace| { try std.debug.writeStackTrace( trace.*, &response.stream, response.allocator, try std.debug.getSelfDebugInfo(), .no_color); } } else { try part.render(context, response.stream); } } } else { if (@errorReturnTrace()) |trace| { const stderr = std.io.getStdErr().writer(); const held = std.debug.getStderrMutex().acquire(); defer held.release(); try std.debug.writeStackTrace( trace.*, &stderr, response.allocator, try std.debug.getSelfDebugInfo(), std.debug.detectTTYConfig()); } try response.stream.writeAll("<h1>Server Error</h1>"); } } }; pub const NotFoundHandler = struct { const template = @embedFile("templates/not-found.html"); pub fn dispatch(self: *NotFoundHandler, request: *web.Request, response: *web.Response) !void { response.status = responses.NOT_FOUND; try response.stream.print(template, .{default_stylesheet}); } }; pub fn StaticFileHandler(comptime static_url: []const u8, comptime static_root: []const u8) type { if (!fs.path.isAbsolute(static_url)) { @compileError("The static url must be absolute"); } // TODO: Should the root be checked if it exists? return struct { const Self = @This(); //handler: web.RequestHandler, file: ?std.fs.File = null, start: usize = 0, end: usize = 0, server_request: *web.ServerRequest, pub fn get(self: *Self, request: *web.Request, response: *web.Response) !void { const allocator = response.allocator; const mimetypes = &web.mimetypes.instance.?; // Determine path relative to the url root const rel_path = try fs.path.relative( allocator, static_url, request.path); // Cannot be outside the root folder if (rel_path.len == 0 or rel_path[0] == '.') { return self.renderNotFound(request, response); } const full_path = try fs.path.join(allocator, &[_][]const u8{ static_root, rel_path }); const file = fs.cwd().openFile(full_path, .{.read=true}) catch |err| { // TODO: Handle debug page //log.warn("Static file error: {}", .{err}); return self.renderNotFound(request, response); }; errdefer file.close(); // Get file info const stat = try file.stat(); var modified = Datetime.fromModifiedTime(stat.mtime); // If the file was not modified, return 304 if (self.checkNotModified(request, modified)) { response.status = web.responses.NOT_MODIFIED; file.close(); return; } try response.headers.append("Accept-Ranges", "bytes"); // Set etag header if (self.getETagHeader()) |etag| { try response.headers.append("ETag", etag); } // Set last modified time for caching purposes // NOTE: The modified result doesn't need freed since the response handles that var buf = try response.allocator.alloc(u8, 32); try response.headers.append("Last-Modified", try modified.formatHttpBuf(buf)); // TODO: cache control self.end = stat.size; var size: usize = stat.size; if (request.headers.getOptional("Range")) |range_header| { // As per RFC 2616 14.16, if an invalid Range header is specified, // the request will be treated as if the header didn't exist. // response.status = responses.PARTIAL_CONTENT; if (range_header.len > 8 and mem.startsWith(u8, range_header, "bytes=")) { var it = mem.split(range_header[6..], ","); // Only support the first range const range = mem.trim(u8, it.next().?, " "); var tokens = mem.split(range, "-"); var range_end: ?[]const u8 = null; if (range[0] == '-') { range_end = tokens.next().?; // First one never fails } else { const range_start = tokens.next().?; // First one never fails self.start = std.fmt.parseInt(usize, range_start, 10) catch 0; range_end = tokens.next(); } if (range_end) |value| { const end = std.fmt.parseInt(usize, value, 10) catch 0; if (end > self.start) { // Clients sometimes blindly use a large range to limit their // download size; cap the endpoint at the actual file size. self.end = std.math.min(end, size); } } if (self.start >= size or self.end <= self.start) { // A byte-range-spec is invalid if the last-byte-pos value is present // and less than the first-byte-pos. // https://tools.ietf.org/html/rfc7233#section-2.1 response.status = web.responses.REQUESTED_RANGE_NOT_SATISFIABLE; try response.headers.append("Content-Type", "text/plain"); try response.headers.append("Content-Range", try std.fmt.allocPrint(allocator, "bytes */{}", .{size})); file.close(); return; } // Determine the actual size size = self.end - self.start; if (size != stat.size) { // If it's not the full file se it as a partial response response.status = web.responses.PARTIAL_CONTENT; try response.headers.append("Content-Range", try std.fmt.allocPrint(allocator, "bytes {}-{}/{}", .{ self.start, self.end, size})); } } } // Try to get the content type const content_type = mimetypes.getTypeFromFilename(full_path) orelse "application/octet-stream"; try response.headers.append("Content-Type", content_type); try response.headers.append("Content-Length", try std.fmt.allocPrint(allocator, "{}", .{size})); self.file = file; response.send_stream = true; } // Return true if not modified and a 304 can be returned pub fn checkNotModified(self: *Self, request: *web.Request, mtime: Datetime) bool { // If client sent If-None-Match, use it, ignore If-Modified-Since // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag if (request.headers.getOptional("If-None-Match")) |etag| { return self.checkETagHeader(etag); } // Check if the file was modified since the header // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Modified-Since const v = request.headers.getDefault("If-Modified-Since", ""); const since = Datetime.parseModifiedSince(v) catch return false; return since.gte(mtime); } // Get a hash of the file pub fn getETagHeader(self: *Self) ?[]const u8 { // TODO: This return null; } pub fn checkETagHeader(self: *Self, etag: []const u8) bool { // TODO: Support other formats if (self.getETagHeader()) |tag| { return mem.eql(u8, tag, etag); } return false; } // Stream the file pub fn stream(self: *Self, io: *web.IOStream) !usize { std.debug.assert(self.end > self.start); const total_wrote = self.end - self.start; var bytes_left: usize = total_wrote; if (self.file) |file| { defer file.close(); // Jump to requested range if (self.start > 0) { try file.seekTo(self.start); } // Send it var reader = file.reader(); try io.flush(); while (bytes_left > 0) { // Read into buffer const end = std.math.min(bytes_left, io.out_buffer.len); const n = try reader.read(io.out_buffer[0..end]); if (n == 0) break; // Unexpected EOF bytes_left -= n; try io.flushBuffered(n); } } return total_wrote - bytes_left; } pub fn renderNotFound(self: *Self, request: *web.Request, response: *web.Response) !void { var handler = NotFoundHandler{}; try handler.dispatch(request, response); } }; } /// Handles a websocket connection /// See https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers pub fn WebsocketHandler(comptime Protocol: type) type { return struct { const Self = @This(); // The app will allocate this in the response's allocator buffer accept_key: [28]u8 = undefined, server_request: *web.ServerRequest, pub fn get(self: *Self, request: *web.Request, response: *web.Response) !void { return self.doHandshake(request, response) catch |err| switch (err) { error.BadRequest => self.respondError(web.responses.BAD_REQUEST), error.Forbidden => self.respondError(web.responses.FORBIDDEN), error.UpgradeRequired => self.respondError(web.responses.UPGRADE_REQUIRED), else => err, }; } fn respondError(self: *Self, status: web.responses.Status) void { self.server_request.request.read_finished = true; // Skip reading the body self.server_request.response.disconnect_on_finish = true; self.server_request.response.status = status; } fn doHandshake(self: *Self, request: *web.Request, response: *web.Response) !void { // Check upgrade headers try self.checkUpgradeHeaders(request); // Make sure this is not a cross origin request if (!self.checkOrigin(request)) { return error.Forbidden; // Cross origin websockets are forbidden } // Check websocket version const version = try self.getWebsocketVersion(request); switch (version) { 7, 8, 13 => {}, else => { // Unsupported version // Set header to indicate to the client which versions are supported try response.headers.append("Sec-WebSocket-Version", "7, 8, 13"); return error.UpgradeRequired; } } // Create the accept key const key = try self.getWebsocketAcceptKey(request); // At this point the connection is valid so switch to stream mode try response.headers.append("Connection", "Upgrade"); try response.headers.append("Upgrade", "websocket"); try response.headers.append("Sec-WebSocket-Accept", key); response.send_stream = true; response.status = web.responses.SWITCHING_PROTOCOLS; } fn checkUpgradeHeaders(self: *Self, request: *web.Request) !void { if (!request.headers.eqlIgnoreCase("Upgrade", "websocket")) { log.debug("Cannot only upgrade to 'websocket'", .{}); return error.BadRequest; // Can only upgrade to websocket } // Some proxies/load balancers will mess with the connection header // and browsers also send multiple values here const header = request.headers.getDefault("Connection", ""); var it = std.mem.split(header, ","); while (it.next()) |part| { const conn = std.mem.trim(u8, part, " "); if (ascii.eqlIgnoreCase(conn, "upgrade")) { return; } } // If we didn't find it, give an error log.debug("Connection must be 'upgrade'", .{}); return error.BadRequest; // Connection must be upgrade } /// As a safety measure make sure the origin header matches the host header fn checkOrigin(self: *Self, request: *web.Request) bool { if (@hasDecl(Protocol, "checkOrigin")) { return Protocol.checkOrigin(request); } else { // Version 13 uses "Origin", others use "Sec-Websocket-Origin" var origin = web.url.findHost( if (request.headers.getOptional("Origin")) |o| o else request.headers.getDefault("Sec-Websocket-Origin", "")); const host = request.headers.getDefault("Host", ""); if (origin.len == 0 or host.len == 0 or !ascii.eqlIgnoreCase(origin, host)) { log.debug("Cross origin websockets are not allowed ('{s}' != '{s}')", .{ origin, host }); return false; } return true; } } fn getWebsocketVersion(self: *Self, request: *web.Request) !u8 { const v = request.headers.getDefault("Sec-WebSocket-Version", ""); return std.fmt.parseInt(u8, v, 10) catch error.BadRequest; } fn getWebsocketAcceptKey(self: *Self, request: *web.Request) ![]const u8 { const key = request.headers.getDefault("Sec-WebSocket-Key", ""); if (key.len < 8) { // TODO: Must it be a certain length? log.debug("Insufficent websocket key length", .{}); return error.BadRequest; } var hash = std.crypto.hash.Sha1.init(.{}); var out: [20]u8 = undefined; hash.update(key); hash.update("258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); hash.final(&out); // Encode it return std.base64.standard_encoder.encode(&self.accept_key, &out); } pub fn stream(self: *Self, io: *web.IOStream) !usize { const request = &self.server_request.request; const response = &self.server_request.response; // Always close defer io.close(); // Flush the request try io.flush(); // Delegate handler var protocol = Protocol{ .websocket = web.Websocket{ .request = request, .response = response, .io = io, }, }; try protocol.connected(); self.processStream(&protocol) catch |err| { protocol.websocket.err = err; }; try protocol.disconnected(); return 0; } fn processStream(self: *Self, protocol: *Protocol) !void { const ws = &protocol.websocket; while (true) { const dataframe = try ws.readDataFrame(); if (@hasDecl(Protocol, "onDataFrame")) { // Let the user handle it try protocol.onDataFrame(dataframe); } else { switch (dataframe.header.opcode) { .Text => try protocol.onMessage(dataframe.data, false), .Binary => try protocol.onMessage(dataframe.data, true), .Ping => { _ = try ws.writeMessage(.Pong, ""); }, .Pong => { _ = try ws.writeMessage(.Ping, ""); }, .Close => { try ws.close(1000); break; // Client requsted close }, else => return error.UnexpectedOpcode, } } } } }; }
src/handlers.zig
const std = @import("std"); const clap = @import("clap"); const Uuid = @import("uuid"); pub fn main() anyerror!void { const stderr = std.io.getStdErr().writer(); const stdout = std.io.getStdOut().writer(); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer if (gpa.deinit()) std.fmt.format(stderr, "WARNING: memory leak!\n", .{}) catch unreachable; const allocator = gpa.allocator(); const nanos = std.time.nanoTimestamp(); var rng = std.rand.DefaultPrng.init(@bitCast(u64, @truncate(i64, nanos))); const random = rng.random(); var clock = Uuid.Clock.init(random); const params = comptime [_]clap.Param(clap.Help){ clap.parseParam("-h, --help Display this help and exit.") catch unreachable, clap.parseParam("-v, --version <v> UUID version") catch unreachable, clap.parseParam("-d, --domain <d> Domain (for v3 & v5)") catch unreachable, clap.parseParam("-n, --number <n> Number of UUIDs to generate (default 1)") catch unreachable, clap.parseParam("-p, --print Print generated UUIDs") catch unreachable, }; var args = try clap.parse(clap.Help, &params, .{}); defer args.deinit(); if (args.flag("--help")) { try clap.help(stdout, &params); return; } const version_flag = args.option("--version") orelse { try std.fmt.format(stderr, "ERROR: version is required\n", .{}); std.process.exit(1); }; const version = std.fmt.parseUnsigned(u4, version_flag, 10) catch |err| { try std.fmt.format(stderr, "ERROR: error parsing version: {s}\n", .{@errorName(err)}); std.process.exit(1); }; var source: Source = switch (version) { 1 => .{ .v1 = Uuid.v1.Source.init(&clock, Uuid.v1.randomNode(random)) }, 3 => .{ .v3 = Uuid.v3.Source.init(Uuid.namespace.dns) }, 4 => .{ .v4 = Uuid.v4.Source.init(random) }, 5 => .{ .v5 = Uuid.v5.Source.init(Uuid.namespace.dns) }, 6 => .{ .v6 = Uuid.v6.Source.init(&clock, random) }, 7 => .{ .v7 = Uuid.v7.Source.init(random) }, else => { try std.fmt.format(stderr, "ERROR: unsupported version\n", .{}); std.process.exit(1); }, }; const domain = args.option("--domain") orelse "www.example.com"; const number = if (args.option("--number")) |flag| try std.fmt.parseUnsigned(usize, flag, 10) else 1; const print = args.flag("--print"); var print_buffer = try allocator.alloc(Uuid, if (print) number else 0); defer allocator.free(print_buffer); var timer = try std.time.Timer.start(); var i: usize = 0; while (i < number) : (i += 1) { const uuid = source.create(domain); if (print) { print_buffer[i] = uuid; } } const duration = timer.read(); if (print) { for (print_buffer) |uuid| { try std.fmt.format(stdout, "{}\n", .{uuid}); } } else { const duration_per_uuid = @floatToInt(u64, @intToFloat(f64, duration) / @intToFloat(f64, number)); try std.fmt.format(stdout, "{d} UUIDs in {} = {}/UUID\n", .{ number, std.fmt.fmtDuration(duration), std.fmt.fmtDuration(duration_per_uuid) }); } } pub const Source = union(enum) { v1: Uuid.v1.Source, v3: Uuid.v3.Source, v4: Uuid.v4.Source, v5: Uuid.v5.Source, v6: Uuid.v6.Source, v7: Uuid.v7.Source, pub fn create(self: *Source, name: []const u8) Uuid { return switch (self.*) { .v1 => |src| src.create(), .v3 => |src| src.create(name), .v4 => |src| src.create(), .v5 => |src| src.create(name), .v6 => |src| src.create(), .v7 => |src| src.create(), }; } };
examples/bench/src/main.zig
const sf = @import("../sfml.zig"); const VertexBuffer = @This(); pub const Usage = enum(c_uint) { Static = 0, Dynamic = 1, Stream = 2 }; // Constructors/destructors /// Creates a vertex buffer of a given size. Specify its usage and the primitive type. pub fn createFromSlice(vertices: []const sf.graphics.Vertex, primitive: sf.graphics.PrimitiveType, usage: Usage) !VertexBuffer { var ptr = sf.c.sfVertexBuffer_create(@truncate(c_uint, vertices.len), @enumToInt(primitive), @enumToInt(usage)) orelse return sf.Error.nullptrUnknownReason; if (sf.c.sfVertexBuffer_update(ptr, @ptrCast([*]const sf.c.sfVertex, @alignCast(4, vertices.ptr)), @truncate(c_uint, vertices.len), 0) != 1) return sf.Error.resourceLoadingError; return VertexBuffer{ ._ptr = ptr }; } /// Destroyes this vertex buffer pub fn destroy(self: *VertexBuffer) void { sf.c.sfVertexBuffer_destroy(self._ptr); } // Getters/setters and methods /// Gets the vertex count of this vertex buffer pub fn getVertexCount(self: VertexBuffer) usize { return sf.c.sfVertexBuffer_getVertexCount(self._ptr); } /// Gets the primitive type of this vertex buffer pub fn getPrimitiveType(self: VertexBuffer) sf.graphics.PrimitiveType { return @intToEnum(sf.graphics.PrimitiveType, sf.c.sfVertexBuffer_getPrimitiveType(self._ptr)); } /// Gets the usage of this vertex buffer pub fn getUsage(self: VertexBuffer) Usage { return @intToEnum(Usage, sf.c.sfVertexBuffer_getUsage(self._ptr)); } /// Tells whether or not vertex buffers are available in the system pub fn isAvailable() bool { return sf.c.sfVertexBuffer_isAvailable() != 0; } /// Pointer to the csfml structure _ptr: *sf.c.sfVertexBuffer, test "VertexBuffer: sane getters and setters" { const tst = @import("std").testing; const va_slice = [_]sf.graphics.Vertex{ .{ .position = .{ .x = -1, .y = 0 }, .color = sf.graphics.Color.Red }, .{ .position = .{ .x = 1, .y = 0 }, .color = sf.graphics.Color.Green }, .{ .position = .{ .x = -1, .y = 1 }, .color = sf.graphics.Color.Blue }, }; var va = try createFromSlice(va_slice[0..], sf.graphics.PrimitiveType.Triangles, Usage.Static); defer va.destroy(); try tst.expectEqual(@as(usize, 3), va.getVertexCount()); try tst.expectEqual(sf.graphics.PrimitiveType.Triangles, va.getPrimitiveType()); try tst.expectEqual(Usage.Static, va.getUsage()); }
src/sfml/graphics/VertexBuffer.zig
const std = @import("std"); const util = @import("aoc_util"); const print = std.debug.print; const fmt = std.fmt; const mem = std.mem; const DiagProperties = struct{ entries: u32, gamma: u32, epsilon: u32, heatmap: [12]u32 = [12]u32{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, }; const SubDiag = struct{ power_consumption: i128, O2_gen_rating: u32, CO2_scrub_rating: u32 }; pub fn main() !void { //pull input values from the file const file_input: []u8 = try util.getInputLines(3, 0x4FFF); //init diag properties struct var properties = DiagProperties{ .entries = 0, .gamma = 0, .epsilon = 0}; var subStatus = SubDiag{ .power_consumption = 0, .O2_gen_rating = 0, .CO2_scrub_rating = 0 }; subStatus.power_consumption = try part1(file_input, &properties); //try part2(file_input, &properties, &subStatus); print("---Part 1 result---\n", .{}); print("Result: {d}\n", .{subStatus.power_consumption}); print("Entries: {d}, Gamma: {b}, Epsilon: {b}\n", .{properties.entries, properties.gamma, properties.epsilon}); print("---Part 2 result---\n Does not currently work\n", .{}); print("Result: {d}\n", .{subStatus.O2_gen_rating * subStatus.CO2_scrub_rating}); print("O2 Generator rating: {d}, CO2 scrubber rating: {d}\n", .{subStatus.O2_gen_rating, subStatus.CO2_scrub_rating}); } pub fn part1(input: []u8, properties: *DiagProperties) !i128{ // initialize the count for the number of input lines/entries var num_count: u32 = 0; // initialize the array to count how many 1's are in each bit // of the input lines var num_bin_one: [12]u32 = [12]u32{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; //mem.set(u32, num_bin_one, 0); const bitmask = [_]u16{ 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080, 0x0100, 0x0200, 0x0400, 0x0800}; var epsilon_rate : u32 = 0; var gamma_rate : u32 = 0; //pull and tokenize the file input //const input: []u8 = try util.getInputLines(3, 0x4FFF); var binary_power = mem.tokenize(u8, input, "\n"); while(binary_power.next()) |power_str| : (num_count += 1){ //parse the line as a binary number: var power = try fmt.parseInt(u16, power_str, 2); for(num_bin_one) |_ , bit|{ if (power & bitmask[bit] != 0) { num_bin_one[bit] += 1; } } } for(num_bin_one) |value, i|{ if(value > (num_count/2)){ gamma_rate |= bitmask[i]; }else{ epsilon_rate |= bitmask[i]; } properties.heatmap[i] = num_bin_one[i]; } properties.entries = num_count; properties.gamma = gamma_rate; properties.epsilon = epsilon_rate; return gamma_rate * epsilon_rate; } const DiagValue = struct{ CO2_valid: bool = true, O2_valid: bool = true, value: u16 }; pub fn part2(input: []u8, properties: *DiagProperties, subStatus: *SubDiag) !void{ var gen_alloc = std.heap.GeneralPurposeAllocator(.{}){}; const bitmask = [_]u16{0x0800, 0x0400, 0x0200, 0x0100, 0x0080, 0x0040, 0x0020, 0x0010, 0x0008, 0x0004, 0x0002, 0x0001, }; //heatmap[0] is the number of 1's present in the numbers valid for O2 //heatmap[1] is the number of 1's present in the numbers valid for CO2 var heatmap = [_]u16{@intCast(u16, properties.heatmap[11]), @intCast(u16, properties.heatmap[11])}; //initialize array list of diag numbers and array indicies var diag_list = std.ArrayList(DiagValue).init(gen_alloc.allocator()); defer diag_list.deinit(); //tokenize and parse the input into diag list var binary_diag = mem.tokenize(u8, input, "\n"); while(binary_diag.next()) |diag_str| { var value = try fmt.parseInt(u16, diag_str, 2); try diag_list.append(DiagValue{.value = value}); } var O2_found: bool = false; var CO2_found: bool = false; var numCO2Valid = properties.entries; var numO2Valid = properties.entries; //cycle through each bit bitCycle: for(bitmask) |mask, i|{ print("\nchecking bit {d}\n", .{12 - i}); //determine the Bits that we're comparing to const O2_Bit: bool = (heatmap[0] >= (numO2Valid/2)); const CO2_Bit: bool = (heatmap[1] <= (numCO2Valid/2)); print("O2_Bit: {}, CO2_Bit: {}\n", .{O2_Bit, CO2_Bit}); //cycle through each number in the input for(diag_list.items) |*item|{ var bitMatch: bool = undefined; //if O2 number hasn't been found, check this entry if(!O2_found){ if(item.O2_valid){ print("checking value for O2: {b} ", .{item.value}); if(O2_Bit){ bitMatch = (item.value & mask) != 0; }else{ bitMatch = (item.value | (~mask)) != 0; } if(numO2Valid == 1){ O2_found = true; subStatus.O2_gen_rating = item.value; }else if(!bitMatch){ print("value failed!\n", .{}); item.O2_valid = bitMatch; numO2Valid -= 1; }else{ print("\n", .{}); } } } //if CO2 number hasn't been found, check this entry. if(!CO2_found){ if(item.CO2_valid){ print("checking value for CO2: {b} ", .{item.value}); if(CO2_Bit){ bitMatch = (item.value & mask) != 0; }else{ bitMatch = (item.value | (~mask)) != 0; } if(numCO2Valid == 1){ CO2_found = true; subStatus.CO2_scrub_rating = item.value; }else if(!bitMatch){ print("value failed!\n", .{}); item.CO2_valid = bitMatch; numCO2Valid -= 1; }else{ print("\n", .{}); } } } //break if we've found both desired numbers if(CO2_found and O2_found){ break :bitCycle; } } //determine new heatmap values heatmap[0] = 0; heatmap[1] = 0; // we shouldn't get through the previous for loop on bit 11 without // getting something for the ratings if(i == 11) break; for(diag_list.items) |item|{ if(!O2_found){ if(item.O2_valid){ if(item.value & bitmask[i + 1] != 0){ heatmap[0] += 1; } } } if(!CO2_found){ if(item.CO2_valid){ if(item.value & bitmask[i + 1] != 0){ heatmap[1] += 1; } } } if(!CO2_found){ } } } }
src/day-03/binary-diag.zig
const std = @import("std"); const math = @import("std").math; const fs = @import("std").fs; const io = @import("std").io; const rand = @import("std").rand; const warn = @import("std").debug.warn; const c_allocator = @import("std").heap.c_allocator; //float_type ft const ft = f64; fn Vec(comptime T: type) type { return struct { x: T, y: T, z: T, pub fn init(x: T, y: T, z: T) Vec(T) { return Vec(T){ .x = x, .y = y, .z = z, }; } pub fn add(self: Vec(T), other: Vec(T)) Vec(T) { return Vec(T).init(self.x + other.x, self.y + other.y, self.z + other.z); } pub fn sub(self: Vec(T), other: Vec(T)) Vec(T) { return Vec(T).init(self.x - other.x, self.y - other.y, self.z - other.z); } pub fn mul(self: Vec(T), other: Vec(T)) Vec(T) { return Vec(T).init(self.x * other.x, self.y * other.y, self.z * other.z); } pub fn scale(self: Vec(T), scaling: T) Vec(T) { return Vec(T).init(self.x * scaling, self.y * scaling, self.z * scaling); } pub fn dot(self: Vec(T), other: Vec(T)) T { return self.x * other.x + self.y * other.y + self.z * other.z; } pub fn cross(self: Vec(T), other: Vec(T)) Vec(T) { return Vec(T).init(self.y * other.z - self.z * other.y, self.z * other.x - self.x * other.z, self.x * other.y - self.y * other.x); } pub fn norm(self: Vec(T)) Vec(T) { const factor = 1.0 / math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z); return Vec(T).init(self.x * factor, self.y * factor, self.z * factor); } }; } const Refl_t = enum { DIFF, SPEC, REFR, }; fn Ray(comptime T: type) type { return struct { o: Vec(T), d: Vec(T), pub fn init(o: Vec(T), d: Vec(T)) Ray(T) { return Ray(T){ .o = o, .d = d, }; } }; } fn Sphere(comptime T: type) type { return struct { rad: T, p: Vec(T), e: Vec(T), c: Vec(T), refl: Refl_t, pub fn init(rad: T, p: Vec(T), e: Vec(T), c: Vec(T), refl: Refl_t) Sphere(T) { return Sphere(T){ .rad = rad, .p = p, .e = e, .c = c, .refl = refl, }; } pub fn intersect(self: Sphere(T), r: Ray(T)) T { const op = self.p.sub(r.o); const eps: T = 1e-4; const b = op.dot(r.d); var det = b * b - op.dot(op) + self.rad * self.rad; if (det < 0.0) { return 0.0; } else { det = math.sqrt(det); } const t1 = b - det; if (t1 > eps) { return t1; } else { const t2 = b + det; if (t2 > eps) { return t2; } else { return 0.0; } } } }; } const spheres = [_]Sphere(ft){ Sphere(ft).init(1.0e5, Vec(ft).init(1.0e5 + 1.0, 40.8, 81.6), Vec(ft).init(0, 0, 0), Vec(ft).init(0.75, 0.25, 0.25), Refl_t.DIFF), //Leftt Sphere(ft).init(1.0e5, Vec(ft).init(-1.0e5 + 99.0, 40.8, 81.6), Vec(ft).init(0, 0, 0), Vec(ft).init(0.25, 0.25, 0.75), Refl_t.DIFF), //Rght Sphere(ft).init(1.0e5, Vec(ft).init(50.0, 40.8, 1.0e5), Vec(ft).init(0, 0, 0), Vec(ft).init(0.75, 0.75, 0.75), Refl_t.DIFF), //Back Sphere(ft).init(1.0e5, Vec(ft).init(50.0, 40.8, -1.0e5 + 170.0), Vec(ft).init(0, 0, 0), Vec(ft).init(0, 0, 0), Refl_t.DIFF), //Frnt Sphere(ft).init(1.0e5, Vec(ft).init(50.0, 1.0e5, 81.6), Vec(ft).init(0, 0, 0), Vec(ft).init(0.75, 0.75, 0.75), Refl_t.DIFF), //Botm Sphere(ft).init(1.0e5, Vec(ft).init(50.0, -1.0e5 + 81.6, 81.6), Vec(ft).init(0, 0, 0), Vec(ft).init(0.75, 0.75, 0.75), Refl_t.DIFF), //Top Sphere(ft).init(16.5, Vec(ft).init(27.0, 16.5, 47.0), Vec(ft).init(0, 0, 0), Vec(ft).init(0.999, 0.999, 0.999), Refl_t.SPEC), //Mirr Sphere(ft).init(16.5, Vec(ft).init(73.0, 16.5, 78.0), Vec(ft).init(0, 0, 0), Vec(ft).init(0.999, 0.999, 0.999), Refl_t.REFR), //Glas Sphere(ft).init(600.0, Vec(ft).init(50.0, 681.6 - 0.27, 81.6), Vec(ft).init(12.0, 12.0, 12.0), Vec(ft).init(0, 0, 0), Refl_t.DIFF), //Lite }; pub fn clamp(x: var) @TypeOf(x) { if (x < 0.0) { return 0.0; } else if (x > 1.0) { return 1.0; } else { return x; } } pub fn toInt(x: var) i32 { return @floatToInt(i32, math.pow(@TypeOf(x), clamp(x), 1.0 / 2.2) * 255.0 + 0.5); } pub fn intersect(comptime T: type, r: Ray(T), t: *T, id: *usize) bool { const inf = 1.0e20; t.* = inf; for (spheres) |sphere, i| { const d = sphere.intersect(r); if ((d != 0.0) and (d < t.*)) { t.* = d; id.* = i; } } return t.* < inf; } pub fn radiance(comptime T: type, r: Ray(T), depth: usize, random: *rand.Random) Vec(T) { var t: T = 0.0; var id: usize = 0; if (!intersect(T, r, &t, &id)) { return Vec(T).init(0.0, 0.0, 0.0); } const obj = spheres[id]; const x = r.o.add(r.d.scale(t)); const n = x.sub(obj.p).norm(); const nl = if (n.dot(r.d) < 0) n else n.scale(-1); var f = obj.c; const p = if ((f.x > f.y) and (f.x > f.z)) f.x else if (f.y > f.z) f.y else f.z; if (depth > 4) { if ((random.float(T) < p) and depth < 10) { f = f.scale(1.0 / p); } else { return Vec(T).init(obj.e.x, obj.e.y, obj.e.z); } } if (obj.refl == Refl_t.DIFF) { const r1 = 2.0 * math.pi * random.float(T); const r2 = random.float(T); const r2s = math.sqrt(r2); const w = nl; const u = (if (math.fabs(w.x) > 0.1) Vec(T).init(0.0, 1.0, 0.0) else Vec(T).init(1.0, 0.0, 0.0)).cross(w).norm(); const v = w.cross(u); const d = u.scale(math.cos(r1) * r2s).add(v.scale(math.sin(r1) * r2s)).add(w.scale(math.sqrt(1.0 - r2))).norm(); return obj.e.add(f.mul(radiance(T, Ray(T).init(x, d), depth + 1, random))); } else if (obj.refl == Refl_t.SPEC) { return obj.e.add(f.mul(radiance(T, Ray(T).init(x, r.d.sub(n.scale(2.0 * n.dot(r.d)))), depth + 1, random))); } const reflRay = Ray(T).init(x, (r.d.sub(n.scale(2.0 * n.dot(r.d))))); const into = n.dot(nl) > 0; const nc: T = 1.0; const nt: T = 1.5; const nnt = if (into) nc / nt else nt / nc; const ddn = r.d.dot(nl); const cos2t = 1.0 - nnt * nnt * (1 - ddn * ddn); if (cos2t < 0.0) { return obj.e.add(f.mul(radiance(T, reflRay, depth + 1, random))); } const factor: T = if (into) 1.0 else -1.0; const tdir = (r.d.scale(nnt).sub(n.scale(factor * (ddn * nnt + math.sqrt(cos2t))))).norm(); const a = nt - nc; const b = nt + nc; const c = 1.0 - (if (into) -ddn else tdir.dot(n)); const R0 = a * a / (b * b); const Re = R0 + (1 - R0) * c * c * c * c * c; const Tr = 1.0 - Re; const P = 0.25 + 0.5 * Re; const RP = Re / P; const TP = Tr / (1.0 - P); const multi1 = if (random.float(T) < P) radiance(T, reflRay, depth + 1, random).scale(RP) else radiance(T, Ray(T).init(x, tdir), depth + 1, random).scale(TP); const multi2 = radiance(T, reflRay, depth + 1, random).scale(Re).add(radiance(T, Ray(T).init(x, tdir), depth + 1, random).scale(Tr)); const multi = if (depth > 2) multi1 else multi2; return obj.e.add(f.mul(multi)); } pub fn main() !void { var prng = rand.DefaultPrng.init(0); var random = prng.random; const w: usize = 100; const h: usize = 100; const samps = 5; const cam = Ray(ft).init(Vec(ft).init(50, 52, 295.6), Vec(ft).init(0, -0.042612, -1).norm()); const cx = Vec(ft).init(@intToFloat(f64, w) * 0.5135 / @intToFloat(f64, h), 0.0, 0.0); const cy = (cx.cross(cam.d)).norm().scale(0.5135); var c = try c_allocator.alloc(Vec(ft), w * h); defer c_allocator.free(c); for (c) |*item| { item.* = Vec(ft).init(0.0, 0.0, 0.0); } var y: usize = 0; var r = Vec(ft).init(0.0, 0.0, 0.0); while (y < h) : (y += 1) { var x: usize = 0; while (x < w) : (x += 1) { const i: usize = (h - y - 1) * w + x; var sy: usize = 0; while (sy < 2) : (sy += 1) { var sx: usize = 0; while (sx < 2) : ({ sx += 1; r = Vec(ft).init(0.0, 0.0, 0.0); }) { var s: usize = 0; while (s < samps) : (s += 1) { const r1 = 2.0 * random.float(ft); const dx = if (r1 < 1.0) math.sqrt(r1) - 1.0 else 1.0 - math.sqrt(2.0 - r1); const r2 = 2.0 * random.float(ft); const dy = if (r2 < 1.0) math.sqrt(r2) - 1.0 else 1.0 - math.sqrt(2.0 - r2); const exp1 = ((@intToFloat(f64, sx) + 0.5 + dx) / 2.0 + @intToFloat(f64, x)) / @intToFloat(f64, w) - 0.5; const exp2 = ((@intToFloat(f64, sy) + 0.5 + dy) / 2.0 + @intToFloat(f64, y)) / @intToFloat(f64, h) - 0.5; var d = cx.scale(exp1).add(cy.scale(exp2)).add(cam.d); const vec = cam.o.add(d.scale(140.0)); const rad = radiance(ft, Ray(ft).init(vec, d.norm()), 0, &random); r = r.add(rad.scale(1.0 / @intToFloat(f64, samps))); } c[i] = c[i].add(Vec(ft).init(clamp(r.x), clamp(r.y), clamp(r.z))).scale(0.25); } } } } var file = try fs.cwd().createFile("image.ppm", .{.truncate = true,}); defer file.close(); var adapter = file.outStream(); var bufferedOutStream =io.bufferedOutStream(adapter); var stream = bufferedOutStream.outStream(); var i: usize = 0; const bits: usize = 255; try stream.print("P3\n{} {}\n{}\n", .{w, h, bits}); var col: usize = 0; while (i < (w * h)) : (i += 1) { try stream.print("{} {} {} ", .{toInt(c[i].x), toInt(c[i].y), toInt(c[i].z)}); col = col + 1; if (col == w) { col = 0; try stream.print("\n", .{}); } } try bufferedOutStream.flush(); }
src/main.zig
extern "c" fn __error() *c_int; pub const _errno = __error; pub extern "c" fn kqueue() c_int; pub extern "c" fn kevent( kq: c_int, changelist: [*]const Kevent, nchanges: c_int, eventlist: [*]Kevent, nevents: c_int, timeout: ?*const timespec, ) c_int; pub extern "c" fn sysctl(name: [*]c_int, namelen: c_uint, oldp: ?*c_void, oldlenp: ?*usize, newp: ?*c_void, newlen: usize) c_int; pub extern "c" fn sysctlbyname(name: [*]const u8, oldp: ?*c_void, oldlenp: ?*usize, newp: ?*c_void, newlen: usize) c_int; pub extern "c" fn sysctlnametomib(name: [*]const u8, mibp: ?*c_int, sizep: ?*usize) c_int; pub extern "c" fn getdirentries(fd: c_int, buf_ptr: [*]u8, nbytes: usize, basep: *i64) usize; pub extern "c" fn getdents(fd: c_int, buf_ptr: [*]u8, nbytes: usize) usize; pub extern "c" fn pipe2(arg0: *[2]c_int, arg1: u32) c_int; pub extern "c" fn preadv(fd: c_int, iov: *const c_void, iovcnt: c_int, offset: usize) isize; pub extern "c" fn pwritev(fd: c_int, iov: *const c_void, iovcnt: c_int, offset: usize) isize; pub extern "c" fn openat(fd: c_int, path: ?[*]const u8, flags: c_int) c_int; pub extern "c" fn setgid(ruid: c_uint, euid: c_uint) c_int; pub extern "c" fn setuid(uid: c_uint) c_int; pub extern "c" fn kill(pid: c_int, sig: c_int) c_int; pub extern "c" fn clock_gettime(clk_id: c_int, tp: *timespec) c_int; pub extern "c" fn clock_getres(clk_id: c_int, tp: *timespec) c_int; /// Renamed from `kevent` to `Kevent` to avoid conflict with function name. pub const Kevent = extern struct { ident: usize, filter: i16, flags: u16, fflags: u32, data: i64, udata: usize, // TODO ext }; pub const pthread_attr_t = extern struct { __size: [56]u8, __align: c_long, }; pub const msghdr = extern struct { msg_name: *u8, msg_namelen: socklen_t, msg_iov: *iovec, msg_iovlen: i32, __pad1: i32, msg_control: *u8, msg_controllen: socklen_t, __pad2: socklen_t, msg_flags: i32, }; pub const Stat = extern struct { dev: u64, ino: u64, nlink: usize, mode: u16, __pad0: u16, uid: u32, gid: u32, __pad1: u32, rdev: u64, atim: timespec, mtim: timespec, ctim: timespec, birthtim: timespec, size: i64, blocks: i64, blksize: isize, flags: u32, gen: u64, __spare: [10]u64, }; pub const timespec = extern struct { tv_sec: isize, tv_nsec: isize, }; pub const dirent = extern struct { d_fileno: usize, d_off: i64, d_reclen: u16, d_type: u8, d_pad0: u8, d_namlen: u16, d_pad1: u16, d_name: [256]u8, }; pub const in_port_t = u16; pub const sa_family_t = u16; pub const sockaddr = extern union { in: sockaddr_in, in6: sockaddr_in6, }; pub const sockaddr_in = extern struct { len: u8, family: sa_family_t, port: in_port_t, addr: [16]u8, zero: [8]u8, }; pub const sockaddr_in6 = extern struct { len: u8, family: sa_family_t, port: in_port_t, flowinfo: u32, addr: [16]u8, scope_id: u32, };
std/c/freebsd.zig
const std = @import("std"); const process = std.process; const Allocator = std.mem.Allocator; pub fn resolveExePath(allocator: *Allocator) ![]const u8 { const args = try std.process.argsAlloc(allocator); defer process.argsFree(allocator, args); // std.debug.print("args[{}]={}\n", .{0, args[0]}); const exe_path = try std.fs.path.resolve(allocator, &[_][]const u8{args[0]}); return exe_path; } pub fn resolveHomePath(allocator: *Allocator, exe_path: []const u8) ![]const u8 { const path = std.fs.path.dirname(exe_path) orelse return error.FileNotFound; return try std.fs.path.resolve(allocator, &[_][]const u8{ path, ".." }); } pub fn resolveTmpPath(allocator: *Allocator, exe_path: []const u8) ![]const u8 { const path = std.fs.path.dirname(exe_path) orelse return error.FileNotFound; return try std.fs.path.resolve(allocator, &[_][]const u8{ path, "../tmp" }); } pub fn resolveSrcPath(allocator: *Allocator, exe_path: []const u8) ![]const u8 { const path = std.fs.path.dirname(exe_path) orelse return error.FileNotFound; return try std.fs.path.resolve(allocator, &[_][]const u8{ path, "../src" }); } pub fn resolveExamplePath(allocator: *Allocator, exe_path: []const u8, example_name: []const u8) ![]const u8 { const path = std.fs.path.dirname(exe_path) orelse return error.FileNotFound; return try std.fs.path.resolve(allocator, &[_][]const u8{ path, "../src", example_name }); } pub fn readTitleFromExample(allocator: *Allocator, src_path: []const u8, example_name: []const u8) ![]const u8 { // read title from main.zig file const main_zig_path = try std.fs.path.resolve(allocator, &[_][]const u8{ src_path, example_name, "main.zig" }); defer allocator.free(main_zig_path); const file = std.fs.openFileAbsolute(main_zig_path, .{ .read = true }) catch { // read title from test.zig file const test_zig_path = try std.fs.path.resolve(allocator, &[_][]const u8{ src_path, example_name, "test.zig" }); defer allocator.free(test_zig_path); const file = std.fs.openFileAbsolute(test_zig_path, .{ .read = true }) catch { // read title from first zig file const example_path = try std.fs.path.resolve(allocator, &[_][]const u8{ src_path, example_name }); defer allocator.free(example_path); var example_dir = try std.fs.cwd().openDir(example_path, .{ .iterate = true }); defer example_dir.close(); var file_name_opt: ?[]const u8 = null; var it = example_dir.iterate(); while (try it.next()) |entry| { if (entry.kind == .File and std.mem.endsWith(u8, entry.name, ".zig")) { file_name_opt = entry.name; break; } } if (file_name_opt) |file_name| { // std.debug.print("util.cgi: first zig file_name={}\n", .{file_name}); const file_zig_path = try std.fs.path.resolve(allocator, &[_][]const u8{ src_path, example_name, file_name }); defer allocator.free(file_zig_path); // std.debug.print("util.cgi: first zig file_zig_path={}\n", .{file_zig_path}); const file = try std.fs.openFileAbsolute(file_zig_path, .{ .read = true }); defer file.close(); return try readTitleFromFile(allocator, file, example_name); } return try readTitleFromFile(allocator, null, example_name); }; defer file.close(); return try readTitleFromFile(allocator, file, example_name); }; defer file.close(); return try readTitleFromFile(allocator, file, example_name); } pub fn readTitleFromFile(allocator: *Allocator, file_opt: ?std.fs.File, example_name: []const u8) ![]const u8 { // std.debug.print("util.zig: file_opt={}\n", .{file_opt}); var title: []u8 = undefined; if (file_opt) |file| { var buffer: [256]u8 = undefined; const bytes_read = try file.readAll(&buffer); const string = buffer[0..bytes_read]; // std.debug.print("util: string={}\n", .{string}); if (bytes_read > 4 and std.mem.startsWith(u8, string, "//! ")) { const opt_i = std.mem.indexOf(u8, string, "\n"); var n = string.len; if (opt_i) |i| { n = i; } // std.debug.print("util: string[4..{}]\n", .{n}); const tmp = string[4..n]; title = try allocator.alloc(u8, tmp.len); std.mem.copy(u8, title, tmp); } else { title = try allocator.alloc(u8, example_name.len); std.mem.copy(u8, title, example_name); } } else { title = try allocator.alloc(u8, example_name.len); std.mem.copy(u8, title, example_name); } // std.debug.print("util: title={}\n", .{title}); return title; }
src/util.zig
const std = @import("std"); const dbg = std.debug.print; const c = @cImport({ @cInclude("uv.h"); }); const mpack = @import("./mpack.zig"); fn zero(val: c_int) !void { if (val != 0) { dbg("the cow jumped over the moon: {}\n", .{val}); return error.TheCowJumpedOverTheMoon; } } fn nonneg(val: anytype) !@TypeOf(val) { if (val < 0) { dbg("the dinner conversation is lively: {}\n", .{val}); return error.TheCowJumpedOverTheMoon; } return val; } fn unconst(comptime T: type, ptr: anytype) T { return @intToPtr(T, @ptrToInt(ptr)); } const Datta = struct { allocator: *std.mem.Allocator, }; fn uv_buf(val: []const u8) c.uv_buf_t { return .{ .base = unconst([*c]u8, val.ptr), .len = val.len }; } fn alloc_cb(handle: [*c]c.uv_handle_t, len: usize, buf: [*c]c.uv_buf_t) callconv(.C) void { var datta = @ptrCast(*Datta, @alignCast(@alignOf(Datta), handle.*.data)); var mem = datta.allocator.alloc(u8, 1024) catch return; buf.* = uv_buf(mem); } fn read_cb(stream: [*c]c.uv_stream_t, len: isize, buf: [*c]const c.uv_buf_t) callconv(.C) void { var datta = @ptrCast(*Datta, @alignCast(@alignOf(Datta), stream.*.data)); dbg("read: {}\n", .{len}); var slice = buf.*.base[0..buf.*.len]; dbg("{s}\n", .{slice}); } pub fn main() !void { var loop: c.uv_loop_t = undefined; try zero(c.uv_loop_init(&loop)); var stdin_pipe: c.uv_pipe_t = undefined; try zero(c.uv_pipe_init(&loop, &stdin_pipe, 0)); var stdin = @ptrCast(*c.uv_stream_t, &stdin_pipe); var stdout_pipe: c.uv_pipe_t = undefined; try zero(c.uv_pipe_init(&loop, &stdout_pipe, 0)); var stdout = @ptrCast(*c.uv_stream_t, &stdout_pipe); const Flags = c.uv_stdio_flags; var uvstdio: [3]c.uv_stdio_container_t = .{ .{ .flags = @intToEnum(Flags, c.UV_CREATE_PIPE | c.UV_READABLE_PIPE), .data = .{ .stream = stdin } }, .{ .flags = @intToEnum(Flags, c.UV_CREATE_PIPE | c.UV_WRITABLE_PIPE), .data = .{ .stream = stdout } }, .{ .flags = @intToEnum(Flags, c.UV_INHERIT_FD), .data = .{ .fd = 2 } }, }; const args = &[_:null]?[*:0]u8{ "nvim", "--embed" }; const yarg = @intToPtr([*c][*c]u8, @ptrToInt(args)); // yarrrg var proc_opt: c.uv_process_options_t = .{ .file = "/usr/local/bin/nvim", .args = yarg, .env = null, .flags = 0, .cwd = null, .stdio_count = 3, .stdio = &uvstdio, .uid = 0, .gid = 0, .exit_cb = null, }; var proc: c.uv_process_t = undefined; var status = c.uv_spawn(&loop, &proc, &proc_opt); dbg("{}\n", .{status}); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const ByteArray = std.ArrayList(u8); var x = ByteArray.init(&gpa.allocator); defer x.deinit(); var encoder = mpack.Encoder(ByteArray.Writer){ .writer = x.writer() }; try encoder.startArray(4); try encoder.putInt(0); // request try encoder.putInt(0); // msgid try encoder.putStr("nvim_get_api_info"); try encoder.startArray(0); var buf = uv_buf(x.items); var len = try nonneg(c.uv_try_write(stdin, &buf, 1)); if (len != buf.len) { dbg("feeel {}\n", .{len}); } var datta = Datta{ .allocator = &gpa.allocator }; stdout.data = &datta; try zero(c.uv_read_start(stdout, alloc_cb, read_cb)); var loopy = c.uv_run(&loop, c.uv_run_mode.UV_RUN_DEFAULT); dbg("loopy: {}\n", .{loopy}); if (c.uv_loop_close(&loop) != 0) { dbg("very error\n", .{}); } return; }
src/io_uv.zig
const std = @import("std"); const eq = std.mem.eql; const print = std.fmt.bufPrint; const util = @import("./util.zig"); const sh = @import("./sh.zig"); const ast = @import("./lang/ast.zig"); const Ast = ast.Ast; const token = @import("./lang/token.zig"); const Token = token.Token; const lexer = @import("./lang/lexer.zig"); const parser = @import("./lang/parser.zig"); const help = @import("./cli/help.zig"); const color = @import("./term/colors.zig"); const Color = color.Color; pub usingnamespace Cmd; pub fn match(arg: []const u8, a1: []const u8, a2: []const u8) bool { return (std.mem.eql(u8, a1, arg) and std.mem.eql(u8, a2, arg)); } pub const Cmd = enum(u8) { const Self = @This(); pub fn exe(self: Self) !void { var a = std.heap.ArenaAllocator.init(std.heap.page_allocator); var alo = a.allocator(); return switch (self) { .run => { // std.debug.print("\x1b[32;1mRun an Idlang/Idldown file or workspace\x1b[0m\n", .{}); // const file = try std.fs.path.resolve(cli.alloc, &[_][]const u8{sc}); // std.debug.print("Found file at {s}", file); // var bf: [2048]u8 = undefined; // _ = try std.io.CountingReader(u8).reader().readAllAlloc(cli.alloc, 2048); // const lx = try lexer.Lexer.init(bf, cli.alloc); // _ = try lx.lex(); // const tokens = try lx.tokenListToString(); // _ = try std.io.getStdOut().writeAll(tokens); // } try token.tokFile(alo, "../../res/test.is"); }, .shell => { std.debug.print("\x1b[32;1mOpen up a base instance of the Idlshell\x1b[0m\n", .{}); const shl = try sh.IdlShell.init(alo); try shl.repl(); }, .help => { std.debug.print("\x1b[32;1mGet help for each subcommand\x1b[0m\n", .{}); help.print_usage(); }, .init => { std.debug.print("\x1b[32;1mInit a new Idlang/Idlsdown workspace/environment\x1b[0m\n", .{}); try token.tokFile(alo, "../../res/test.is"); }, .build => { std.debug.print("\x1b[32;1mBuild an Idlang module/book/workspace/project, or single file to executable/library\x1b[0m\n", .{}); const shell = try sh.IdlShell.init(alo); try shell.repl(); }, .repl => { std.debug.print("\x1b[32;1mOpen up a Idlang interprete/Idl ecosystem interfacer\x1b[0m\n", .{}); const shell = try sh.IdlShell.init(alo); try shell.repl(); }, .id => { std.debug.print("\x1b[32;1mManage your IDs and keys, centrally and across peers\x1b[0m\n", .{}); const shell = try sh.IdlShell.init(alo); // open shell to key manaagement try shell.repl(); }, .guide => { std.debug.print("\x1b[32;1mA guide to how you should; and why you would- use this\x1b[0m\n", .{}); const shell = try sh.IdlShell.init(alo); // open shell to key manaagement try shell.repl(); // Open shell to interactive guide }, .about => { std.debug.print("\x1b[32;1mAbout the Idlang project\x1b[0m\n", .{}); help.print_usage(); // Open pager or something for more in-depth readme }, .config => { std.debug.print("\x1b[32;1mConfigure your Idlang!\x1b[0m\n", .{}); }, else => std.debug.print("\x1b[32;1mUnder development!\x1b[0m\n", .{}), }; } pub fn isCmd(input: []const u8) ?Cmd { inline for (@typeInfo(Cmd).Enum.fields) |c| { if (std.mem.eql(u8, input, c.name)) { return @field(Cmd, c.name); } } return null; } pub fn cmdSubcmd(a: std.mem.Allocator) [2]Cmd { var args = std.process.args(); _ = args.skip(); var cmdm = if ((args.next(a) catch null)) |cmd| cmd else null; var cmds = if ((args.next(a) catch null)) |cmd| cmd else null; std.debug.print("\x1b[32;1m COMMAND = {s}\n,\x1b[34;1m SUBCMD = {s}\n ", .{ cmdm, cmds }); var mcmd = try Cmd.mainCmd(cmdm); var scmd = try Cmd.subCmd(cmds); return .{ mcmd, scmd }; } pub fn mainCmd(ar: []const u8) !Cmd { for (std.meta.FieldEnum(Cmd)) |field| { if (match(ar, field.name, field.name[0])) { const cmd_idx = std.meta.fieldIndex(Cmd, field.name) orelse Cmd.help; return @intToEnum(Cmd, cmd_idx); } else return null; } return null; } pub fn subCmd(self: Cmd, arg: []const u8) Cmd { return switch (self) { .help => for (std.meta.FieldEnum(Cmd)) |field| { if (match(arg, field.name, field.name[0])) { const cmd_idx = std.meta.fieldIndex(Cmd, field.name) orelse Cmd.help; return @intToEnum(Cmd, cmd_idx); } }, else => return null, }; } build, id, run, shell, config, base, page, space, about, guide, help, init, repl, // /// Run an Idlscript or Idldown document with provided settings // run: ?struct { // file: std.fs.File, // compile_opts: anytype, // }, // /// Use the Idl shell and perform configuration // shell: ?struct { // init_cmd: []const u8, // profile: []const u8, // }, // /// Configure and view configuration // config: ?union(enum) { // set: struct { // key: []const u8, // val: []const u8, // }, // get: []const u8, // list, // init, // }, // /// Specifically code-related utils and subcommands // lang: ??union(enum) { lint, lsp }, // /// Configure your knowledge bases // bases: ?union(enum) { // init: struct {}, // delete: []const u8, // switch_to: []const u8, // list: struct { // filters: []const u8 = null, // }, // all: bool, // @"switch": []const u8, // clear, // }, // /// Configure your pages of notes and data and code // pages: ??union(enum) { // add: struct { // name: []const u8, // desc: []const u8, // tags: [][]u8, // }, // remove: []const u8, // list, // clear, // }, // /// Configure your collaborative tooling // spaces: ?union { // add: struct { // name: []const u8, // desc: []const u8, // tags: [][]u8, // }, // remove: []const u8, // list: enum { local, networked }, // clear: enum { all, with_tags }, // }, // /// Initialize some Idl resource // init: ?struct { // name: []const u8, // }, // //// Build an Idlang/Idldown file or project/workspace // build: ?struct { // // //// Get help on the CLI or any specific commands // }, // help: union(enum) { // main, // cmd: []const u8, // color: bool, // }, // //// Create some new resource within a spece/base // new: ?struct {}, // //// Launch the Idl shell to the REPL for Idlang/Idldown // repl: ?struct {}, // //// Launch ID configuration editor for private/public keys and auth // id: ??union(enum) { // keypair: struct {}, // sign: struct {}, // verify: struct {}, // sync: struct {}, // login: struct {}, // }, // //// Launch one of several (to be made) guides on how to use the platform // guide: ?enum(u8) { // how_to, // commands, // idlang, // idldown, // }, // //// About the project // about: ?union { goals: []const u8, description: []const u8 }, // const cli = @This(); }; pub fn Opt() type { return struct { pub const Kind = enum(u2) { short = 1, long = 2 }; kind: Opt.Kind, key: []const u8, flag: bool = true, /// Could genericize this but not necessary? val: ?[]const u8 = null, parent_cmd: *Cmd, pub fn isOpt(s: []const u8) ?Opt.Kind { if (std.mem.startsWith(u8, s, "-")) return Opt.Kind.short else if (std.mem.startsWith(u8, s, "--")) return Opt.kind.long else return null; } /// Queried on the term immediately following an opt, rn naively assuming all such /// opts to be fulfilling values of their prior flaggs pub fn isOptVal(self: Opt, s: []const u8) ?Opt { if (!isOpt(s)) return Opt{ .kind = self.kind, .key = self.key, .parent_cmd = self.parent_cmd, .flag = false, .val = s, }; return null; } pub fn isOptKey(pcmd: *Cmd, s: []const u8) ?Opt { return if (isOpt(s)) |ok| ptp: { return switch (ok) { .short => { break :ptp Opt{ .parent_cmd = pcmd, .kind = .short, .key = s[1..], .val = null }; }, .long => { break :ptp Opt{ .parent_cmd = pcmd, .kind = .long, .key = s[2..], .val = null }; }, }; }; } }; }
src/cli.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/day16.txt"); const BitReader = std.io.BitReader(.Big, std.io.FixedBufferStream([]const u8).Reader); const PacketType = enum { add, mul, min, max, lit, cgt, clt, ceq, }; const BitIter = struct { reader: BitReader, position: usize = 0, part1: u64 = 0, pub fn nextBits(self: *@This(), len: usize) u64 { self.position += len; return self.reader.readBitsNoEof(u64, len) catch unreachable; } pub fn packet(self: *@This()) u64 { const version = self.nextBits(3); const type_id = @intToEnum(PacketType, self.nextBits(3)); self.part1 += version; return switch (type_id) { .lit => self.literal(), .cgt, .clt, .ceq => self.compare(type_id), .add, .mul, .min, .max => self.operator(type_id), }; } pub fn literal(self: *@This()) u64 { var value: u64 = 0; while (true) { const chunk = self.nextBits(5); value <<= 4; value |= chunk & 0xF; if (chunk & 0x10 == 0) break; } return value; } pub fn compare(self: *@This(), type_id: PacketType) u64 { const len_bit = self.nextBits(1); _ = self.nextBits(if (len_bit == 0) 15 else 11); const left = self.packet(); const right = self.packet(); return switch (type_id) { .cgt => @boolToInt(left > right), .clt => @boolToInt(left < right), .ceq => @boolToInt(left == right), else => unreachable, }; } pub fn operator(self: *@This(), type_id: PacketType) u64 { const len_bit = self.nextBits(1); var result: usize = switch (type_id) { .add => 0, .mul => 1, .min => std.math.maxInt(u64), .max => 0, else => unreachable, }; if (len_bit == 0) { const total = self.nextBits(15); const end = self.position + total; while (self.position != end) { const it = self.packet(); switch (type_id) { .add => result += it, .mul => result *= it, .min => result = min(result, it), .max => result = max(result, it), else => unreachable, } } } else { const number = self.nextBits(11); var i: u32 = 0; while (i < number) : (i += 1) { const it = self.packet(); switch (type_id) { .add => result += it, .mul => result *= it, .min => result = min(result, it), .max => result = max(result, it), else => unreachable, } } } return result; } }; pub fn main() void { var timer = std.time.Timer.start() catch unreachable; // convert hex to bytes var bytes: [@divExact(data.len, 2)]u8 = undefined; const result = std.fmt.hexToBytes(&bytes, data) catch unreachable; assert(result.len == bytes.len); // prepare a bit reader stream var buffer = std.io.fixedBufferStream(@as([]const u8, &bytes)); var iter = BitIter{ .reader = std.io.bitReader(.Big, buffer.reader()) }; // process packets recursively const part2 = iter.packet(); const part1 = iter.part1; const time = timer.read(); print("part1={}, part2={} time={}\n", .{ part1, part2, time }); } // 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/day16.zig
usingnamespace @import("root").preamble; pub fn alignDown(comptime t: type, alignment: t, value: t) t { return value - (value % alignment); } pub fn alignUp(comptime t: type, alignment: t, value: t) t { return alignDown(t, alignment, value + alignment - 1); } pub fn isAligned(comptime t: type, alignment: t, value: t) bool { return alignDown(t, alignment, value) == value; } fn sliceAlignCast(comptime t: type, slice: anytype) !(if (std.meta.trait.isConstPtr(@TypeOf(slice.ptr))) []const t else []t) { const alignment = @alignOf(t); const ptr_type = comptime if (std.meta.trait.isConstPtr(@TypeOf(slice.ptr))) [*]const t else [*]t; if (lib.util.isRuntime() // we can't detect alignment of pointer values at comptime, not that it matters anyways and isAligned(usize, alignment, @ptrToInt(slice.ptr)) // base ptr aligned and isAligned(usize, alignment, slice.len)) { // length aligned return @ptrCast( ptr_type, @alignCast(alignment, slice.ptr), )[0..@divExact(slice.len, alignment)]; } return error.NotAligned; } pub fn alignedCopy(comptime t: type, dest: []u8, src: []const u8) void { const dest_aligned = sliceAlignCast(t, dest) catch return std.mem.copy(u8, dest, src); const src_aligned = sliceAlignCast(t, src) catch return std.mem.copy(u8, dest, src); return std.mem.copy(t, dest_aligned, src_aligned); } pub fn alignedFill(comptime t: type, dest: []u8, value: u8) void { const dest_aligned = sliceAlignCast(t, dest) catch return std.mem.set(u8, dest, value); const big_value = @truncate(t, 0x0101010101010101) * @intCast(t, value); return std.mem.set(t, dest_aligned, big_value); } test "alignDown" { std.testing.expect(alignDown(u64, 0x1000, 0x4242) == 0x4000); std.testing.expect(alignDown(u64, 0x1000, 0x1000) == 0x1000); std.testing.expect(alignDown(u64, 0x1000, 0x1FFF) == 0x1000); std.testing.expect(alignDown(u64, 0x1000, 0x2000) == 0x2000); } test "alignUp" { std.testing.expect(alignUp(u64, 0x1000, 0x4242) == 0x5000); std.testing.expect(alignUp(u64, 0x1000, 0x1000) == 0x1000); std.testing.expect(alignUp(u64, 0x1000, 0x1001) == 0x2000); std.testing.expect(alignUp(u64, 0x1000, 0x2000) == 0x2000); } test "isAligned" { std.testing.expect(isAligned(u64, 0x1000, 0x1000)); std.testing.expect(!isAligned(u64, 0x1000, 0x1001)); std.testing.expect(!isAligned(u64, 0x1000, 0x1FFF)); std.testing.expect(isAligned(u64, 0x1000, 0x2000)); }
lib/util/libalign.zig
pub const WSMAN_FLAG_REQUESTED_API_VERSION_1_0 = @as(u32, 0); pub const WSMAN_FLAG_REQUESTED_API_VERSION_1_1 = @as(u32, 1); pub const WSMAN_OPERATION_INFOV1 = @as(u32, 0); pub const WSMAN_OPERATION_INFOV2 = @as(u32, 2864434397); pub const WSMAN_DEFAULT_TIMEOUT_MS = @as(u32, 60000); pub const WSMAN_FLAG_RECEIVE_RESULT_NO_MORE_DATA = @as(u32, 1); pub const WSMAN_FLAG_RECEIVE_FLUSH = @as(u32, 2); pub const WSMAN_FLAG_RECEIVE_RESULT_DATA_BOUNDARY = @as(u32, 4); pub const WSMAN_PLUGIN_PARAMS_MAX_ENVELOPE_SIZE = @as(u32, 1); pub const WSMAN_PLUGIN_PARAMS_TIMEOUT = @as(u32, 2); pub const WSMAN_PLUGIN_PARAMS_REMAINING_RESULT_SIZE = @as(u32, 3); pub const WSMAN_PLUGIN_PARAMS_LARGEST_RESULT_SIZE = @as(u32, 4); pub const WSMAN_PLUGIN_PARAMS_GET_REQUESTED_LOCALE = @as(u32, 5); pub const WSMAN_PLUGIN_PARAMS_GET_REQUESTED_DATA_LOCALE = @as(u32, 6); pub const WSMAN_PLUGIN_PARAMS_SHAREDHOST = @as(u32, 1); pub const WSMAN_PLUGIN_PARAMS_RUNAS_USER = @as(u32, 2); pub const WSMAN_PLUGIN_PARAMS_AUTORESTART = @as(u32, 3); pub const WSMAN_PLUGIN_PARAMS_HOSTIDLETIMEOUTSECONDS = @as(u32, 4); pub const WSMAN_PLUGIN_PARAMS_NAME = @as(u32, 5); pub const WSMAN_PLUGIN_STARTUP_REQUEST_RECEIVED = @as(u32, 0); pub const WSMAN_PLUGIN_STARTUP_AUTORESTARTED_REBOOT = @as(u32, 1); pub const WSMAN_PLUGIN_STARTUP_AUTORESTARTED_CRASH = @as(u32, 2); pub const WSMAN_PLUGIN_SHUTDOWN_SYSTEM = @as(u32, 1); pub const WSMAN_PLUGIN_SHUTDOWN_SERVICE = @as(u32, 2); pub const WSMAN_PLUGIN_SHUTDOWN_IISHOST = @as(u32, 3); pub const WSMAN_PLUGIN_SHUTDOWN_IDLETIMEOUT_ELAPSED = @as(u32, 4); pub const WSMAN_FLAG_SEND_NO_MORE_DATA = @as(u32, 1); //-------------------------------------------------------------------------------- // Section: Types (76) //-------------------------------------------------------------------------------- pub const WSMAN_API = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const WSMAN_SESSION = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const WSMAN_OPERATION = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const WSMAN_SHELL = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const WSMAN_COMMAND = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const WSMAN_DATA_TEXT = extern struct { bufferLength: u32, buffer: ?[*:0]const u16, }; pub const WSMAN_DATA_BINARY = extern struct { dataLength: u32, data: ?*u8, }; pub const WSManDataType = enum(i32) { NONE = 0, TYPE_TEXT = 1, TYPE_BINARY = 2, TYPE_DWORD = 4, }; pub const WSMAN_DATA_NONE = WSManDataType.NONE; pub const WSMAN_DATA_TYPE_TEXT = WSManDataType.TYPE_TEXT; pub const WSMAN_DATA_TYPE_BINARY = WSManDataType.TYPE_BINARY; pub const WSMAN_DATA_TYPE_DWORD = WSManDataType.TYPE_DWORD; pub const WSMAN_DATA = extern struct { type: WSManDataType, Anonymous: extern union { text: WSMAN_DATA_TEXT, binaryData: WSMAN_DATA_BINARY, number: u32, }, }; pub const WSMAN_ERROR = extern struct { code: u32, errorDetail: ?[*:0]const u16, language: ?[*:0]const u16, machineName: ?[*:0]const u16, pluginName: ?[*:0]const u16, }; pub const WSMAN_USERNAME_PASSWORD_CREDS = extern struct { username: ?[*:0]const u16, password: ?[*:0]const u16, }; pub const WSManAuthenticationFlags = enum(i32) { DEFAULT_AUTHENTICATION = 0, NO_AUTHENTICATION = 1, AUTH_DIGEST = 2, AUTH_NEGOTIATE = 4, AUTH_BASIC = 8, AUTH_KERBEROS = 16, AUTH_CREDSSP = 128, AUTH_CLIENT_CERTIFICATE = 32, }; pub const WSMAN_FLAG_DEFAULT_AUTHENTICATION = WSManAuthenticationFlags.DEFAULT_AUTHENTICATION; pub const WSMAN_FLAG_NO_AUTHENTICATION = WSManAuthenticationFlags.NO_AUTHENTICATION; pub const WSMAN_FLAG_AUTH_DIGEST = WSManAuthenticationFlags.AUTH_DIGEST; pub const WSMAN_FLAG_AUTH_NEGOTIATE = WSManAuthenticationFlags.AUTH_NEGOTIATE; pub const WSMAN_FLAG_AUTH_BASIC = WSManAuthenticationFlags.AUTH_BASIC; pub const WSMAN_FLAG_AUTH_KERBEROS = WSManAuthenticationFlags.AUTH_KERBEROS; pub const WSMAN_FLAG_AUTH_CREDSSP = WSManAuthenticationFlags.AUTH_CREDSSP; pub const WSMAN_FLAG_AUTH_CLIENT_CERTIFICATE = WSManAuthenticationFlags.AUTH_CLIENT_CERTIFICATE; pub const WSMAN_AUTHENTICATION_CREDENTIALS = extern struct { authenticationMechanism: u32, Anonymous: extern union { userAccount: WSMAN_USERNAME_PASSWORD_CREDS, certificateThumbprint: ?[*:0]const u16, }, }; pub const WSMAN_OPTION = extern struct { name: ?[*:0]const u16, value: ?[*:0]const u16, mustComply: BOOL, }; pub const WSMAN_OPTION_SET = extern struct { optionsCount: u32, options: ?*WSMAN_OPTION, optionsMustUnderstand: BOOL, }; pub const WSMAN_OPTION_SETEX = extern struct { optionsCount: u32, options: ?*WSMAN_OPTION, optionsMustUnderstand: BOOL, optionTypes: ?*?PWSTR, }; pub const WSMAN_KEY = extern struct { key: ?[*:0]const u16, value: ?[*:0]const u16, }; pub const WSMAN_SELECTOR_SET = extern struct { numberKeys: u32, keys: ?*WSMAN_KEY, }; pub const WSMAN_FRAGMENT = extern struct { path: ?[*:0]const u16, dialect: ?[*:0]const u16, }; pub const WSMAN_FILTER = extern struct { filter: ?[*:0]const u16, dialect: ?[*:0]const u16, }; pub const WSMAN_OPERATION_INFO = extern struct { fragment: WSMAN_FRAGMENT, filter: WSMAN_FILTER, selectorSet: WSMAN_SELECTOR_SET, optionSet: WSMAN_OPTION_SET, reserved: ?*c_void, version: u32, }; pub const WSMAN_OPERATION_INFOEX = extern struct { fragment: WSMAN_FRAGMENT, filter: WSMAN_FILTER, selectorSet: WSMAN_SELECTOR_SET, optionSet: WSMAN_OPTION_SETEX, version: u32, uiLocale: ?[*:0]const u16, dataLocale: ?[*:0]const u16, }; pub const WSManProxyAccessType = enum(i32) { IE_PROXY_CONFIG = 1, WINHTTP_PROXY_CONFIG = 2, AUTO_DETECT = 4, NO_PROXY_SERVER = 8, }; pub const WSMAN_OPTION_PROXY_IE_PROXY_CONFIG = WSManProxyAccessType.IE_PROXY_CONFIG; pub const WSMAN_OPTION_PROXY_WINHTTP_PROXY_CONFIG = WSManProxyAccessType.WINHTTP_PROXY_CONFIG; pub const WSMAN_OPTION_PROXY_AUTO_DETECT = WSManProxyAccessType.AUTO_DETECT; pub const WSMAN_OPTION_PROXY_NO_PROXY_SERVER = WSManProxyAccessType.NO_PROXY_SERVER; pub const WSMAN_PROXY_INFO = extern struct { accessType: u32, authenticationCredentials: WSMAN_AUTHENTICATION_CREDENTIALS, }; pub const WSManSessionOption = enum(i32) { DEFAULT_OPERATION_TIMEOUTMS = 1, MAX_RETRY_TIME = 11, TIMEOUTMS_CREATE_SHELL = 12, TIMEOUTMS_RUN_SHELL_COMMAND = 13, TIMEOUTMS_RECEIVE_SHELL_OUTPUT = 14, TIMEOUTMS_SEND_SHELL_INPUT = 15, TIMEOUTMS_SIGNAL_SHELL = 16, TIMEOUTMS_CLOSE_SHELL = 17, SKIP_CA_CHECK = 18, SKIP_CN_CHECK = 19, UNENCRYPTED_MESSAGES = 20, UTF16 = 21, ENABLE_SPN_SERVER_PORT = 22, MACHINE_ID = 23, LOCALE = 25, UI_LANGUAGE = 26, MAX_ENVELOPE_SIZE_KB = 28, SHELL_MAX_DATA_SIZE_PER_MESSAGE_KB = 29, REDIRECT_LOCATION = 30, SKIP_REVOCATION_CHECK = 31, ALLOW_NEGOTIATE_IMPLICIT_CREDENTIALS = 32, USE_SSL = 33, USE_INTEARACTIVE_TOKEN = 34, }; pub const WSMAN_OPTION_DEFAULT_OPERATION_TIMEOUTMS = WSManSessionOption.DEFAULT_OPERATION_TIMEOUTMS; pub const WSMAN_OPTION_MAX_RETRY_TIME = WSManSessionOption.MAX_RETRY_TIME; pub const WSMAN_OPTION_TIMEOUTMS_CREATE_SHELL = WSManSessionOption.TIMEOUTMS_CREATE_SHELL; pub const WSMAN_OPTION_TIMEOUTMS_RUN_SHELL_COMMAND = WSManSessionOption.TIMEOUTMS_RUN_SHELL_COMMAND; pub const WSMAN_OPTION_TIMEOUTMS_RECEIVE_SHELL_OUTPUT = WSManSessionOption.TIMEOUTMS_RECEIVE_SHELL_OUTPUT; pub const WSMAN_OPTION_TIMEOUTMS_SEND_SHELL_INPUT = WSManSessionOption.TIMEOUTMS_SEND_SHELL_INPUT; pub const WSMAN_OPTION_TIMEOUTMS_SIGNAL_SHELL = WSManSessionOption.TIMEOUTMS_SIGNAL_SHELL; pub const WSMAN_OPTION_TIMEOUTMS_CLOSE_SHELL = WSManSessionOption.TIMEOUTMS_CLOSE_SHELL; pub const WSMAN_OPTION_SKIP_CA_CHECK = WSManSessionOption.SKIP_CA_CHECK; pub const WSMAN_OPTION_SKIP_CN_CHECK = WSManSessionOption.SKIP_CN_CHECK; pub const WSMAN_OPTION_UNENCRYPTED_MESSAGES = WSManSessionOption.UNENCRYPTED_MESSAGES; pub const WSMAN_OPTION_UTF16 = WSManSessionOption.UTF16; pub const WSMAN_OPTION_ENABLE_SPN_SERVER_PORT = WSManSessionOption.ENABLE_SPN_SERVER_PORT; pub const WSMAN_OPTION_MACHINE_ID = WSManSessionOption.MACHINE_ID; pub const WSMAN_OPTION_LOCALE = WSManSessionOption.LOCALE; pub const WSMAN_OPTION_UI_LANGUAGE = WSManSessionOption.UI_LANGUAGE; pub const WSMAN_OPTION_MAX_ENVELOPE_SIZE_KB = WSManSessionOption.MAX_ENVELOPE_SIZE_KB; pub const WSMAN_OPTION_SHELL_MAX_DATA_SIZE_PER_MESSAGE_KB = WSManSessionOption.SHELL_MAX_DATA_SIZE_PER_MESSAGE_KB; pub const WSMAN_OPTION_REDIRECT_LOCATION = WSManSessionOption.REDIRECT_LOCATION; pub const WSMAN_OPTION_SKIP_REVOCATION_CHECK = WSManSessionOption.SKIP_REVOCATION_CHECK; pub const WSMAN_OPTION_ALLOW_NEGOTIATE_IMPLICIT_CREDENTIALS = WSManSessionOption.ALLOW_NEGOTIATE_IMPLICIT_CREDENTIALS; pub const WSMAN_OPTION_USE_SSL = WSManSessionOption.USE_SSL; pub const WSMAN_OPTION_USE_INTEARACTIVE_TOKEN = WSManSessionOption.USE_INTEARACTIVE_TOKEN; pub const WSManCallbackFlags = enum(i32) { END_OF_OPERATION = 1, END_OF_STREAM = 8, SHELL_SUPPORTS_DISCONNECT = 32, SHELL_AUTODISCONNECTED = 64, NETWORK_FAILURE_DETECTED = 256, RETRYING_AFTER_NETWORK_FAILURE = 512, RECONNECTED_AFTER_NETWORK_FAILURE = 1024, SHELL_AUTODISCONNECTING = 2048, RETRY_ABORTED_DUE_TO_INTERNAL_ERROR = 4096, RECEIVE_DELAY_STREAM_REQUEST_PROCESSED = 8192, }; pub const WSMAN_FLAG_CALLBACK_END_OF_OPERATION = WSManCallbackFlags.END_OF_OPERATION; pub const WSMAN_FLAG_CALLBACK_END_OF_STREAM = WSManCallbackFlags.END_OF_STREAM; pub const WSMAN_FLAG_CALLBACK_SHELL_SUPPORTS_DISCONNECT = WSManCallbackFlags.SHELL_SUPPORTS_DISCONNECT; pub const WSMAN_FLAG_CALLBACK_SHELL_AUTODISCONNECTED = WSManCallbackFlags.SHELL_AUTODISCONNECTED; pub const WSMAN_FLAG_CALLBACK_NETWORK_FAILURE_DETECTED = WSManCallbackFlags.NETWORK_FAILURE_DETECTED; pub const WSMAN_FLAG_CALLBACK_RETRYING_AFTER_NETWORK_FAILURE = WSManCallbackFlags.RETRYING_AFTER_NETWORK_FAILURE; pub const WSMAN_FLAG_CALLBACK_RECONNECTED_AFTER_NETWORK_FAILURE = WSManCallbackFlags.RECONNECTED_AFTER_NETWORK_FAILURE; pub const WSMAN_FLAG_CALLBACK_SHELL_AUTODISCONNECTING = WSManCallbackFlags.SHELL_AUTODISCONNECTING; pub const WSMAN_FLAG_CALLBACK_RETRY_ABORTED_DUE_TO_INTERNAL_ERROR = WSManCallbackFlags.RETRY_ABORTED_DUE_TO_INTERNAL_ERROR; pub const WSMAN_FLAG_CALLBACK_RECEIVE_DELAY_STREAM_REQUEST_PROCESSED = WSManCallbackFlags.RECEIVE_DELAY_STREAM_REQUEST_PROCESSED; pub const WSMAN_STREAM_ID_SET = extern struct { streamIDsCount: u32, streamIDs: ?*?PWSTR, }; pub const WSMAN_ENVIRONMENT_VARIABLE = extern struct { name: ?[*:0]const u16, value: ?[*:0]const u16, }; pub const WSMAN_ENVIRONMENT_VARIABLE_SET = extern struct { varsCount: u32, vars: ?*WSMAN_ENVIRONMENT_VARIABLE, }; pub const WSMAN_SHELL_STARTUP_INFO_V10 = extern struct { inputStreamSet: ?*WSMAN_STREAM_ID_SET, outputStreamSet: ?*WSMAN_STREAM_ID_SET, idleTimeoutMs: u32, workingDirectory: ?[*:0]const u16, variableSet: ?*WSMAN_ENVIRONMENT_VARIABLE_SET, }; pub const WSMAN_SHELL_STARTUP_INFO_V11 = extern struct { __AnonymousBase_wsman_L665_C48: WSMAN_SHELL_STARTUP_INFO_V10, name: ?[*:0]const u16, }; pub const WSMAN_SHELL_DISCONNECT_INFO = extern struct { idleTimeoutMs: u32, }; pub const WSManShellFlag = enum(i32) { NO_COMPRESSION = 1, DELETE_SERVER_SESSION = 2, SERVER_BUFFERING_MODE_DROP = 4, SERVER_BUFFERING_MODE_BLOCK = 8, RECEIVE_DELAY_OUTPUT_STREAM = 16, }; pub const WSMAN_FLAG_NO_COMPRESSION = WSManShellFlag.NO_COMPRESSION; pub const WSMAN_FLAG_DELETE_SERVER_SESSION = WSManShellFlag.DELETE_SERVER_SESSION; pub const WSMAN_FLAG_SERVER_BUFFERING_MODE_DROP = WSManShellFlag.SERVER_BUFFERING_MODE_DROP; pub const WSMAN_FLAG_SERVER_BUFFERING_MODE_BLOCK = WSManShellFlag.SERVER_BUFFERING_MODE_BLOCK; pub const WSMAN_FLAG_RECEIVE_DELAY_OUTPUT_STREAM = WSManShellFlag.RECEIVE_DELAY_OUTPUT_STREAM; pub const WSMAN_RECEIVE_DATA_RESULT = extern struct { streamId: ?[*:0]const u16, streamData: WSMAN_DATA, commandState: ?[*:0]const u16, exitCode: u32, }; pub const WSMAN_CONNECT_DATA = extern struct { data: WSMAN_DATA, }; pub const WSMAN_CREATE_SHELL_DATA = extern struct { data: WSMAN_DATA, }; pub const WSMAN_RESPONSE_DATA = extern union { receiveData: WSMAN_RECEIVE_DATA_RESULT, connectData: WSMAN_CONNECT_DATA, createData: WSMAN_CREATE_SHELL_DATA, }; pub const WSMAN_SHELL_COMPLETION_FUNCTION = fn( operationContext: ?*c_void, flags: u32, @"error": ?*WSMAN_ERROR, shell: ?*WSMAN_SHELL, command: ?*WSMAN_COMMAND, operationHandle: ?*WSMAN_OPERATION, data: ?*WSMAN_RESPONSE_DATA, ) callconv(@import("std").os.windows.WINAPI) void; pub const WSMAN_SHELL_ASYNC = extern struct { operationContext: ?*c_void, completionFunction: ?WSMAN_SHELL_COMPLETION_FUNCTION, }; pub const WSMAN_COMMAND_ARG_SET = extern struct { argsCount: u32, args: ?*?PWSTR, }; pub const WSMAN_CERTIFICATE_DETAILS = extern struct { subject: ?[*:0]const u16, issuerName: ?[*:0]const u16, issuerThumbprint: ?[*:0]const u16, subjectName: ?[*:0]const u16, }; pub const WSMAN_SENDER_DETAILS = extern struct { senderName: ?[*:0]const u16, authenticationMechanism: ?[*:0]const u16, certificateDetails: ?*WSMAN_CERTIFICATE_DETAILS, clientToken: ?HANDLE, httpURL: ?[*:0]const u16, }; pub const WSMAN_PLUGIN_REQUEST = extern struct { senderDetails: ?*WSMAN_SENDER_DETAILS, locale: ?[*:0]const u16, resourceUri: ?[*:0]const u16, operationInfo: ?*WSMAN_OPERATION_INFO, shutdownNotification: i32, shutdownNotificationHandle: ?HANDLE, dataLocale: ?[*:0]const u16, }; pub const WSMAN_PLUGIN_RELEASE_SHELL_CONTEXT = fn( shellContext: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) void; pub const WSMAN_PLUGIN_RELEASE_COMMAND_CONTEXT = fn( shellContext: ?*c_void, commandContext: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) void; pub const WSMAN_PLUGIN_STARTUP = fn( flags: u32, applicationIdentification: ?[*:0]const u16, extraInfo: ?[*:0]const u16, pluginContext: ?*?*c_void, ) callconv(@import("std").os.windows.WINAPI) u32; pub const WSMAN_PLUGIN_SHUTDOWN = fn( pluginContext: ?*c_void, flags: u32, reason: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub const WSMAN_PLUGIN_SHELL = fn( pluginContext: ?*c_void, requestDetails: ?*WSMAN_PLUGIN_REQUEST, flags: u32, startupInfo: ?*WSMAN_SHELL_STARTUP_INFO_V11, inboundShellInformation: ?*WSMAN_DATA, ) callconv(@import("std").os.windows.WINAPI) void; pub const WSMAN_PLUGIN_COMMAND = fn( requestDetails: ?*WSMAN_PLUGIN_REQUEST, flags: u32, shellContext: ?*c_void, commandLine: ?[*:0]const u16, arguments: ?*WSMAN_COMMAND_ARG_SET, ) callconv(@import("std").os.windows.WINAPI) void; pub const WSMAN_PLUGIN_SEND = fn( requestDetails: ?*WSMAN_PLUGIN_REQUEST, flags: u32, shellContext: ?*c_void, commandContext: ?*c_void, stream: ?[*:0]const u16, inboundData: ?*WSMAN_DATA, ) callconv(@import("std").os.windows.WINAPI) void; pub const WSMAN_PLUGIN_RECEIVE = fn( requestDetails: ?*WSMAN_PLUGIN_REQUEST, flags: u32, shellContext: ?*c_void, commandContext: ?*c_void, streamSet: ?*WSMAN_STREAM_ID_SET, ) callconv(@import("std").os.windows.WINAPI) void; pub const WSMAN_PLUGIN_SIGNAL = fn( requestDetails: ?*WSMAN_PLUGIN_REQUEST, flags: u32, shellContext: ?*c_void, commandContext: ?*c_void, code: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) void; pub const WSMAN_PLUGIN_CONNECT = fn( requestDetails: ?*WSMAN_PLUGIN_REQUEST, flags: u32, shellContext: ?*c_void, commandContext: ?*c_void, inboundConnectInformation: ?*WSMAN_DATA, ) callconv(@import("std").os.windows.WINAPI) void; pub const WSMAN_AUTHZ_QUOTA = extern struct { maxAllowedConcurrentShells: u32, maxAllowedConcurrentOperations: u32, timeslotSize: u32, maxAllowedOperationsPerTimeslot: u32, }; pub const WSMAN_PLUGIN_AUTHORIZE_USER = fn( pluginContext: ?*c_void, senderDetails: ?*WSMAN_SENDER_DETAILS, flags: u32, ) callconv(@import("std").os.windows.WINAPI) void; pub const WSMAN_PLUGIN_AUTHORIZE_OPERATION = fn( pluginContext: ?*c_void, senderDetails: ?*WSMAN_SENDER_DETAILS, flags: u32, operation: u32, action: ?[*:0]const u16, resourceUri: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) void; pub const WSMAN_PLUGIN_AUTHORIZE_QUERY_QUOTA = fn( pluginContext: ?*c_void, senderDetails: ?*WSMAN_SENDER_DETAILS, flags: u32, ) callconv(@import("std").os.windows.WINAPI) void; pub const WSMAN_PLUGIN_AUTHORIZE_RELEASE_CONTEXT = fn( userAuthorizationContext: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) void; const CLSID_WSMan_Value = @import("../zig.zig").Guid.initString("bced617b-ec03-420b-8508-977dc7a686bd"); pub const CLSID_WSMan = &CLSID_WSMan_Value; const CLSID_WSManInternal_Value = @import("../zig.zig").Guid.initString("7de087a5-5dcb-4df7-bb12-0924ad8fbd9a"); pub const CLSID_WSManInternal = &CLSID_WSManInternal_Value; pub const WSManSessionFlags = enum(i32) { UTF8 = 1, CredUsernamePassword = <PASSWORD>, SkipCACheck = 8192, SkipCNCheck = 16384, UseNoAuthentication = 32768, UseDigest = 65536, UseNegotiate = 131072, UseBasic = 262144, UseKerberos = 524288, NoEncryption = 1048576, UseClientCertificate = 2097152, EnableSPNServerPort = 4194304, UTF16 = 8388608, UseCredSsp = 16777216, SkipRevocationCheck = 33554432, AllowNegotiateImplicitCredentials = 67108864, UseSsl = 134217728, }; pub const WSManFlagUTF8 = WSManSessionFlags.UTF8; pub const WSManFlagCredUsernamePassword = WSManSessionFlags.CredUsernamePassword; pub const WSManFlagSkipCACheck = WSManSessionFlags.SkipCACheck; pub const WSManFlagSkipCNCheck = WSManSessionFlags.SkipCNCheck; pub const WSManFlagUseNoAuthentication = WSManSessionFlags.UseNoAuthentication; pub const WSManFlagUseDigest = WSManSessionFlags.UseDigest; pub const WSManFlagUseNegotiate = WSManSessionFlags.UseNegotiate; pub const WSManFlagUseBasic = WSManSessionFlags.UseBasic; pub const WSManFlagUseKerberos = WSManSessionFlags.UseKerberos; pub const WSManFlagNoEncryption = WSManSessionFlags.NoEncryption; pub const WSManFlagUseClientCertificate = WSManSessionFlags.UseClientCertificate; pub const WSManFlagEnableSPNServerPort = WSManSessionFlags.EnableSPNServerPort; pub const WSManFlagUTF16 = WSManSessionFlags.UTF16; pub const WSManFlagUseCredSsp = WSManSessionFlags.UseCredSsp; pub const WSManFlagSkipRevocationCheck = WSManSessionFlags.SkipRevocationCheck; pub const WSManFlagAllowNegotiateImplicitCredentials = WSManSessionFlags.AllowNegotiateImplicitCredentials; pub const WSManFlagUseSsl = WSManSessionFlags.UseSsl; pub const WSManEnumFlags = enum(i32) { NonXmlText = 1, ReturnObject = 0, ReturnEPR = 2, ReturnObjectAndEPR = 4, // HierarchyDeep = 0, this enum value conflicts with ReturnObject HierarchyShallow = 32, HierarchyDeepBasePropsOnly = 64, // AssociatedInstance = 0, this enum value conflicts with ReturnObject AssociationInstance = 128, }; pub const WSManFlagNonXmlText = WSManEnumFlags.NonXmlText; pub const WSManFlagReturnObject = WSManEnumFlags.ReturnObject; pub const WSManFlagReturnEPR = WSManEnumFlags.ReturnEPR; pub const WSManFlagReturnObjectAndEPR = WSManEnumFlags.ReturnObjectAndEPR; pub const WSManFlagHierarchyDeep = WSManEnumFlags.ReturnObject; pub const WSManFlagHierarchyShallow = WSManEnumFlags.HierarchyShallow; pub const WSManFlagHierarchyDeepBasePropsOnly = WSManEnumFlags.HierarchyDeepBasePropsOnly; pub const WSManFlagAssociatedInstance = WSManEnumFlags.ReturnObject; pub const WSManFlagAssociationInstance = WSManEnumFlags.AssociationInstance; pub const WSManProxyAccessTypeFlags = enum(i32) { IEConfig = 1, WinHttpConfig = 2, AutoDetect = 4, NoProxyServer = 8, }; pub const WSManProxyIEConfig = WSManProxyAccessTypeFlags.IEConfig; pub const WSManProxyWinHttpConfig = WSManProxyAccessTypeFlags.WinHttpConfig; pub const WSManProxyAutoDetect = WSManProxyAccessTypeFlags.AutoDetect; pub const WSManProxyNoProxyServer = WSManProxyAccessTypeFlags.NoProxyServer; pub const WSManProxyAuthenticationFlags = enum(i32) { Negotiate = 1, Basic = 2, Digest = 4, }; pub const WSManFlagProxyAuthenticationUseNegotiate = WSManProxyAuthenticationFlags.Negotiate; pub const WSManFlagProxyAuthenticationUseBasic = WSManProxyAuthenticationFlags.Basic; pub const WSManFlagProxyAuthenticationUseDigest = WSManProxyAuthenticationFlags.Digest; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSMan_Value = @import("../zig.zig").Guid.initString("190d8637-5cd3-496d-ad24-69636bb5a3b5"); pub const IID_IWSMan = &IID_IWSMan_Value; pub const IWSMan = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, CreateSession: fn( self: *const IWSMan, connection: ?BSTR, flags: i32, connectionOptions: ?*IDispatch, session: ?*?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateConnectionOptions: fn( self: *const IWSMan, connectionOptions: ?*?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_CommandLine: fn( self: *const IWSMan, value: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Error: fn( self: *const IWSMan, 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 IWSMan_CreateSession(self: *const T, connection: ?BSTR, flags: i32, connectionOptions: ?*IDispatch, session: ?*?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IWSMan.VTable, self.vtable).CreateSession(@ptrCast(*const IWSMan, self), connection, flags, connectionOptions, session); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSMan_CreateConnectionOptions(self: *const T, connectionOptions: ?*?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IWSMan.VTable, self.vtable).CreateConnectionOptions(@ptrCast(*const IWSMan, self), connectionOptions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSMan_get_CommandLine(self: *const T, value: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSMan.VTable, self.vtable).get_CommandLine(@ptrCast(*const IWSMan, self), value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSMan_get_Error(self: *const T, value: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSMan.VTable, self.vtable).get_Error(@ptrCast(*const IWSMan, self), value); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSManEx_Value = @import("../zig.zig").Guid.initString("2d53bdaa-798e-49e6-a1aa-74d01256f411"); pub const IID_IWSManEx = &IID_IWSManEx_Value; pub const IWSManEx = extern struct { pub const VTable = extern struct { base: IWSMan.VTable, CreateResourceLocator: fn( self: *const IWSManEx, strResourceLocator: ?BSTR, newResourceLocator: ?*?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SessionFlagUTF8: fn( self: *const IWSManEx, flags: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SessionFlagCredUsernamePassword: fn( self: *const IWSManEx, flags: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SessionFlagSkipCACheck: fn( self: *const IWSManEx, flags: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SessionFlagSkipCNCheck: fn( self: *const IWSManEx, flags: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SessionFlagUseDigest: fn( self: *const IWSManEx, flags: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SessionFlagUseNegotiate: fn( self: *const IWSManEx, flags: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SessionFlagUseBasic: fn( self: *const IWSManEx, flags: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SessionFlagUseKerberos: fn( self: *const IWSManEx, flags: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SessionFlagNoEncryption: fn( self: *const IWSManEx, flags: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SessionFlagEnableSPNServerPort: fn( self: *const IWSManEx, flags: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SessionFlagUseNoAuthentication: fn( self: *const IWSManEx, flags: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumerationFlagNonXmlText: fn( self: *const IWSManEx, flags: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumerationFlagReturnEPR: fn( self: *const IWSManEx, flags: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumerationFlagReturnObjectAndEPR: fn( self: *const IWSManEx, flags: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetErrorMessage: fn( self: *const IWSManEx, errorNumber: u32, errorMessage: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumerationFlagHierarchyDeep: fn( self: *const IWSManEx, flags: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumerationFlagHierarchyShallow: fn( self: *const IWSManEx, flags: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumerationFlagHierarchyDeepBasePropsOnly: fn( self: *const IWSManEx, flags: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumerationFlagReturnObject: fn( self: *const IWSManEx, flags: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWSMan.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEx_CreateResourceLocator(self: *const T, strResourceLocator: ?BSTR, newResourceLocator: ?*?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEx.VTable, self.vtable).CreateResourceLocator(@ptrCast(*const IWSManEx, self), strResourceLocator, newResourceLocator); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEx_SessionFlagUTF8(self: *const T, flags: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEx.VTable, self.vtable).SessionFlagUTF8(@ptrCast(*const IWSManEx, self), flags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEx_SessionFlagCredUsernamePassword(self: *const T, flags: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEx.VTable, self.vtable).SessionFlagCredUsernamePassword(@ptrCast(*const IWSManEx, self), flags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEx_SessionFlagSkipCACheck(self: *const T, flags: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEx.VTable, self.vtable).SessionFlagSkipCACheck(@ptrCast(*const IWSManEx, self), flags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEx_SessionFlagSkipCNCheck(self: *const T, flags: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEx.VTable, self.vtable).SessionFlagSkipCNCheck(@ptrCast(*const IWSManEx, self), flags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEx_SessionFlagUseDigest(self: *const T, flags: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEx.VTable, self.vtable).SessionFlagUseDigest(@ptrCast(*const IWSManEx, self), flags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEx_SessionFlagUseNegotiate(self: *const T, flags: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEx.VTable, self.vtable).SessionFlagUseNegotiate(@ptrCast(*const IWSManEx, self), flags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEx_SessionFlagUseBasic(self: *const T, flags: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEx.VTable, self.vtable).SessionFlagUseBasic(@ptrCast(*const IWSManEx, self), flags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEx_SessionFlagUseKerberos(self: *const T, flags: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEx.VTable, self.vtable).SessionFlagUseKerberos(@ptrCast(*const IWSManEx, self), flags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEx_SessionFlagNoEncryption(self: *const T, flags: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEx.VTable, self.vtable).SessionFlagNoEncryption(@ptrCast(*const IWSManEx, self), flags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEx_SessionFlagEnableSPNServerPort(self: *const T, flags: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEx.VTable, self.vtable).SessionFlagEnableSPNServerPort(@ptrCast(*const IWSManEx, self), flags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEx_SessionFlagUseNoAuthentication(self: *const T, flags: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEx.VTable, self.vtable).SessionFlagUseNoAuthentication(@ptrCast(*const IWSManEx, self), flags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEx_EnumerationFlagNonXmlText(self: *const T, flags: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEx.VTable, self.vtable).EnumerationFlagNonXmlText(@ptrCast(*const IWSManEx, self), flags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEx_EnumerationFlagReturnEPR(self: *const T, flags: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEx.VTable, self.vtable).EnumerationFlagReturnEPR(@ptrCast(*const IWSManEx, self), flags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEx_EnumerationFlagReturnObjectAndEPR(self: *const T, flags: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEx.VTable, self.vtable).EnumerationFlagReturnObjectAndEPR(@ptrCast(*const IWSManEx, self), flags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEx_GetErrorMessage(self: *const T, errorNumber: u32, errorMessage: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEx.VTable, self.vtable).GetErrorMessage(@ptrCast(*const IWSManEx, self), errorNumber, errorMessage); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEx_EnumerationFlagHierarchyDeep(self: *const T, flags: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEx.VTable, self.vtable).EnumerationFlagHierarchyDeep(@ptrCast(*const IWSManEx, self), flags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEx_EnumerationFlagHierarchyShallow(self: *const T, flags: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEx.VTable, self.vtable).EnumerationFlagHierarchyShallow(@ptrCast(*const IWSManEx, self), flags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEx_EnumerationFlagHierarchyDeepBasePropsOnly(self: *const T, flags: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEx.VTable, self.vtable).EnumerationFlagHierarchyDeepBasePropsOnly(@ptrCast(*const IWSManEx, self), flags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEx_EnumerationFlagReturnObject(self: *const T, flags: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEx.VTable, self.vtable).EnumerationFlagReturnObject(@ptrCast(*const IWSManEx, self), flags); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSManEx2_Value = @import("../zig.zig").Guid.initString("1d1b5ae0-42d9-4021-8261-3987619512e9"); pub const IID_IWSManEx2 = &IID_IWSManEx2_Value; pub const IWSManEx2 = extern struct { pub const VTable = extern struct { base: IWSManEx.VTable, SessionFlagUseClientCertificate: fn( self: *const IWSManEx2, flags: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWSManEx.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEx2_SessionFlagUseClientCertificate(self: *const T, flags: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEx2.VTable, self.vtable).SessionFlagUseClientCertificate(@ptrCast(*const IWSManEx2, self), flags); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IWSManEx3_Value = @import("../zig.zig").Guid.initString("6400e966-011d-4eac-8474-049e0848afad"); pub const IID_IWSManEx3 = &IID_IWSManEx3_Value; pub const IWSManEx3 = extern struct { pub const VTable = extern struct { base: IWSManEx2.VTable, SessionFlagUTF16: fn( self: *const IWSManEx3, flags: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SessionFlagUseCredSsp: fn( self: *const IWSManEx3, flags: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumerationFlagAssociationInstance: fn( self: *const IWSManEx3, flags: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumerationFlagAssociatedInstance: fn( self: *const IWSManEx3, flags: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SessionFlagSkipRevocationCheck: fn( self: *const IWSManEx3, flags: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SessionFlagAllowNegotiateImplicitCredentials: fn( self: *const IWSManEx3, flags: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SessionFlagUseSsl: fn( self: *const IWSManEx3, flags: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWSManEx2.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEx3_SessionFlagUTF16(self: *const T, flags: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEx3.VTable, self.vtable).SessionFlagUTF16(@ptrCast(*const IWSManEx3, self), flags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEx3_SessionFlagUseCredSsp(self: *const T, flags: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEx3.VTable, self.vtable).SessionFlagUseCredSsp(@ptrCast(*const IWSManEx3, self), flags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEx3_EnumerationFlagAssociationInstance(self: *const T, flags: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEx3.VTable, self.vtable).EnumerationFlagAssociationInstance(@ptrCast(*const IWSManEx3, self), flags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEx3_EnumerationFlagAssociatedInstance(self: *const T, flags: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEx3.VTable, self.vtable).EnumerationFlagAssociatedInstance(@ptrCast(*const IWSManEx3, self), flags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEx3_SessionFlagSkipRevocationCheck(self: *const T, flags: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEx3.VTable, self.vtable).SessionFlagSkipRevocationCheck(@ptrCast(*const IWSManEx3, self), flags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEx3_SessionFlagAllowNegotiateImplicitCredentials(self: *const T, flags: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEx3.VTable, self.vtable).SessionFlagAllowNegotiateImplicitCredentials(@ptrCast(*const IWSManEx3, self), flags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEx3_SessionFlagUseSsl(self: *const T, flags: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEx3.VTable, self.vtable).SessionFlagUseSsl(@ptrCast(*const IWSManEx3, self), flags); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSManConnectionOptions_Value = @import("../zig.zig").Guid.initString("f704e861-9e52-464f-b786-da5eb2320fdd"); pub const IID_IWSManConnectionOptions = &IID_IWSManConnectionOptions_Value; pub const IWSManConnectionOptions = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UserName: fn( self: *const IWSManConnectionOptions, name: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_UserName: fn( self: *const IWSManConnectionOptions, name: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Password: fn( self: *const IWSManConnectionOptions, password: ?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 IWSManConnectionOptions_get_UserName(self: *const T, name: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManConnectionOptions.VTable, self.vtable).get_UserName(@ptrCast(*const IWSManConnectionOptions, self), name); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManConnectionOptions_put_UserName(self: *const T, name: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManConnectionOptions.VTable, self.vtable).put_UserName(@ptrCast(*const IWSManConnectionOptions, self), name); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManConnectionOptions_put_Password(self: *const T, password: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManConnectionOptions.VTable, self.vtable).put_Password(@ptrCast(*const IWSManConnectionOptions, self), password); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSManConnectionOptionsEx_Value = @import("../zig.zig").Guid.initString("ef43edf7-2a48-4d93-9526-8bd6ab6d4a6b"); pub const IID_IWSManConnectionOptionsEx = &IID_IWSManConnectionOptionsEx_Value; pub const IWSManConnectionOptionsEx = extern struct { pub const VTable = extern struct { base: IWSManConnectionOptions.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_CertificateThumbprint: fn( self: *const IWSManConnectionOptionsEx, thumbprint: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_CertificateThumbprint: fn( self: *const IWSManConnectionOptionsEx, thumbprint: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWSManConnectionOptions.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManConnectionOptionsEx_get_CertificateThumbprint(self: *const T, thumbprint: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManConnectionOptionsEx.VTable, self.vtable).get_CertificateThumbprint(@ptrCast(*const IWSManConnectionOptionsEx, self), thumbprint); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManConnectionOptionsEx_put_CertificateThumbprint(self: *const T, thumbprint: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManConnectionOptionsEx.VTable, self.vtable).put_CertificateThumbprint(@ptrCast(*const IWSManConnectionOptionsEx, self), thumbprint); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IWSManConnectionOptionsEx2_Value = @import("../zig.zig").Guid.initString("f500c9ec-24ee-48ab-b38d-fc9a164c658e"); pub const IID_IWSManConnectionOptionsEx2 = &IID_IWSManConnectionOptionsEx2_Value; pub const IWSManConnectionOptionsEx2 = extern struct { pub const VTable = extern struct { base: IWSManConnectionOptionsEx.VTable, SetProxy: fn( self: *const IWSManConnectionOptionsEx2, accessType: i32, authenticationMechanism: i32, userName: ?BSTR, password: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ProxyIEConfig: fn( self: *const IWSManConnectionOptionsEx2, value: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ProxyWinHttpConfig: fn( self: *const IWSManConnectionOptionsEx2, value: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ProxyAutoDetect: fn( self: *const IWSManConnectionOptionsEx2, value: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ProxyNoProxyServer: fn( self: *const IWSManConnectionOptionsEx2, value: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ProxyAuthenticationUseNegotiate: fn( self: *const IWSManConnectionOptionsEx2, value: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ProxyAuthenticationUseBasic: fn( self: *const IWSManConnectionOptionsEx2, value: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ProxyAuthenticationUseDigest: fn( self: *const IWSManConnectionOptionsEx2, value: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWSManConnectionOptionsEx.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManConnectionOptionsEx2_SetProxy(self: *const T, accessType: i32, authenticationMechanism: i32, userName: ?BSTR, password: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManConnectionOptionsEx2.VTable, self.vtable).SetProxy(@ptrCast(*const IWSManConnectionOptionsEx2, self), accessType, authenticationMechanism, userName, password); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManConnectionOptionsEx2_ProxyIEConfig(self: *const T, value: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManConnectionOptionsEx2.VTable, self.vtable).ProxyIEConfig(@ptrCast(*const IWSManConnectionOptionsEx2, self), value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManConnectionOptionsEx2_ProxyWinHttpConfig(self: *const T, value: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManConnectionOptionsEx2.VTable, self.vtable).ProxyWinHttpConfig(@ptrCast(*const IWSManConnectionOptionsEx2, self), value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManConnectionOptionsEx2_ProxyAutoDetect(self: *const T, value: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManConnectionOptionsEx2.VTable, self.vtable).ProxyAutoDetect(@ptrCast(*const IWSManConnectionOptionsEx2, self), value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManConnectionOptionsEx2_ProxyNoProxyServer(self: *const T, value: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManConnectionOptionsEx2.VTable, self.vtable).ProxyNoProxyServer(@ptrCast(*const IWSManConnectionOptionsEx2, self), value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManConnectionOptionsEx2_ProxyAuthenticationUseNegotiate(self: *const T, value: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManConnectionOptionsEx2.VTable, self.vtable).ProxyAuthenticationUseNegotiate(@ptrCast(*const IWSManConnectionOptionsEx2, self), value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManConnectionOptionsEx2_ProxyAuthenticationUseBasic(self: *const T, value: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManConnectionOptionsEx2.VTable, self.vtable).ProxyAuthenticationUseBasic(@ptrCast(*const IWSManConnectionOptionsEx2, self), value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManConnectionOptionsEx2_ProxyAuthenticationUseDigest(self: *const T, value: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManConnectionOptionsEx2.VTable, self.vtable).ProxyAuthenticationUseDigest(@ptrCast(*const IWSManConnectionOptionsEx2, self), value); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSManSession_Value = @import("../zig.zig").Guid.initString("fc84fc58-1286-40c4-9da0-c8ef6ec241e0"); pub const IID_IWSManSession = &IID_IWSManSession_Value; pub const IWSManSession = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, Get: fn( self: *const IWSManSession, resourceUri: VARIANT, flags: i32, resource: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Put: fn( self: *const IWSManSession, resourceUri: VARIANT, resource: ?BSTR, flags: i32, resultResource: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Create: fn( self: *const IWSManSession, resourceUri: VARIANT, resource: ?BSTR, flags: i32, newUri: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Delete: fn( self: *const IWSManSession, resourceUri: VARIANT, flags: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Invoke: fn( self: *const IWSManSession, actionUri: ?BSTR, resourceUri: VARIANT, parameters: ?BSTR, flags: i32, result: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Enumerate: fn( self: *const IWSManSession, resourceUri: VARIANT, filter: ?BSTR, dialect: ?BSTR, flags: i32, resultSet: ?*?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Identify: fn( self: *const IWSManSession, flags: i32, result: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Error: fn( self: *const IWSManSession, value: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BatchItems: fn( self: *const IWSManSession, value: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_BatchItems: fn( self: *const IWSManSession, value: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Timeout: fn( self: *const IWSManSession, value: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Timeout: fn( self: *const IWSManSession, value: i32, ) 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 IWSManSession_Get(self: *const T, resourceUri: VARIANT, flags: i32, resource: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManSession.VTable, self.vtable).Get(@ptrCast(*const IWSManSession, self), resourceUri, flags, resource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManSession_Put(self: *const T, resourceUri: VARIANT, resource: ?BSTR, flags: i32, resultResource: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManSession.VTable, self.vtable).Put(@ptrCast(*const IWSManSession, self), resourceUri, resource, flags, resultResource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManSession_Create(self: *const T, resourceUri: VARIANT, resource: ?BSTR, flags: i32, newUri: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManSession.VTable, self.vtable).Create(@ptrCast(*const IWSManSession, self), resourceUri, resource, flags, newUri); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManSession_Delete(self: *const T, resourceUri: VARIANT, flags: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManSession.VTable, self.vtable).Delete(@ptrCast(*const IWSManSession, self), resourceUri, flags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManSession_Invoke(self: *const T, actionUri: ?BSTR, resourceUri: VARIANT, parameters: ?BSTR, flags: i32, result: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManSession.VTable, self.vtable).Invoke(@ptrCast(*const IWSManSession, self), actionUri, resourceUri, parameters, flags, result); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManSession_Enumerate(self: *const T, resourceUri: VARIANT, filter: ?BSTR, dialect: ?BSTR, flags: i32, resultSet: ?*?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManSession.VTable, self.vtable).Enumerate(@ptrCast(*const IWSManSession, self), resourceUri, filter, dialect, flags, resultSet); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManSession_Identify(self: *const T, flags: i32, result: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManSession.VTable, self.vtable).Identify(@ptrCast(*const IWSManSession, self), flags, result); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManSession_get_Error(self: *const T, value: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManSession.VTable, self.vtable).get_Error(@ptrCast(*const IWSManSession, self), value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManSession_get_BatchItems(self: *const T, value: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManSession.VTable, self.vtable).get_BatchItems(@ptrCast(*const IWSManSession, self), value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManSession_put_BatchItems(self: *const T, value: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManSession.VTable, self.vtable).put_BatchItems(@ptrCast(*const IWSManSession, self), value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManSession_get_Timeout(self: *const T, value: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManSession.VTable, self.vtable).get_Timeout(@ptrCast(*const IWSManSession, self), value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManSession_put_Timeout(self: *const T, value: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManSession.VTable, self.vtable).put_Timeout(@ptrCast(*const IWSManSession, self), value); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSManEnumerator_Value = @import("../zig.zig").Guid.initString("f3457ca9-abb9-4fa5-b850-90e8ca300e7f"); pub const IID_IWSManEnumerator = &IID_IWSManEnumerator_Value; pub const IWSManEnumerator = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, ReadItem: fn( self: *const IWSManEnumerator, resource: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AtEndOfStream: fn( self: *const IWSManEnumerator, eos: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Error: fn( self: *const IWSManEnumerator, 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 IWSManEnumerator_ReadItem(self: *const T, resource: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEnumerator.VTable, self.vtable).ReadItem(@ptrCast(*const IWSManEnumerator, self), resource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEnumerator_get_AtEndOfStream(self: *const T, eos: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEnumerator.VTable, self.vtable).get_AtEndOfStream(@ptrCast(*const IWSManEnumerator, self), eos); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManEnumerator_get_Error(self: *const T, value: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManEnumerator.VTable, self.vtable).get_Error(@ptrCast(*const IWSManEnumerator, self), value); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWSManResourceLocator_Value = @import("../zig.zig").Guid.initString("a7a1ba28-de41-466a-ad0a-c4059ead7428"); pub const IID_IWSManResourceLocator = &IID_IWSManResourceLocator_Value; pub const IWSManResourceLocator = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ResourceURI: fn( self: *const IWSManResourceLocator, uri: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ResourceURI: fn( self: *const IWSManResourceLocator, uri: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddSelector: fn( self: *const IWSManResourceLocator, resourceSelName: ?BSTR, selValue: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ClearSelectors: fn( self: *const IWSManResourceLocator, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_FragmentPath: fn( self: *const IWSManResourceLocator, text: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_FragmentPath: fn( self: *const IWSManResourceLocator, text: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_FragmentDialect: fn( self: *const IWSManResourceLocator, text: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_FragmentDialect: fn( self: *const IWSManResourceLocator, text: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddOption: fn( self: *const IWSManResourceLocator, OptionName: ?BSTR, OptionValue: VARIANT, mustComply: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MustUnderstandOptions: fn( self: *const IWSManResourceLocator, mustUnderstand: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MustUnderstandOptions: fn( self: *const IWSManResourceLocator, mustUnderstand: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ClearOptions: fn( self: *const IWSManResourceLocator, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Error: fn( self: *const IWSManResourceLocator, 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 IWSManResourceLocator_put_ResourceURI(self: *const T, uri: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManResourceLocator.VTable, self.vtable).put_ResourceURI(@ptrCast(*const IWSManResourceLocator, self), uri); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManResourceLocator_get_ResourceURI(self: *const T, uri: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManResourceLocator.VTable, self.vtable).get_ResourceURI(@ptrCast(*const IWSManResourceLocator, self), uri); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManResourceLocator_AddSelector(self: *const T, resourceSelName: ?BSTR, selValue: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManResourceLocator.VTable, self.vtable).AddSelector(@ptrCast(*const IWSManResourceLocator, self), resourceSelName, selValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManResourceLocator_ClearSelectors(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManResourceLocator.VTable, self.vtable).ClearSelectors(@ptrCast(*const IWSManResourceLocator, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManResourceLocator_get_FragmentPath(self: *const T, text: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManResourceLocator.VTable, self.vtable).get_FragmentPath(@ptrCast(*const IWSManResourceLocator, self), text); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManResourceLocator_put_FragmentPath(self: *const T, text: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManResourceLocator.VTable, self.vtable).put_FragmentPath(@ptrCast(*const IWSManResourceLocator, self), text); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManResourceLocator_get_FragmentDialect(self: *const T, text: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManResourceLocator.VTable, self.vtable).get_FragmentDialect(@ptrCast(*const IWSManResourceLocator, self), text); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManResourceLocator_put_FragmentDialect(self: *const T, text: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManResourceLocator.VTable, self.vtable).put_FragmentDialect(@ptrCast(*const IWSManResourceLocator, self), text); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManResourceLocator_AddOption(self: *const T, OptionName: ?BSTR, OptionValue: VARIANT, mustComply: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManResourceLocator.VTable, self.vtable).AddOption(@ptrCast(*const IWSManResourceLocator, self), OptionName, OptionValue, mustComply); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManResourceLocator_put_MustUnderstandOptions(self: *const T, mustUnderstand: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManResourceLocator.VTable, self.vtable).put_MustUnderstandOptions(@ptrCast(*const IWSManResourceLocator, self), mustUnderstand); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManResourceLocator_get_MustUnderstandOptions(self: *const T, mustUnderstand: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManResourceLocator.VTable, self.vtable).get_MustUnderstandOptions(@ptrCast(*const IWSManResourceLocator, self), mustUnderstand); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManResourceLocator_ClearOptions(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManResourceLocator.VTable, self.vtable).ClearOptions(@ptrCast(*const IWSManResourceLocator, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWSManResourceLocator_get_Error(self: *const T, value: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManResourceLocator.VTable, self.vtable).get_Error(@ptrCast(*const IWSManResourceLocator, self), value); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWSManResourceLocatorInternal_Value = @import("../zig.zig").Guid.initString("effaead7-7ec8-4716-b9be-f2e7e9fb4adb"); pub const IID_IWSManResourceLocatorInternal = &IID_IWSManResourceLocatorInternal_Value; pub const IWSManResourceLocatorInternal = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); };} pub usingnamespace MethodMixin(@This()); }; const IID_IWSManInternal_Value = @import("../zig.zig").Guid.initString("04ae2b1d-9954-4d99-94a9-a961e72c3a13"); pub const IID_IWSManInternal = &IID_IWSManInternal_Value; pub const IWSManInternal = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, ConfigSDDL: fn( self: *const IWSManInternal, session: ?*IDispatch, resourceUri: VARIANT, flags: i32, resource: ?*?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 IWSManInternal_ConfigSDDL(self: *const T, session: ?*IDispatch, resourceUri: VARIANT, flags: i32, resource: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWSManInternal.VTable, self.vtable).ConfigSDDL(@ptrCast(*const IWSManInternal, self), session, resourceUri, flags, resource); } };} pub usingnamespace MethodMixin(@This()); }; //-------------------------------------------------------------------------------- // Section: Functions (33) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows8.0' pub extern "WsmSvc" fn WSManInitialize( flags: u32, apiHandle: ?*?*WSMAN_API, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "WsmSvc" fn WSManDeinitialize( apiHandle: ?*WSMAN_API, flags: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "WsmSvc" fn WSManGetErrorMessage( apiHandle: ?*WSMAN_API, flags: u32, languageCode: ?[*:0]const u16, errorCode: u32, messageLength: u32, message: ?[*:0]u16, messageLengthUsed: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "WsmSvc" fn WSManCreateSession( apiHandle: ?*WSMAN_API, connection: ?[*:0]const u16, flags: u32, serverAuthenticationCredentials: ?*WSMAN_AUTHENTICATION_CREDENTIALS, proxyInfo: ?*WSMAN_PROXY_INFO, session: ?*?*WSMAN_SESSION, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "WsmSvc" fn WSManCloseSession( session: ?*WSMAN_SESSION, flags: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "WsmSvc" fn WSManSetSessionOption( session: ?*WSMAN_SESSION, option: WSManSessionOption, data: ?*WSMAN_DATA, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "WsmSvc" fn WSManGetSessionOptionAsDword( session: ?*WSMAN_SESSION, option: WSManSessionOption, value: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "WsmSvc" fn WSManGetSessionOptionAsString( session: ?*WSMAN_SESSION, option: WSManSessionOption, stringLength: u32, string: ?[*:0]u16, stringLengthUsed: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "WsmSvc" fn WSManCloseOperation( operationHandle: ?*WSMAN_OPERATION, flags: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "WsmSvc" fn WSManCreateShell( session: ?*WSMAN_SESSION, flags: u32, resourceUri: ?[*:0]const u16, startupInfo: ?*WSMAN_SHELL_STARTUP_INFO_V11, options: ?*WSMAN_OPTION_SET, createXml: ?*WSMAN_DATA, @"async": ?*WSMAN_SHELL_ASYNC, shell: ?*?*WSMAN_SHELL, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.1' pub extern "WsmSvc" fn WSManRunShellCommand( shell: ?*WSMAN_SHELL, flags: u32, commandLine: ?[*:0]const u16, args: ?*WSMAN_COMMAND_ARG_SET, options: ?*WSMAN_OPTION_SET, @"async": ?*WSMAN_SHELL_ASYNC, command: ?*?*WSMAN_COMMAND, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.1' pub extern "WsmSvc" fn WSManSignalShell( shell: ?*WSMAN_SHELL, command: ?*WSMAN_COMMAND, flags: u32, code: ?[*:0]const u16, @"async": ?*WSMAN_SHELL_ASYNC, signalOperation: ?*?*WSMAN_OPERATION, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.1' pub extern "WsmSvc" fn WSManReceiveShellOutput( shell: ?*WSMAN_SHELL, command: ?*WSMAN_COMMAND, flags: u32, desiredStreamSet: ?*WSMAN_STREAM_ID_SET, @"async": ?*WSMAN_SHELL_ASYNC, receiveOperation: ?*?*WSMAN_OPERATION, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.1' pub extern "WsmSvc" fn WSManSendShellInput( shell: ?*WSMAN_SHELL, command: ?*WSMAN_COMMAND, flags: u32, streamId: ?[*:0]const u16, streamData: ?*WSMAN_DATA, endOfStream: BOOL, @"async": ?*WSMAN_SHELL_ASYNC, sendOperation: ?*?*WSMAN_OPERATION, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.1' pub extern "WsmSvc" fn WSManCloseCommand( commandHandle: ?*WSMAN_COMMAND, flags: u32, @"async": ?*WSMAN_SHELL_ASYNC, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.1' pub extern "WsmSvc" fn WSManCloseShell( shellHandle: ?*WSMAN_SHELL, flags: u32, @"async": ?*WSMAN_SHELL_ASYNC, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows8.0' pub extern "WsmSvc" fn WSManCreateShellEx( session: ?*WSMAN_SESSION, flags: u32, resourceUri: ?[*:0]const u16, shellId: ?[*:0]const u16, startupInfo: ?*WSMAN_SHELL_STARTUP_INFO_V11, options: ?*WSMAN_OPTION_SET, createXml: ?*WSMAN_DATA, @"async": ?*WSMAN_SHELL_ASYNC, shell: ?*?*WSMAN_SHELL, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows8.0' pub extern "WsmSvc" fn WSManRunShellCommandEx( shell: ?*WSMAN_SHELL, flags: u32, commandId: ?[*:0]const u16, commandLine: ?[*:0]const u16, args: ?*WSMAN_COMMAND_ARG_SET, options: ?*WSMAN_OPTION_SET, @"async": ?*WSMAN_SHELL_ASYNC, command: ?*?*WSMAN_COMMAND, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows8.0' pub extern "WsmSvc" fn WSManDisconnectShell( shell: ?*WSMAN_SHELL, flags: u32, disconnectInfo: ?*WSMAN_SHELL_DISCONNECT_INFO, @"async": ?*WSMAN_SHELL_ASYNC, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows8.0' pub extern "WsmSvc" fn WSManReconnectShell( shell: ?*WSMAN_SHELL, flags: u32, @"async": ?*WSMAN_SHELL_ASYNC, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows8.0' pub extern "WsmSvc" fn WSManReconnectShellCommand( commandHandle: ?*WSMAN_COMMAND, flags: u32, @"async": ?*WSMAN_SHELL_ASYNC, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows8.0' pub extern "WsmSvc" fn WSManConnectShell( session: ?*WSMAN_SESSION, flags: u32, resourceUri: ?[*:0]const u16, shellID: ?[*:0]const u16, options: ?*WSMAN_OPTION_SET, connectXml: ?*WSMAN_DATA, @"async": ?*WSMAN_SHELL_ASYNC, shell: ?*?*WSMAN_SHELL, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows8.0' pub extern "WsmSvc" fn WSManConnectShellCommand( shell: ?*WSMAN_SHELL, flags: u32, commandID: ?[*:0]const u16, options: ?*WSMAN_OPTION_SET, connectXml: ?*WSMAN_DATA, @"async": ?*WSMAN_SHELL_ASYNC, command: ?*?*WSMAN_COMMAND, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.1' pub extern "WsmSvc" fn WSManPluginReportContext( requestDetails: ?*WSMAN_PLUGIN_REQUEST, flags: u32, context: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "WsmSvc" fn WSManPluginReceiveResult( requestDetails: ?*WSMAN_PLUGIN_REQUEST, flags: u32, stream: ?[*:0]const u16, streamResult: ?*WSMAN_DATA, commandState: ?[*:0]const u16, exitCode: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "WsmSvc" fn WSManPluginOperationComplete( requestDetails: ?*WSMAN_PLUGIN_REQUEST, flags: u32, errorCode: u32, extendedInformation: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "WsmSvc" fn WSManPluginGetOperationParameters( requestDetails: ?*WSMAN_PLUGIN_REQUEST, flags: u32, data: ?*WSMAN_DATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WsmSvc" fn WSManPluginGetConfiguration( pluginContext: ?*c_void, flags: u32, data: ?*WSMAN_DATA, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WsmSvc" fn WSManPluginReportCompletion( pluginContext: ?*c_void, flags: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "WsmSvc" fn WSManPluginFreeRequestDetails( requestDetails: ?*WSMAN_PLUGIN_REQUEST, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "WsmSvc" fn WSManPluginAuthzUserComplete( senderDetails: ?*WSMAN_SENDER_DETAILS, flags: u32, userAuthorizationContext: ?*c_void, impersonationToken: ?HANDLE, userIsAdministrator: BOOL, errorCode: u32, extendedErrorInformation: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "WsmSvc" fn WSManPluginAuthzOperationComplete( senderDetails: ?*WSMAN_SENDER_DETAILS, flags: u32, userAuthorizationContext: ?*c_void, errorCode: u32, extendedErrorInformation: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "WsmSvc" fn WSManPluginAuthzQueryQuotaComplete( senderDetails: ?*WSMAN_SENDER_DETAILS, flags: u32, quota: ?*WSMAN_AUTHZ_QUOTA, errorCode: u32, extendedErrorInformation: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; //-------------------------------------------------------------------------------- // 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 (8) //-------------------------------------------------------------------------------- const BOOL = @import("../foundation.zig").BOOL; const BSTR = @import("../foundation.zig").BSTR; const HANDLE = @import("../foundation.zig").HANDLE; const HRESULT = @import("../foundation.zig").HRESULT; const IDispatch = @import("../system/ole_automation.zig").IDispatch; const IUnknown = @import("../system/com.zig").IUnknown; const PWSTR = @import("../foundation.zig").PWSTR; 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(), "WSMAN_SHELL_COMPLETION_FUNCTION")) { _ = WSMAN_SHELL_COMPLETION_FUNCTION; } if (@hasDecl(@This(), "WSMAN_PLUGIN_RELEASE_SHELL_CONTEXT")) { _ = WSMAN_PLUGIN_RELEASE_SHELL_CONTEXT; } if (@hasDecl(@This(), "WSMAN_PLUGIN_RELEASE_COMMAND_CONTEXT")) { _ = WSMAN_PLUGIN_RELEASE_COMMAND_CONTEXT; } if (@hasDecl(@This(), "WSMAN_PLUGIN_STARTUP")) { _ = WSMAN_PLUGIN_STARTUP; } if (@hasDecl(@This(), "WSMAN_PLUGIN_SHUTDOWN")) { _ = WSMAN_PLUGIN_SHUTDOWN; } if (@hasDecl(@This(), "WSMAN_PLUGIN_SHELL")) { _ = WSMAN_PLUGIN_SHELL; } if (@hasDecl(@This(), "WSMAN_PLUGIN_COMMAND")) { _ = WSMAN_PLUGIN_COMMAND; } if (@hasDecl(@This(), "WSMAN_PLUGIN_SEND")) { _ = WSMAN_PLUGIN_SEND; } if (@hasDecl(@This(), "WSMAN_PLUGIN_RECEIVE")) { _ = WSMAN_PLUGIN_RECEIVE; } if (@hasDecl(@This(), "WSMAN_PLUGIN_SIGNAL")) { _ = WSMAN_PLUGIN_SIGNAL; } if (@hasDecl(@This(), "WSMAN_PLUGIN_CONNECT")) { _ = WSMAN_PLUGIN_CONNECT; } if (@hasDecl(@This(), "WSMAN_PLUGIN_AUTHORIZE_USER")) { _ = WSMAN_PLUGIN_AUTHORIZE_USER; } if (@hasDecl(@This(), "WSMAN_PLUGIN_AUTHORIZE_OPERATION")) { _ = WSMAN_PLUGIN_AUTHORIZE_OPERATION; } if (@hasDecl(@This(), "WSMAN_PLUGIN_AUTHORIZE_QUERY_QUOTA")) { _ = WSMAN_PLUGIN_AUTHORIZE_QUERY_QUOTA; } if (@hasDecl(@This(), "WSMAN_PLUGIN_AUTHORIZE_RELEASE_CONTEXT")) { _ = WSMAN_PLUGIN_AUTHORIZE_RELEASE_CONTEXT; } @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/remote_management.zig
const format = @import("std").fmt.format; const OutStream = @import("std").io.OutStream; const regs = struct { fn bit(comptime n: u32) u8 { return 1 << n; } const DATA: usize = 0x00; const STATE: usize = 0x04; const STATE_TX_FULL: u8 = bit(0); const STATE_RX_FULL: u8 = bit(1); const STATE_TX_OVERRUN: u8 = bit(2); const STATE_RX_OVERRUN: u8 = bit(3); const CTRL: usize = 0x08; const CTRL_TX_ENABLE: u8 = bit(0); const CTRL_RX_ENABLE: u8 = bit(1); const CTRL_TX_INT_ENABLE: u8 = bit(2); const CTRL_RX_INT_ENABLE: u8 = bit(3); const CTRL_TX_OVERRUN_INT_ENABLE: u8 = bit(4); const CTRL_RX_OVERRUN_INT_ENABLE: u8 = bit(5); const INT: usize = 0x0c; const INT_TX: u8 = bit(0); const INT_RX: u8 = bit(1); const INT_TX_OVERRUN: u8 = bit(2); const INT_RX_OVERRUN: u8 = bit(3); const BAUDDIV: usize = 0x10; }; pub const Pl011 = struct { base: usize, const Self = @This(); /// Construct a `Pl011` object using the specified MMIO base address. pub fn withBase(base: usize) Self { return Self{ .base = base }; } fn regData(self: Self) *volatile u8 { return @intToPtr(*volatile u8, self.base + regs.DATA); } fn regState(self: Self) *volatile u8 { return @intToPtr(*volatile u8, self.base + regs.STATE); } fn regCtrl(self: Self) *volatile u8 { return @intToPtr(*volatile u8, self.base + regs.CTRL); } fn regInt(self: Self) *volatile u8 { return @intToPtr(*volatile u8, self.base + regs.INT); } fn regBauddiv(self: Self) *volatile u32 { return @intToPtr(*volatile u32, self.base + regs.BAUDDIV); } pub fn configure(self: Self, system_core_clock: u32, baud_Rate: u32) void { self.regBauddiv().* = system_core_clock / baud_Rate; self.regCtrl().* = regs.CTRL_TX_ENABLE | regs.CTRL_RX_ENABLE; } pub fn tryWrite(self: Self, data: u8) bool { if ((self.regState().* & regs.STATE_TX_FULL) != 0) { return false; } self.regData().* = data; return true; } pub fn write(self: Self, data: u8) void { while (!self.tryWrite(data)) {} } pub fn writeSlice(self: Self, data: []const u8) void { for (data) |b| { self.write(b); } } /// Render the format string `fmt` with `args` and transmit the output. pub fn print(self: Self, comptime fmt: []const u8, args: var) void { const out_stream = OutStream(Self, error{}, printInner){ .context = self }; format(out_stream, fmt, args) catch unreachable; } fn printInner(self: Self, data: []const u8) error{}!usize { self.writeSlice(data); return data.len; } };
examples/drivers/pl011.zig
const std = @import("std"); const ascii = std.ascii; pub const FieldFlagsDef = struct { field: []const u8, flags: []const u8, }; pub const FieldFlagsMask = struct { field: []const u8, mask: u8, }; pub const FieldFlags = struct { /// For disambiguation in case 2 fields share a flag char field: ?[]const u8 = null, flags: []const u8, }; /// Helper struct to convert a string of flags to a bit mask pub fn CreateFlags(comptime T: type, comptime ff_defs: []const FieldFlagsDef) type { for (ff_defs) |ff_def| { if (std.meta.fieldIndex(T, ff_def.field)) |index| { const t = std.meta.fields(T)[index].field_type; if (t != u8) { @compileError("Expected field \"" ++ ff_def.field ++ "\" to be a u8, got " ++ t); } } else { @compileError("Field \"" ++ ff_def.field ++ "\" not in struct"); } for (ff_def.flags[0..(ff_def.flags.len - 1)]) |c, i| { if (ascii.isDigit(c)) { @compileError("Digits not allowed in flags"); } if (c == '?') { continue; } if (std.mem.indexOfScalar(u8, ff_def.flags[(i + 1)..], c) != null) { @compileError("Duplicate flag (" ++ [1]u8{c} ++ ") within field \"" ++ ff_def.field ++ "\""); } } } return struct { /// If FieldFlags.fields == null, attempts to disambiguate using the first letter flag /// Psuedocode example: def flag1 = "abcd???g", flag2 = "a?dcefgh" /// getFlagMask("234") // ambiguous /// getFlagMask("2ab") // ambiguous /// getFlagMask("2ba") // flag1 pub fn getFlagMask(comptime field_flags: FieldFlags) FieldFlagsMask { if (field_flags.flags.len == 0) { @compileError("0 len flags"); } const ff_def = blk: { if (field_flags.field) |field| { // search for requested field for (ff_defs) |f| { if (std.mem.eql(u8, f.field, field)) { break :blk f; } } else { @compileError("Field \"" ++ field ++ "\" doesn't exist"); } } var first_letter: u8 = for (field_flags.flags) |c| { if (c == '?') { @compileError("'?' flag not allowed in get/set"); } if (ascii.isAlpha(c)) { break c; } } else { @compileError("Need at least one letter flag in non-disambiguated get/set"); }; // search for any field that contains the first flag var result: ?FieldFlagsDef = null; for (ff_defs) |f| { if (std.mem.indexOfScalar(u8, f.flags, first_letter) != null) { if (result) |r| { @compileError("Flag '" ++ [1]u8{first_letter} ++ "' is ambiguous between fields \"" ++ r.field ++ "\" and \"" ++ f.field ++ "\""); } result = f; } } if (result) |r| { break :blk r; } @compileError("Flag '" ++ [1]u8{first_letter} ++ "' is not in any field"); }; var mask = 0; for (field_flags.flags) |c| { const new_bit = blk: { if (ascii.isDigit(c)) { break :blk 1 << (c - '0'); } else if (std.mem.indexOfScalar(u8, ff_def.flags, c)) |i| { break :blk 1 << (7 - i); } else { @compileError("Unknown flag '" ++ [1]u8{c} ++ "'"); } }; if (mask & new_bit != 0) { @compileError("Flag '" ++ [1]u8{c} ++ "' accessed via both letter and number indices"); } mask |= new_bit; } return FieldFlagsMask{ .field = ff_def.field, .mask = mask, }; } pub fn getFlag(self: @This(), structure: T, comptime field_flags: FieldFlags) bool { if (field_flags.flags.len != 1) { @compileError("getFlags expect a single flag"); } return self.getFlags(structure, field_flags) != 0; } pub fn getFlags(_: @This(), structure: T, comptime field_flags: FieldFlags) u8 { const ff_mask = comptime getFlagMask(field_flags); return @field(structure, ff_mask.field) & ff_mask.mask; } pub fn setFlag(self: @This(), structure: *T, comptime field_flags: FieldFlags, val: bool) void { if (field_flags.flags.len != 1) { @compileError("setFlags expect a single flag"); } self.setFlags(structure, field_flags, if (val) @as(u8, 0xff) else 0x00); } pub fn setFlags(_: @This(), structure: *T, comptime field_flags: FieldFlags, val: u8) void { const ff_mask = comptime getFlagMask(field_flags); const field = &@field(structure, ff_mask.field); setMask(u8, field, val, ff_mask.mask); } }; } pub fn getMaskBool(comptime T: type, val: T, mask: T) bool { return (val & mask) != 0; } pub fn setMask(comptime T: type, lhs: *T, rhs: T, mask: T) void { lhs.* = (lhs.* & ~mask) | (rhs & mask); } const testing = std.testing; test "CreateFlags" { const TestStruct = struct { f1: u8, f2: u8, f3: u8, f4: u8, }; const ff_masks = CreateFlags(TestStruct, ([_]FieldFlagsDef{ .{ .field = "f1", .flags = "abcdefgh" }, .{ .field = "f2", .flags = "zyxwvuts" }, .{ .field = "f3", .flags = "a?c?d?e?" }, .{ .field = "f4", .flags = "a?c???w?" }, })[0..]){}; var test_struct = std.mem.zeroes(TestStruct); ff_masks.setFlags(&test_struct, .{ .field = "f1", .flags = "fabcdeg" }, 0xff); ff_masks.setFlags(&test_struct, .{ .flags = "zyxwvuts" }, 0xaa); ff_masks.setFlag(&test_struct, .{ .flags = "s" }, true); ff_masks.setFlags(&test_struct, .{ .field = "f3", .flags = "a6c4" }, 0b1111_0000); ff_masks.setFlags(&test_struct, .{ .field = "f3", .flags = "5432e0" }, 0b0000_1101); ff_masks.setFlags(&test_struct, .{ .field = "f4", .flags = "w76" }, 0b1110_0010); ff_masks.setFlag(&test_struct, .{ .field = "f4", .flags = "7" }, false); ff_masks.setFlags(&test_struct, .{ .field = "f4", .flags = "65432w0" }, 0b000_0001); ff_masks.setFlag(&test_struct, .{ .field = "f4", .flags = "3" }, true); try testing.expectEqual(@as(u8, 0xfe), test_struct.f1); try testing.expectEqual(@as(u8, 0xab), test_struct.f2); try testing.expectEqual(@as(u8, 0xcd), test_struct.f3); try testing.expectEqual(@as(u8, 0x09), test_struct.f4); try testing.expect(ff_masks.getFlag(test_struct, .{ .flags = "f" })); try testing.expect(!ff_masks.getFlag(test_struct, .{ .flags = "h" })); try testing.expect(!ff_masks.getFlag(test_struct, .{ .field = "f4", .flags = "a" })); try testing.expect(!ff_masks.getFlag(test_struct, .{ .field = "f4", .flags = "w" })); try testing.expectEqual(@as(u8, 0xfe & 0b1110_0001), ff_masks.getFlags(test_struct, .{ .flags = "habc" })); try testing.expectEqual(@as(u8, 0b0000_0011), ff_masks.getFlags(test_struct, .{ .flags = "sw2t" })); }
src/flags.zig
const std = @import("std"); const input = @import("input.zig"); pub fn run(allocator: std.mem.Allocator, stdout: anytype) anyerror!void { var input_ = try input.readFile("inputs/day12"); defer input_.deinit(); const input_parsed = try Input.init(allocator, &input_); { const result = try part1(allocator, &input_parsed); try stdout.print("12a: {}\n", .{ result }); std.debug.assert(result == 4691); } { const result = try part2(allocator, &input_parsed); try stdout.print("12b: {}\n", .{ result }); std.debug.assert(result == 140718); } } const Input = struct { const max_num_nodes = 16; const NodeId = usize; const NeighborsSet = std.StaticBitSet(max_num_nodes); const NodeKind = enum { start, small, big, end, }; const NodeInfo = struct { kind: NodeKind, neighbors: NeighborsSet, }; const Node = struct { id: NodeId, info: NodeInfo, }; nodes: [max_num_nodes]NodeInfo, fn init(allocator: std.mem.Allocator, input_: anytype) !@This() { var node_names = try std.BoundedArray([]const u8, max_num_nodes).init(0); defer for (node_names.slice()) |node_name| { allocator.free(node_name); }; var nodes: [max_num_nodes]NodeInfo = [_]NodeInfo { .{ .kind = .end, .neighbors = NeighborsSet.initEmpty() } } ** max_num_nodes; while (try input_.next()) |line| { var parts = std.mem.split(u8, line, "-"); const start = parts.next() orelse return error.InvalidInput; const start_node_id = try addNode(allocator, &node_names, &nodes, start); const end = parts.next() orelse return error.InvalidInput; const end_node_id = try addNode(allocator, &node_names, &nodes, end); if (nodes[end_node_id].kind != .start) { nodes[start_node_id].neighbors.set(end_node_id); } if (nodes[start_node_id].kind != .start) { nodes[end_node_id].neighbors.set(start_node_id); } } return Input { .nodes = nodes, }; } fn getStartNode(self: *const @This()) !Node { for (self.nodes) |info, id| { if (info.kind == .start) { return Node { .id = id, .info = info, }; } } return error.NoStartNodeDefined; } fn getNodeInfo(self: *const @This(), id: NodeId) NodeInfo { return self.nodes[id]; } fn addNode( allocator: std.mem.Allocator, node_names: *std.BoundedArray([]const u8, max_num_nodes), nodes: *[max_num_nodes]NodeInfo, name: []const u8, ) !NodeId { for (node_names.constSlice()) |node_name, node_id| { if (std.mem.eql(u8, node_name, name)) { return node_id; } } const node_id = node_names.len; const name_copy = try allocator.alloc(u8, name.len); errdefer allocator.free(name_copy); std.mem.copy(u8, name_copy, name); try node_names.append(name_copy); const node_kind = if (std.mem.eql(u8, name, "start")) NodeKind.start else if (std.mem.eql(u8, name, "end")) NodeKind.end else if (name[0] >= 'a' and name[0] <= 'z') NodeKind.small else if (name[0] >= 'A' and name[0] <= 'Z') NodeKind.big else return error.InvalidInput; nodes[node_id].kind = node_kind; return node_id; } }; fn part1(allocator: std.mem.Allocator, input_: *const Input) !usize { return solve(allocator, input_, false); } fn part2(allocator: std.mem.Allocator, input_: *const Input) !usize { return solve(allocator, input_, true); } const Path = struct { const VisitedSet = std.StaticBitSet(Input.max_num_nodes); visited_nodes: VisitedSet, visit_next: Input.NeighborsSet, have_visited_small_twice: bool, fn init(start_node: Input.Node) @This() { std.debug.assert(start_node.info.kind == .start); var visited_nodes = VisitedSet.initEmpty(); visited_nodes.set(start_node.id); return Path { .visited_nodes = visited_nodes, .visit_next = start_node.info.neighbors, .have_visited_small_twice = false, }; } fn visit(self: *const @This(), node: Input.Node) @This() { var visited_nodes = self.visited_nodes; if (node.info.kind != .big) { visited_nodes.set(node.id); } return Path { .visited_nodes = visited_nodes, .visit_next = node.info.neighbors, .have_visited_small_twice = self.have_visited_small_twice, }; } fn have_visited(self: *const @This(), node_id: Input.NodeId) bool { return self.visited_nodes.isSet(node_id); } }; fn solve(allocator: std.mem.Allocator, input_: *const Input, allow_visiting_small_twice: bool) !usize { var result: usize = 0; var paths = std.ArrayList(Path).init(allocator); defer paths.deinit(); { const start_node = try input_.getStartNode(); const path = Path.init(start_node); try paths.append(path); } while (paths.popOrNull()) |path| { var neighbors = path.visit_next.iterator(.{}); while (neighbors.next()) |neighbor_id| { const neighbor_info = input_.getNodeInfo(neighbor_id); if (neighbor_info.kind == .end) { result += 1; } else if (!path.have_visited(neighbor_id)) { const path_copy = path.visit(.{ .id = neighbor_id, .info = neighbor_info }); try paths.append(path_copy); } else if (allow_visiting_small_twice and !path.have_visited_small_twice) { var path_copy = path.visit(.{ .id = neighbor_id, .info = neighbor_info }); path_copy.have_visited_small_twice = true; try paths.append(path_copy); } } } return result; } test "day 12 example 1" { const input_ = \\start-A \\start-b \\A-c \\A-b \\b-d \\A-end \\b-end ; var input__ = input.readString(input_); const input_parsed = try Input.init(std.testing.allocator, &input__); try std.testing.expectEqual(@as(usize, 10), try part1(std.testing.allocator, &input_parsed)); try std.testing.expectEqual(@as(usize, 36), try part2(std.testing.allocator, &input_parsed)); } test "day 12 example 2" { const input_ = \\dc-end \\HN-start \\start-kj \\dc-start \\dc-HN \\LN-dc \\HN-end \\kj-sa \\kj-HN \\kj-dc ; var input__ = input.readString(input_); const input_parsed = try Input.init(std.testing.allocator, &input__); try std.testing.expectEqual(@as(usize, 19), try part1(std.testing.allocator, &input_parsed)); try std.testing.expectEqual(@as(usize, 103), try part2(std.testing.allocator, &input_parsed)); } test "day 12 example 3" { const input_ = \\fs-end \\he-DX \\fs-he \\start-DX \\pj-DX \\end-zg \\zg-sl \\zg-pj \\pj-he \\RW-he \\fs-DX \\pj-RW \\zg-RW \\start-pj \\he-WI \\zg-he \\pj-fs \\start-RW ; var input__ = input.readString(input_); const input_parsed = try Input.init(std.testing.allocator, &input__); try std.testing.expectEqual(@as(usize, 226), try part1(std.testing.allocator, &input_parsed)); try std.testing.expectEqual(@as(usize, 3509), try part2(std.testing.allocator, &input_parsed)); }
src/day12.zig
const std = @import("std"); const builtin = @import("builtin"); const Buffer = std.Buffer; const ArrayList = std.ArrayList; const Allocator = std.mem.Allocator; const warn = std.debug.warn; /// Top Level pub const Device = struct { name: Buffer, version: Buffer, description: Buffer, cpu: ?Cpu, /// Bus Interface Properties /// Smallest addressable unit in bits address_unit_bits: ?u32, /// The Maximum data bit width accessible within a single transfer max_bit_width: ?u32, /// Start register default properties reg_default_size: ?u32, reg_default_reset_value: ?u32, reg_default_reset_mask: ?u32, peripherals: Peripherals, interrupts: Interrupts, const Self = @This(); pub fn init(allocator: *Allocator) !Self { var name = try Buffer.init(allocator, ""); errdefer name.deinit(); var version = try Buffer.init(allocator, ""); errdefer version.deinit(); var description = try Buffer.init(allocator, ""); errdefer description.deinit(); var peripherals = Peripherals.init(allocator); errdefer peripherals; var interrupts = Interrupts.init(allocator); errdefer interrupts; return Self{ .name = name, .version = version, .description = description, .cpu = null, .address_unit_bits = null, .max_bit_width = null, .reg_default_size = null, .reg_default_reset_value = null, .reg_default_reset_mask = null, .peripherals = peripherals, .interrupts = interrupts, }; } pub fn deinit(self: *Self) void { self.name.deinit(); self.version.deinit(); self.description.deinit(); self.peripherals.deinit(); self.interrupts.deinit(); } pub fn format(self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: var) !void { const name = if (self.name.len() == 0) "unknown" else self.name.toSliceConst(); const version = if (self.version.len() == 0) "unknown" else self.version.toSliceConst(); const description = if (self.description.len() == 0) "unknown" else self.description.toSliceConst(); try out_stream.print( \\pub const device_name = "{}"; \\pub const device_revision = "{}"; \\pub const device_description = "{}"; \\ , .{ name, version, description }); if (self.cpu) |the_cpu| { try out_stream.print("{}\n", .{the_cpu}); } // now print peripherals for (self.peripherals.toSliceConst()) |peripheral| { try out_stream.print("{}\n", .{peripheral}); } // now print interrupt table try out_stream.writeAll("pub const interrupts = struct {\n"); for (self.interrupts.toSliceConst()) |interrupt| { if (interrupt.value) |int_value| { try out_stream.print( "pub const {} = {};\n", .{ interrupt.name.toSliceConst(), int_value }, ); } } try out_stream.writeAll("};"); return; } }; pub const Cpu = struct { name: Buffer, revision: Buffer, endian: Buffer, mpu_present: ?bool, fpu_present: ?bool, nvic_prio_bits: ?u32, vendor_systick_config: ?bool, const Self = @This(); pub fn init(allocator: *Allocator) !Self { var name = try Buffer.init(allocator, ""); errdefer name.deinit(); var revision = try Buffer.init(allocator, ""); errdefer revision.deinit(); var endian = try Buffer.init(allocator, ""); errdefer endian.deinit(); return Self{ .name = name, .revision = revision, .endian = endian, .mpu_present = null, .fpu_present = null, .nvic_prio_bits = null, .vendor_systick_config = null, }; } pub fn deinit(self: *Self) void { self.name.deinit(); self.revision.deinit(); self.endian.deinit(); } pub fn format(self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: var) !void { try out_stream.writeAll("\n"); const name = if (self.name.len() == 0) "unknown" else self.name.toSliceConst(); const revision = if (self.revision.len() == 0) "unknown" else self.revision.toSliceConst(); const endian = if (self.endian.len() == 0) "unknown" else self.endian.toSliceConst(); const mpu_present = self.mpu_present orelse false; const fpu_present = self.mpu_present orelse false; const vendor_systick_config = self.vendor_systick_config orelse false; try out_stream.print( \\pub const cpu = struct {{ \\ pub const name = "{}"; \\ pub const revision = "{}"; \\ pub const endian = "{}"; \\ pub const mpu_present = {}; \\ pub const fpu_present = {}; \\ pub const vendor_systick_config = {}; \\ , .{ name, revision, endian, mpu_present, fpu_present, vendor_systick_config }); if (self.nvic_prio_bits) |prio_bits| { try out_stream.print( \\ pub const nvic_prio_bits = {}; \\ , .{prio_bits}); } try out_stream.writeAll("};"); return; } }; pub const Peripherals = ArrayList(Peripheral); pub const Peripheral = struct { name: Buffer, group_name: Buffer, description: Buffer, base_address: ?u32, address_block: ?AddressBlock, registers: Registers, const Self = @This(); pub fn init(allocator: *Allocator) !Self { var name = try Buffer.init(allocator, ""); errdefer name.deinit(); var group_name = try Buffer.init(allocator, ""); errdefer group_name.deinit(); var description = try Buffer.init(allocator, ""); errdefer description.deinit(); var registers = Registers.init(allocator); errdefer registers.deinit(); return Self{ .name = name, .group_name = group_name, .description = description, .base_address = null, .address_block = null, .registers = registers, }; } pub fn copy(self: Self, allocator: *Allocator) !Self { var the_copy = try Self.init(allocator); errdefer the_copy.deinit(); try the_copy.name.append(self.name.toSliceConst()); try the_copy.group_name.append(self.group_name.toSliceConst()); try the_copy.description.append(self.description.toSliceConst()); the_copy.base_address = self.base_address; the_copy.address_block = self.address_block; for (self.registers.toSliceConst()) |self_register| { try the_copy.registers.append(try self_register.copy(allocator)); } return the_copy; } pub fn deinit(self: *Self) void { self.name.deinit(); self.group_name.deinit(); self.description.deinit(); self.registers.deinit(); } pub fn isValid(self: Self) bool { if (self.name.len() == 0) { return false; } _ = self.base_address orelse return false; return true; } pub fn format(self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: var) !void { try out_stream.writeAll("\n"); if (!self.isValid()) { try out_stream.writeAll("// Not enough info to print register value\n"); return; } const name = self.name.toSlice(); const description = if (self.description.len() == 0) "No description" else self.description.toSliceConst(); try out_stream.print( \\/// {} \\pub const {}_Base_Address = 0x{x}; \\ , .{ description, name, self.base_address.? }); // now print registers for (self.registers.toSliceConst()) |register| { try out_stream.print("{}\n", .{register}); } return; } }; pub const AddressBlock = struct { offset: ?u32, size: ?u32, usage: Buffer, const Self = @This(); pub fn init(allocator: *Allocator) !Self { var usage = try Buffer.init(allocator, ""); errdefer usage.deinit(); return Self{ .offset = null, .size = null, .usage = usage, }; } pub fn deinit(self: *Self) void { self.usage.deinit(); } }; pub const Interrupts = ArrayList(Interrupt); pub const Interrupt = struct { name: Buffer, description: Buffer, value: ?u32, const Self = @This(); pub fn init(allocator: *Allocator) !Self { var name = try Buffer.init(allocator, ""); errdefer name.deinit(); var description = try Buffer.init(allocator, ""); errdefer description.deinit(); return Self{ .name = name, .description = description, .value = null, }; } pub fn copy(self: Self, allocator: *Allocator) !Self { var the_copy = try Self.init(allocator); try the_copy.name.append(self.name.toSliceConst()); try the_copy.description.append(self.description.toSliceConst()); the_copy.value = self.value; return the_copy; } pub fn deinit(self: *Self) void { self.name.deinit(); self.description.deinit(); } pub fn isValid(self: Self) bool { if (self.name.len() == 0) { return false; } _ = self.value orelse return false; return true; } pub fn format(self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: var) !void { try out_stream.writeAll("\n"); if (!self.isValid()) { try output(context, "// Not enough info to print interrupt value\n"); return; } const name = self.name.toSlice(); const description = if (self.description.len() == 0) "No description" else self.description.toSliceConst(); try out_stream.print( \\/// {} \\pub const {} = {}; \\ , .{ description, name, value.? }); } }; const Registers = ArrayList(Register); pub const Register = struct { periph_containing: Buffer, name: Buffer, display_name: Buffer, description: Buffer, base_address: u32, // must come from peripheral address_offset: ?u32, size: u32, reset_value: u32, fields: Fields, access: Access = .ReadWrite, const Self = @This(); pub fn init(allocator: *Allocator, periph: []const u8, base_address: u32, reset_value: u32, size: u32) !Self { var prefix = try Buffer.init(allocator, ""); errdefer prefix.deinit(); var name = try Buffer.init(allocator, ""); errdefer name.deinit(); var display_name = try Buffer.init(allocator, ""); errdefer display_name.deinit(); var description = try Buffer.init(allocator, ""); errdefer description.deinit(); var fields = Fields.init(allocator); errdefer fields.deinit(); try prefix.replaceContents(periph); return Self{ .periph_containing = prefix, .name = name, .display_name = display_name, .description = description, .base_address = base_address, .address_offset = null, .size = size, .reset_value = reset_value, .fields = fields, }; } pub fn copy(self: Self, allocator: *Allocator) !Self { var the_copy = try Self.init(allocator, self.periph_containing.toSliceConst(), self.base_address, self.reset_value, self.size); try the_copy.name.append(self.name.toSliceConst()); try the_copy.display_name.append(self.display_name.toSliceConst()); try the_copy.description.append(self.description.toSliceConst()); the_copy.address_offset = self.address_offset; the_copy.access = self.access; for (self.fields.toSliceConst()) |self_field| { try the_copy.fields.append(try self_field.copy(allocator)); } return the_copy; } pub fn deinit(self: *Self) void { self.periph_containing.deinit(); self.name.deinit(); self.display_name.deinit(); self.description.deinit(); self.fields.deinit(); } pub fn isValid(self: Self) bool { if (self.name.len() == 0) { return false; } _ = self.address_offset orelse return false; return true; } pub fn format(self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: var) !void { try out_stream.writeAll("\n"); if (!self.isValid()) { try out_stream.writeAll("// Not enough info to print register value\n"); return; } const name = self.name.toSliceConst(); const periph = self.periph_containing.toSliceConst(); const description = if (self.description.len() == 0) "No description" else self.description.toSliceConst(); try out_stream.print( \\/// {} \\ , .{description}); try out_stream.print( \\pub const {}_{}_Address = 0x{x} + 0x{x}; \\pub const {}_{}_Reset_Value = 0x{x}; \\ , .{ // address periph, name, self.base_address, self.address_offset.?, // reset value periph, name, self.reset_value, }); var write_mask: u32 = 0; for (self.fields.toSliceConst()) |field| { if (field.bit_offset) |def_offset| { if (field.bit_width) |def_width| { if (field.access != .ReadOnly) { write_mask |= bitWidthToMask(def_width) << @truncate(u5, def_offset); } } } } const ptr_str = \\pub const {}_{}_Write_Mask = 0x{x}; \\pub const {}_{}_Ptr = @intToPtr(*volatile u{}, {}_{}_Address); \\ ; try out_stream.print(ptr_str, .{ periph, name, write_mask, periph, name, self.size, periph, name, }); // now print fields for (self.fields.toSliceConst()) |field| { try out_stream.print("{}\n", .{field}); } return; } }; pub const Access = enum { ReadOnly, WriteOnly, ReadWrite, }; pub const Fields = ArrayList(Field); pub const Field = struct { periph: Buffer, register: Buffer, name: Buffer, description: Buffer, bit_offset: ?u32, bit_width: ?u32, access: Access = .ReadWrite, const Self = @This(); pub fn init(allocator: *Allocator, periph_containing: []const u8, register_containing: []const u8) !Self { var periph = try Buffer.init(allocator, periph_containing); errdefer periph.deinit(); var register = try Buffer.init(allocator, register_containing); errdefer register.deinit(); var name = try Buffer.init(allocator, ""); errdefer name.deinit(); var description = try Buffer.init(allocator, ""); errdefer description.deinit(); return Self{ .periph = periph, .register = register, .name = name, .description = description, .bit_offset = null, .bit_width = null, }; } pub fn copy(self: Self, allocator: *Allocator) !Self { var the_copy = try Self.init(allocator, self.periph.toSliceConst(), self.register.toSliceConst()); try the_copy.name.append(self.name.toSliceConst()); try the_copy.description.append(self.description.toSliceConst()); the_copy.bit_offset = self.bit_offset; the_copy.bit_width = self.bit_width; the_copy.access = self.access; return the_copy; } pub fn deinit(self: *Self) void { self.periph.deinit(); self.register.deinit(); self.name.deinit(); self.description.deinit(); } pub fn format(self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: var) !void { try out_stream.writeAll("\n"); if (self.name.len() == 0) { try out_stream.writeAll("// No name to print field value\n"); return; } if ((self.bit_offset == null) or (self.bit_width == null)) { try out_stream.writeAll("// Not enough info to print field\n"); return; } const name = self.name.toSlice(); const periph = self.periph.toSliceConst(); const register = self.register.toSliceConst(); const description = if (self.description.len() == 0) "No description" else self.description.toSliceConst(); const offset = self.bit_offset.?; const base_mask = bitWidthToMask(self.bit_width.?); try out_stream.print( \\/// {} \\pub const {}_{}_{}_Offset = {}; \\pub const {}_{}_{}_Mask = 0x{x} << {}_{}_{}_Offset; \\pub inline fn {}_{}_{}(setting: u32) u32 {{ \\ return (setting & 0x{x}) << {}_{}_{}_Offset; \\}} \\ , .{ description, // offset periph, register, name, offset, // mask periph, register, name, base_mask, periph, register, name, // val periph, register, name, // setting base_mask, periph, register, name, }); return; } }; test "Field print" { var allocator = std.testing.allocator; const fieldDesiredPrint = \\ \\/// RNGEN comment \\pub const PERIPH_RND_RNGEN_Offset = 2; \\pub const PERIPH_RND_RNGEN_Mask = 0x1 << PERIPH_RND_RNGEN_Offset; \\pub inline fn PERIPH_RND_RNGEN(setting: u32) u32 { \\ return (setting & 0x1) << PERIPH_RND_RNGEN_Offset; \\} \\ \\ ; var output_buffer = try Buffer.init(allocator, ""); defer output_buffer.deinit(); var buf_stream = &std.io.BufferOutStream.init(&output_buffer).stream; var field = try Field.init(allocator, "PERIPH", "RND"); defer field.deinit(); try field.name.append("RNGEN"); try field.description.append("RNGEN comment"); field.bit_offset = 2; field.bit_width = 1; try buf_stream.print("{}\n", .{field}); std.testing.expect(output_buffer.eql(fieldDesiredPrint)); } test "Register Print" { var allocator = std.testing.allocator; const registerDesiredPrint = \\ \\/// RND comment \\pub const PERIPH_RND_Address = 0x24000 + 0x100; \\pub const PERIPH_RND_Reset_Value = 0x0; \\pub const PERIPH_RND_Write_Mask = 0x4; \\pub const PERIPH_RND_Ptr = @intToPtr(*volatile u32, PERIPH_RND_Address); \\ \\/// RNGEN comment \\pub const PERIPH_RND_RNGEN_Offset = 2; \\pub const PERIPH_RND_RNGEN_Mask = 0x1 << PERIPH_RND_RNGEN_Offset; \\pub inline fn PERIPH_RND_RNGEN(setting: u32) u32 { \\ return (setting & 0x1) << PERIPH_RND_RNGEN_Offset; \\} \\ \\ \\ ; var output_buffer = try Buffer.init(allocator, ""); defer output_buffer.deinit(); var buf_stream = &std.io.BufferOutStream.init(&output_buffer).stream; var register = try Register.init(allocator, "PERIPH", 0x24000, 0, 0x20); defer register.deinit(); try register.name.append("RND"); try register.description.append("RND comment"); register.address_offset = 0x100; register.size = 0x20; var field = try Field.init(allocator, "PERIPH", "RND"); defer field.deinit(); try field.name.append("RNGEN"); try field.description.append("RNGEN comment"); field.bit_offset = 2; field.bit_width = 1; field.access = .ReadWrite; // write field will exist try register.fields.append(field); try buf_stream.print("{}\n", .{register}); var expected = output_buffer.toSlice(); std.testing.expectEqualSlices(u8, expected, registerDesiredPrint); } test "Peripheral Print" { var allocator = std.testing.allocator; const peripheralDesiredPrint = \\ \\/// PERIPH comment \\pub const PERIPH_Base_Address = 0x24000; \\ \\/// RND comment \\pub const PERIPH_RND_Address = 0x24000 + 0x100; \\pub const PERIPH_RND_Reset_Value = 0x0; \\pub const PERIPH_RND_Write_Mask = 0x0; \\pub const PERIPH_RND_Ptr = @intToPtr(*volatile u32, PERIPH_RND_Address); \\ \\/// RNGEN comment \\pub const PERIPH_RND_RNGEN_Offset = 2; \\pub const PERIPH_RND_RNGEN_Mask = 0x1 << PERIPH_RND_RNGEN_Offset; \\pub inline fn PERIPH_RND_RNGEN(setting: u32) u32 { \\ return (setting & 0x1) << PERIPH_RND_RNGEN_Offset; \\} \\ \\ \\ \\ ; var output_buffer = try Buffer.init(allocator, ""); defer output_buffer.deinit(); var buf_stream = &std.io.BufferOutStream.init(&output_buffer).stream; var peripheral = try Peripheral.init(allocator); defer peripheral.deinit(); try peripheral.name.append("PERIPH"); try peripheral.description.append("PERIPH comment"); peripheral.base_address = 0x24000; var register = try Register.init(allocator, "PERIPH", peripheral.base_address.?, 0, 0x20); defer register.deinit(); try register.name.append("RND"); try register.description.append("RND comment"); register.address_offset = 0x100; register.size = 0x20; var field = try Field.init(allocator, "PERIPH", "RND"); defer field.deinit(); try field.name.append("RNGEN"); try field.description.append("RNGEN comment"); field.bit_offset = 2; field.bit_width = 1; field.access = .ReadOnly; // since only register, write field will not exist try register.fields.append(field); try peripheral.registers.append(register); try buf_stream.print("{}\n", .{peripheral}); std.testing.expectEqualSlices(u8, peripheralDesiredPrint, output_buffer.toSliceConst()); } fn bitWidthToMask(width: u32) u32 { const max_supported_bits = 32; const width_to_mask = blk: { comptime var mask_array: [max_supported_bits + 1]u32 = undefined; inline for (mask_array) |*item, i| { const i_use = if (i == 0) max_supported_bits else i; item.* = std.math.maxInt(@Type(builtin.TypeInfo{ .Int = .{ .is_signed = false, .bits = i_use, }, })); } break :blk mask_array; }; const width_to_mask_slice = width_to_mask[0..]; return width_to_mask_slice[if (width > max_supported_bits) 0 else width]; }
src/svd.zig
const std = @import("std"); const help = @import("./helpers.zig"); const EscapeCodes = struct { const smcup = "\x1b[?1049h\x1b[22;0;0t\x1b[2J\x1b[H"; const rmcup = "\x1b[2J\x1b[H\x1b[?1049l\x1b[23;0;0t"; }; fn print(msg: []const u8) !void { try std.io.getStdOut().writer().print("{}", .{msg}); } /// enters fullscreen /// fullscreen is a seperate screen that does not impact the screen you type commands on /// make sure to exit fullscreen before exit pub fn enterFullscreen() !void { try print(EscapeCodes.smcup); } /// exit fullscreen and restore the previous terminal state pub fn exitFullscreen() !void { try print(EscapeCodes.rmcup); } fn tcflags(comptime itms: anytype) std.os.tcflag_t { comptime { var res: std.os.tcflag_t = 0; for (itms) |itm| res |= @as(std.os.tcflag_t, @field(std.os, @tagName(itm))); return res; } } pub fn enterRawMode(stdin: std.fs.File) !std.os.termios { const origTermios = try std.os.tcgetattr(stdin.handle); var termios = origTermios; termios.lflag &= ~tcflags(.{ .ECHO, .ICANON, .ISIG, .IXON, .IEXTEN, .BRKINT, .INPCK, .ISTRIP, .CS8 }); try std.os.tcsetattr(stdin.handle, std.os.TCSA.FLUSH, termios); return origTermios; } pub fn exitRawMode(stdin: std.fs.File, orig: std.os.termios) !void { try std.os.tcsetattr(stdin.handle, std.os.TCSA.FLUSH, orig); } fn ioctl(fd: std.os.fd_t, request: u32, comptime ResT: type) !ResT { var res: ResT = undefined; while (true) { switch (std.os.errno(std.os.system.ioctl(fd, request, @ptrToInt(&res)))) { 0 => break, std.os.EBADF => return error.BadFileDescriptor, std.os.EFAULT => unreachable, // Bad pointer param std.os.EINVAL => unreachable, // Bad params std.os.ENOTTY => return error.RequestDoesNotApply, std.os.EINTR => continue, else => |err| return std.os.unexpectedErrno(err), } } return res; } const TermSize = struct { w: u16, h: u16 }; pub fn winSize(stdout: std.fs.File) !TermSize { var wsz: std.os.linux.winsize = try ioctl(stdout.handle, std.os.linux.TIOCGWINSZ, std.os.linux.winsize); return TermSize{ .w = wsz.ws_col, .h = wsz.ws_row }; } pub fn startCaptureMouse() !void { try print("\x1b[?1003;1004;1015;1006h"); } pub fn stopCaptureMouse() !void { try print("\x1b[?1003;1004;1015;1006l"); } pub const Event = union(enum) { const Keycode = union(enum) { character: u21, backspace, delete, enter, up, left, down, right, insert, tab, }; const KeyEvent = struct { modifiers: struct { ctrl: bool = false, shift: bool = false, } = .{}, keycode: Keycode, }; key: KeyEvent, resize: void, mouse: struct { x: u32, y: u32, button: MouseButton, direction: MouseDirection, ctrl: bool, alt: bool, shift: bool, }, scroll: struct { x: u32, y: u32, pixels: i32, ctrl: bool, alt: bool, shift: bool, }, focus, blur, none, const MouseButton = enum { none, left, middle, right }; const MouseDirection = enum { down, move, up }; pub fn from(text: []const u8) !Event { var resev: KeyEvent = .{ .keycode = .{ .character = 0 } }; var split = std.mem.tokenize(text, "+"); b: while (split.next()) |section| { inline for (.{ "ctrl", "shift" }) |modifier| { if (std.mem.eql(u8, section, modifier)) { if (@field(resev.modifiers, modifier)) return error.AlreadySet; @field(resev.modifiers, modifier) = true; continue :b; } } if (section.len == 1) { if (resev.keycode != .character or resev.keycode.character != 0) return error.DoubleSetCode; resev.keycode = .{ .character = section[0] }; continue :b; } inline for (@typeInfo(Keycode).Union.fields) |field| { if (field.field_type != void) continue; if (std.mem.eql(u8, section, field.name)) { resev.keycode = @field(Keycode, field.name); continue :b; } } std.debug.warn("Unused Section: `{}`\n", .{section}); return error.UnusedSection; } if (resev.keycode == .character and resev.keycode.character == 0) return error.NeverSetCode; return Event{ .key = resev }; } pub fn fromc(comptime text: []const u8) Event { return comptime Event.from(text) catch @compileError("bad event str"); } pub fn is(thsev: Event, comptime text: []const u8) bool { return std.meta.eql(thsev, comptime Event.from(text) catch @compileError("bad event str")); } // fun idea, functioniterator isn't good enough atm it seems fn formatIter(value: Event, out: anytype) void { switch (value) { .key => |k| { if (k.modifiers.ctrl) out.emit("ctrl"); if (k.modifiers.shift) out.emit("shift"); out.emit(std.meta.tagName(k.keycode)); }, else => { out.emit("Unsupported: "); out.emit(std.meta.tagName(value)); }, } } pub fn format(value: Event, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { // var fniter = help.FunctionIterator(formatIter, Event, []const u8).init(value); // fniter.start(); // var joinIter = help.iteratorJoin(fniter, "+"); // while (joinIter.next()) |it| { // try writer.writeAll(it); // } switch (value) { .key => |k| { try writer.writeAll("["); if (k.modifiers.ctrl) try writer.writeAll("ctrl+"); if (k.modifiers.shift) try writer.writeAll("shift+"); switch (k.keycode) { .character => |char| { if (char < 128) try writer.print("{c}", .{@intCast(u8, char)}) else try writer.print("{}", .{char}); }, else => |code| try writer.writeAll(std.meta.tagName(code)), } try writer.writeAll("]"); }, .resize => { try writer.writeAll(":resize:"); }, .mouse => |m| { try writer.writeAll("("); switch (m.direction) { .down => try writer.writeAll("↓"), .move => {}, .up => try writer.writeAll("↑"), } switch (m.button) { .left => try writer.writeAll("lmb "), .right => try writer.writeAll("rmb "), .middle => try writer.writeAll("mmb "), .none => {}, } if (m.ctrl) try writer.writeAll("ctrl "); if (m.alt) try writer.writeAll("alt "); if (m.shift) try writer.writeAll("shift "); try writer.print("{}, {})", .{ m.x, m.y }); }, .scroll => |m| { if (m.pixels < 0) try writer.print("↑{} ", .{-m.pixels}) // zig-fmt else try writer.print("↓{} ", .{m.pixels}); try writer.writeAll("("); if (m.ctrl) try writer.writeAll("ctrl "); if (m.alt) try writer.writeAll("alt "); if (m.shift) try writer.writeAll("shift "); try writer.print("{}, {})", .{ m.x, m.y }); }, else => { try writer.writeAll(":unknown "); try writer.writeAll(std.meta.tagName(value)); try writer.writeAll(":"); }, } } }; test "Event.from" { const somev = try Event.from("ctrl+c"); std.debug.warn("\n{}\n", .{somev}); } const IntRetV = struct { char: u8, val: u32 }; /// read a u32 from a stream /// returns the read u32 and the final read character /// undefined behaviours on overflow fn readInt(stream: anytype) !IntRetV { var res: u32 = 0; var itm = try stream.readByte(); while (itm >= '0' and itm <= '9') : (itm = try stream.readByte()) { res = (res * 10) + (itm - '0'); } return IntRetV{ .char = itm, .val = res }; } // TODO instead of signal handlers, use sigwaitinfo/sigtimedwait // and somehow wait for either a character or a signal (eg with select syntax #5263) // or syscall magic and wait for something on two streams and write to a stream or something // on signal. pub fn nextEvent(stdinf: std.fs.File) !?Event { const stdin = stdinf.reader(); const firstByte = stdin.readByte() catch return null; switch (firstByte) { // ctrl+k, ctrl+m don't work // also ctrl+[ allows you to type bad stuff that panics rn 1...8, 11...26 => |ch| return Event{ .key = .{ .modifiers = .{ .ctrl = true }, .keycode = .{ .character = ch - 1 + 'a' } } }, '\t' => return Event{ .key = .{ .keycode = .tab } }, '\x1b' => { switch (stdin.readByte() catch return null) { '[' => { switch (stdin.readByte() catch return null) { '1'...'9' => |num| { // if next byte is 1-9, this is a urxvt mouse event // readInt(stdin, &[_]u8{num, byte}) // and then the rest if ((stdin.readByte() catch return null) != '~') return error.UnsupportedEvent; switch (num) { '2' => return Event.fromc("insert"), '3' => return Event.fromc("delete"), else => return error.UnsupportedEvent, } }, 'A' => return Event.fromc("up"), 'B' => return Event.fromc("down"), 'D' => return Event.fromc("left"), 'C' => return Event.fromc("right"), 'O' => return Event.blur, 'I' => return Event.focus, '<' => { const MouseButtonData = packed struct { button: packed enum(u2) { left = 0, middle = 1, right = 2, none = 3 }, shift: u1, alt: u1, ctrl: u1, move: u1, scroll: u1, unused: u1, }; const b = readInt(stdin) catch return null; if (b.char != ';') return error.BadEscapeSequence; const x = readInt(stdin) catch return null; if (x.char != ';') return error.BadEscapeSequence; const y = readInt(stdin) catch return null; if (y.char != 'M' and y.char != 'm') return error.BadEscapeSequence; const data = @bitCast(MouseButtonData, @intCast(u8, b.val)); if (y.char == 'm' and data.move == 1) return error.BadEscapeSequence; // "mouse is moving and released at the same time" if (data.scroll == 1) return Event{ .scroll = .{ .x = x.val - 1, .y = y.val - 1, .pixels = switch (data.button) { .left => -3, .middle => 3, else => return error.BadScrollEvent, }, .ctrl = data.ctrl == 1, .alt = data.alt == 1, .shift = data.shift == 1, }, }; return Event{ .mouse = .{ .x = x.val - 1, .y = y.val - 1, .button = switch (data.button) { .left => Event.MouseButton.left, .middle => .middle, .right => .right, .none => .none, }, .direction = if (data.move == 1) Event.MouseDirection.move //zig fmt else if (y.char == 'm') Event.MouseDirection.up else .down, .ctrl = data.ctrl == 1, .alt = data.alt == 1, .shift = data.shift == 1, }, }; }, else => |chr| return error.UnsupportedEvent, } }, else => |esch| return error.UnsupportedEvent, } }, 10 => return Event{ .key = .{ .keycode = .enter } }, 32...126 => return Event{ .key = .{ .keycode = .{ .character = firstByte } } }, 127 => return Event{ .key = .{ .keycode = .backspace } }, 128...255 => { const len = std.unicode.utf8ByteSequenceLength(firstByte) catch return error.BadEscapeSequence; var read = [_]u8{ firstByte, undefined, undefined, undefined }; stdin.readNoEof(read[1..len]) catch return null; const unichar = std.unicode.utf8Decode(read[0..len]) catch return error.BadEscapeSequence; return Event{ .key = .{ .keycode = .{ .character = unichar } } }; }, else => return error.UnsupportedEvent, } } var cbRunning = false; var doResize = false; var mainLoopFn: fn () void = undefined; fn handleSigwinch(sig: i32, info: *const std.os.siginfo_t, ctx_ptr: ?*const c_void) callconv(.C) void { if (cbRunning) { doResize = true; } else { mainLoopFn(); } setSignalHandler(); } fn setSignalHandler() void { var act = std.os.Sigaction{ .sigaction = handleSigwinch, .mask = std.os.empty_sigset, .flags = (std.os.SA_SIGINFO | std.os.SA_RESTART | std.os.SA_RESETHAND), }; std.os.sigaction(std.os.SIGWINCH, &act, null); } /// data: any /// cb: fn (data: @TypeOf(data), event: Event) bool pub fn mainLoop(data: anytype, comptime cb: anytype, stdinF: std.fs.File) !void { const DataType = @TypeOf(data); const MLFnData = struct { var dataptr: usize = undefined; pub fn mainLoopFn_() void { if (!cb(@intToPtr(*const DataType, dataptr).*, .resize)) @panic("requested exit during resize handler. not supported."); } }; MLFnData.dataptr = @ptrToInt(&data); mainLoopFn = MLFnData.mainLoopFn_; setSignalHandler(); while (nextEvent(stdinF) catch @as(?Event, Event.none)) |ev| { cbRunning = true; if (!cb(data, ev)) break; cbRunning = false; // what is this while (doResize) { doResize = false; cbRunning = true; if (!cb(data, .resize)) break; cbRunning = false; } } } // \x1b[30m // \x1b[90m pub const Color = struct { const ColorCode = enum(u3) { black = 0, red = 1, green = 2, yellow = 3, blue = 4, magenta = 5, cyan = 6, white = 7, }; code: ColorCode, bright: bool, pub fn from(comptime code: anytype) Color { const tt = @tagName(code); if (comptime std.mem.startsWith(u8, tt, "br")) return .{ .bright = true, .code = @field(ColorCode, tt[2..]) }; return .{ .bright = false, .code = @field(ColorCode, tt) }; } /// returned []const u8 is embedded in the binary and freeing is not necessary const BGFGMode = enum { bg, fg }; pub fn escapeCode(color: Color, mode: BGFGMode) []const u8 { // ah yes, readable code inline for (@typeInfo(ColorCode).Enum.fields) |colrfld| { inline for (.{ .bg, .fg }) |bgfgmode| { inline for (.{ true, false }) |bright| { if (@enumToInt(color.code) == colrfld.value and mode == bgfgmode and color.bright == bright) { comptime const vtxt = switch (@as(BGFGMode, bgfgmode)) { .bg => if (bright) "10" else "4", .fg => if (bright) "9" else "3", }; return "\x1b[" ++ vtxt ++ &[_]u8{colrfld.value + '0'} ++ "m"; } } } } unreachable; // all cases handled } }; // \x1b[40m // \x1b[100m pub const Style = struct { fg: ?Color = null, bg: ?Color = null, mode: enum { normal, bold, italic } = .normal, }; /// set the text style. if oldStyle is specified, find the closest path to /// it rather than the full style. pub fn setTextStyle(writer: anytype, style: Style, oldStyle: ?Style) !void { if (oldStyle) |ostyl| if (std.meta.eql(style, ostyl)) return; // nothing to do try writer.writeAll("\x1b(B\x1b[m"); // reset if (style.fg) |fg| try writer.writeAll(fg.escapeCode(.fg)); if (style.bg) |bg| try writer.writeAll(bg.escapeCode(.bg)); switch (style.mode) { .normal => {}, .bold => try writer.writeAll("\x1b[1m"), .italic => try writer.writeAll("\x1b[3m"), } } pub fn moveCursor(writer: anytype, x: u32, y: u32) !void { try writer.print("\x1b[{};{}f", .{ y + 1, x + 1 }); } pub fn clearScreen(writer: anytype) !void { try writer.writeAll("\x1b[2J"); } pub fn clearToEol(writer: anytype) !void { try writer.writeAll("\x1b[0K"); } // instead of requiring the user to manage cursor positions // why not store the entire screen here // and then when it changes, diff it and only update what changed // ez
src/cli.zig
const std = @import("std"); const atomic = std.atomic; const mem = std.mem; const testing = std.testing; /// Create a new Zighlander to manage a singleton of type T. pub fn Zighlander(comptime T: type) type { return struct { const Self = @This(); const Singleton = struct { instance: *T, ref_count: atomic.Atomic(usize), }; allocator: *mem.Allocator, singleton: ?Singleton, /// Initialize the Zighlander, not the contained singleton. pub fn init(allocator: *mem.Allocator) Self { return Self{ .allocator = allocator, .singleton = null, }; } /// get a reference to the singleton. Creates a new singleton if necessary, which must then /// be initialized by the caller. pub fn get(self: *Self) !*T { if (self.singleton) |*s| { _ = s.ref_count.fetchAdd(1, .SeqCst); return s.instance; } self.singleton = Singleton{ .instance = try self.allocator.create(T), .ref_count = atomic.Atomic(usize).init(1), }; return self.singleton.?.instance; } /// put decrements the reference counter, de-initializing and destroying the singleton if it /// reaches zero. pub fn put(self: *Self) void { if (self.singleton) |*s| { if (s.ref_count.fetchSub(1, .SeqCst) == 1) self.deinit(); } } /// destroy the singleton, unconditionally, regardless of reference count. pub fn deinit(self: *Self) void { if (self.singleton) |*s| { self.allocator.destroy(s.instance); self.singleton = null; } } /// isNull checks if the singleton is there. pub fn isNull(self: Self) bool { return self.singleton == null; } }; } test "Zighlander" { var allocator = std.testing.allocator; // Create the unique Zighlander to manage the singleton. var only_one = Zighlander(std.ArrayList(u8)).init(allocator); // This deinit on the Zighlander itself will destroy the singleton no matter how many references // are still active. If you don't want this behavior, omit this defer call and manage the references // with the get and put methods as shown below. Even if you manage the references with get and // put, you can still make this defer to ensure clean up on program exit. defer only_one.deinit(); // Call get to retrieve a reference to the singleton instance. var one = try only_one.get(); // NOTE! The first time you get a reference, you must initialize it because it's just a pointer // to garbage memory. Failure to do this will result in either crashes or undefined behavior. one.* = std.ArrayList(u8).init(allocator); // Likewise, make sure to deinit your data if necessary when you're done with it. defer one.deinit(); // Changes made to the singleton will be seen by all references to it. NOTE! The reference counting // is thread-safe thanks to atomics, but the singleton instance itself is NOT thread-safe. for ([3]u8{ 1, 2, 3 }) |i| { try one.append(i); } // Grab another reference to the singleton instance. var two = try only_one.get(); // The put method decremets the reference counter by 1; when it reaches 0, the singleton instance // will be de-initialized and destroyed. defer only_one.put(); // You can check if references are still valid with the isNull methodd. try testing.expect(!only_one.isNull()); // Modifications on reference 'one' are visible through reference 'two'. try testing.expect(two.items.len == 3); }
src/zighlander.zig
const std = @import("std"); usingnamespace std.os.windows; pub extern "kernel32" fn VirtualAllocEx( hProcess: HANDLE, lpAddress: ?LPVOID, dwSize: SIZE_T, flAllocationTypew: DWORD, flProtect: DWORD, ) callconv(WINAPI) ?LPVOID; pub extern "kernel32" fn VirtualFreeEx( hProcess: HANDLE, lpAddress: LPVOID, dwSize: SIZE_T, dwFreeType: DWORD, ) callconv(WINAPI) BOOL; pub extern "kernel32" fn OpenProcess( dwDesiredAccess: DWORD, bInheritHandle: BOOL, dwProcessId: DWORD, ) callconv(WINAPI) ?HANDLE; pub extern "kernel32" fn WriteProcessMemory( hProcess: HANDLE, lpBaseAddress: LPVOID, lpBuffer: LPCVOID, nSize: SIZE_T, lpNumberOfBytesWritten: ?*SIZE_T, ) callconv(WINAPI) BOOL; pub extern "kernel32" fn GetModuleHandleA( lpModuleName: LPCSTR, ) callconv(WINAPI) ?HMODULE; pub extern "kernel32" fn CreateRemoteThread( hProcess: HANDLE, lpThreadAttributes: ?LPSECURITY_ATTRIBUTES, dwStackSize: SIZE_T, lpStartAddress: LPTHREAD_START_ROUTINE, lpParameter: LPVOID, dwCreationFlags: DWORD, lpThreadId: ?LPDWORD, ) callconv(WINAPI) ?HANDLE; pub extern "kernel32" fn LoadLibraryA( lib_file_name: [*:0]const u8, ) callconv(WINAPI) HMODULE; pub const HARDERROR_RESPONSE_OPTION = extern enum(c_ulong) { OptionAbortRetryIgnore, OptionOk, OptionOkCancel, OptionRetryCancel, OptionYesNo, OptionYesNoCancel, OptionShutdownSystem, OptionOkNoWait, OptionCancelTryContinue, _, }; pub const HARDERROR_RESPONSE = extern enum(c_ulong) { ResponseReturnToCaller, ResponseNotHandled, ResponseAbort, ResponseCancel, ResponseIgnore, ResponseNo, ResponseOk, ResponseRetry, ResponseYes, ResponseTryAgain, ResponseContinue, _, }; pub extern "ntdll" fn NtRaiseHardError( error_status: NTSTATUS, number_of_parameters: ULONG, unicode_string_parameter_mask: ULONG, parameters: [*]usize, response_option: HARDERROR_RESPONSE_OPTION, response: ?*HARDERROR_RESPONSE, ) callconv(WINAPI) NTSTATUS; pub extern "ntdll" fn LdrLoadDll( DllPath: ?[*:0]const u16, DllCharacteristics: ?*ULONG, DllName: *const UNICODE_STRING, DllHandle: *c_void, ) callconv(WINAPI) NTSTATUS; pub extern "kernel32" fn VirtualProtect( lpAddress: *const c_void, dwSize: usize, flNewProtect: u32, lpflOldProtect: *u32, ) callconv(WINAPI) BOOL; pub const IMAGE_DOS_HEADER = extern struct { magic: [2]u8, cblp: WORD, cp: WORD, crlc: WORD, cparhdr: WORD, minalloc: WORD, maxalloc: WORD, ss: WORD, sp: WORD, csum: WORD, ip: WORD, cs: WORD, lfarlc: WORD, ovno: WORD, res: [8]u8, oemid: WORD, oeminfo: WORD, res2: [20]u8, lfanew: LONG, }; pub const IMAGE_FILE_HEADER = extern struct { magic: [4]u8, machine: std.coff.MachineType, number_of_sections: WORD, time_date_stamp: DWORD, pointer_to_symbol_table: DWORD, number_of_symbols: DWORD, size_of_optional_header: WORD, characteristics: WORD, }; pub const IMAGE_DATA_DIRECTORY = extern struct { rva: DWORD, size: DWORD, }; pub const PE_MAGIC = extern enum(u16) { PE_ROM_IMAGE = 0x0107, PE_32BIT = 0x010B, PE_64BIT = 0x020B, }; pub const PE_SUBSYSTEM = extern enum(u16) { UNKNOWN = 0x0, NATIVE = 0x1, WINDOWS_GUI = 0x2, WINDOWS_CUI = 0x3, OS2_CUI = 0x5, POSIX_CUI = 0x7, NATIVE_WINDOWS = 0x8, WINDOWS_CE_GUI = 0x9, EFI_APPLICATION = 0xa, EFI_BOOT_SERVICE_DRIVER = 0xb, EFI_RUNTIME_DRIVER = 0xc, EFI_ROM = 0xd, XBOX = 0xe, WINDOWS_BOOT_APPLICATION = 0x10, }; pub const PE_DLL_CHARACTERISTICS = struct { pub const _0001 = 0x1; pub const _0002 = 0x2; pub const _0004 = 0x4; pub const _0008 = 0x8; pub const HIGH_ENTROPY_VA = 0x20; pub const DYNAMIC_BASE = 0x40; pub const FORCE_INTEGRITY = 0x80; pub const NX_COMPAT = 0x100; pub const NO_ISOLATION = 0x200; pub const NO_SEH = 0x400; pub const NO_BIND = 0x800; pub const APPCONTAINER = 0x1000; pub const WDM_DRIVER = 0x2000; pub const GUARD_CF = 0x4000; pub const TERMINAL_SERVER_AWARE = 0x8000; }; pub const IMAGE_OPTIONAL_HEADER = extern struct { magic: PE_MAGIC, major_linker_version: UCHAR, minor_linker_version: UCHAR, size_of_code: ULONG, size_of_initialized_data: ULONG, size_of_uninitialized_data: ULONG, address_of_entry_point: ULONG, base_of_code: ULONG, image_base: usize, section_alignment: ULONG, file_alignment: ULONG, major_operating_system_version: USHORT, minor_operating_system_version: USHORT, major_image_version: USHORT, minor_image_version: USHORT, major_subsystem_version: USHORT, minor_subsystem_version: USHORT, win32_version_value: ULONG, size_of_image: ULONG, size_of_headers: ULONG, check_sum: ULONG, subsystem: PE_SUBSYSTEM, dll_characteristics: u16, size_of_stack_reserve: usize, size_of_stack_commit: usize, size_of_heap_reserve: usize, size_of_heap_commit: usize, loader_flags: ULONG, number_of_rva_and_sizes: ULONG, export_table_entry: IMAGE_DATA_DIRECTORY, import_table_entry: IMAGE_DATA_DIRECTORY, resource_table_entry: IMAGE_DATA_DIRECTORY, exception_table_entry: IMAGE_DATA_DIRECTORY, certificate_table_entry: IMAGE_DATA_DIRECTORY, base_relocation_table_entry: IMAGE_DATA_DIRECTORY, debug_entry: IMAGE_DATA_DIRECTORY, architecture_entry: IMAGE_DATA_DIRECTORY, global_ptr_entry: IMAGE_DATA_DIRECTORY, tls_table_entry: IMAGE_DATA_DIRECTORY, load_config_table_entry: IMAGE_DATA_DIRECTORY, bound_import_entry: IMAGE_DATA_DIRECTORY, iat_entry: IMAGE_DATA_DIRECTORY, delay_import_descriptor_entry: IMAGE_DATA_DIRECTORY, clr_runtime_header_entry: IMAGE_DATA_DIRECTORY, reserved_entry: IMAGE_DATA_DIRECTORY, }; ///valid for x86-64, TODO: check for 32 bit pub const EXPORT_DIRECTORY_TABLE = extern struct { exportFlags: u32, timeDateStamp: u32, majorVersion: u16, minorVersion: u16, nameRva: u32, ordinalBase: u32, addressTableEntries: u32, numberOfNamePointers: u32, exportAddressTableRva: u32, namePointerRva: u32, ordinalTableRva: u32, }; const Entry = enum { export_, import, resource, exception, certificate, baseRelocation, debug, architecture, global_ptr, tls_table, load_config, bound_import, delay_import, clr_runtime, reserved, }; pub const IMAGE_SECTION_HEADER = extern struct { name: [8]UCHAR, virtual_size: ULONG, virtual_address: ULONG, size_of_raw_data: ULONG, pointer_to_raw_data: ULONG, pointer_to_relocations: ULONG, pointer_to_linenumbers: ULONG, number_of_relocations: USHORT, number_of_linenumbers: USHORT, characteristics: ULONG, }; pub const IMAGE_NT_HEADERS = extern struct { signature: DWORD, file_header: IMAGE_FILE_HEADER, optional_header: IMAGE_OPTIONAL_HEADER, }; pub const IMAGE_EXPORT_DIRECTORY = extern struct { characteristics: ULONG, time_date_stamp: ULONG, major_version: USHORT, minor_version: USHORT, name: ULONG, base: ULONG, number_of_functions: ULONG, number_of_names: ULONG, address_of_functions: ULONG, address_of_names: ULONG, address_of_name_ordinals: ULONG, }; pub const PE_SECTION_FLAGS = extern enum(u32) { RESERVED_0001 = 0x1, RESERVED_0002 = 0x2, RESERVED_0004 = 0x4, TYPE_NO_PAD = 0x8, RESERVED_0010 = 0x10, CNT_CODE = 0x20, CNT_INITIALIZED_DATA = 0x40, CNT_UNINITIALIZED_DATA = 0x80, LNK_OTHER = 0x100, LNK_INFO = 0x200, RESERVED_0400 = 0x400, LNK_REMOVE = 0x800, LNK_COMDAT = 0x1000, GPREL = 0x8000, MEM_PURGEABLE = 0x10000, MEM_16BIT = 0x20000, MEM_LOCKED = 0x40000, MEM_PRELOAD = 0x80000, LNK_NRELOC_OVFL = 0x1000000, MEM_DISCARDABLE = 0x2000000, MEM_NOT_CACHED = 0x4000000, MEM_NOT_PAGED = 0x8000000, MEM_SHARED = 0x10000000, MEM_EXECUTE = 0x20000000, MEM_READ = 0x40000000, MEM_WRITE = 0x80000000, }; pub const SectionFlags = packed struct { reserved_0001: bool, reserved_0002: bool, reserved_0004: bool, type_no_pad: bool, reserved_0010: bool, cnt_code: bool, cnt_initialized_data: bool, cnt_uninitialized_data: bool, lnk_other: bool, lnk_info: bool, reserved_0400: bool, lnk_remove: bool, lnk_comdat: bool, pad_0: bool, pad_1: bool, gprel: bool, mem_purgeable: bool, mem_16_bit: bool, mem_locked: bool, mem_preload: bool, pad_2: bool, pad_3: bool, pad_4: bool, pad_5: bool, lnk_nreloc_ovfl: bool, mem_discardable: bool, mem_not_cached: bool, mem_not_paged: bool, mem_shared: bool, mem_execute: bool, mem_read: bool, mem_write: bool, }; pub const Import_Directory_Table = extern struct { import_lookup_table_rva: u32, time_date_stamp: u32, forwarder_chain: u32, name_rva: u32, import_address_table_rva: u32, }; pub const RelocationBlock = packed struct { rva: u32, size: u32, }; pub const RelocationPatch = packed struct { offset: u12, reloc_type: enum(u4) { absolute, addr64, addr32, addr32_nb, rel32, rel32_1, rel32_2, rel32_3, rel32_4, rel32_5, section, secrel, secrel7, token, srel32, pair, // sspan32, wtf is this? why does this not fit in u4? }, }; comptime { if (@bitSizeOf(RelocationPatch) != 16 or @sizeOf(RelocationPatch) != 2) { @compileError("wrong size!"); } }
externs.zig
const std = @import("std"); const assert = std.debug.assert; const log = std.log; const mem = std.mem; const tokenizer = @import("tokenizer.zig"); const Allocator = mem.Allocator; const TokenIndex = tokenizer.TokenIndex; const TokenIterator = tokenizer.TokenIterator; const Tokenizer = tokenizer.Tokenizer; const Token = tokenizer.Token; pub const Scope = struct { nodes: std.ArrayListUnmanaged(Node) = .{}, }; const Loc = struct { start: TokenIndex, end: TokenIndex, }; pub const Node = union(enum) { @"enum": EnumNode, }; const EnumNode = struct { loc: Loc, name: TokenIndex, fields: std.ArrayListUnmanaged(FieldTuple) = .{}, const FieldTuple = std.meta.Tuple(&[_]type{ TokenIndex, TokenIndex }); }; const ParseError = error{ OutOfMemory, ParseFail, }; const ParseResult = union(enum) { ok: void, err: *ErrorMsg, }; const ErrorMsg = struct { msg: []const u8, loc: TokenIndex, }; pub const Parser = struct { arena: Allocator, token_it: *TokenIterator, scope: *Scope, err_msg: ?*ErrorMsg = null, fn fail(parser: *Parser, comptime format: []const u8, args: anytype) ParseError { assert(parser.err_msg == null); const err_msg = try parser.arena.create(ErrorMsg); err_msg.* = .{ .msg = try std.fmt.allocPrint(parser.arena, format, args), .loc = parser.token_it.pos, }; parser.err_msg = err_msg; return error.ParseFail; } pub fn parse(parser: *Parser) !ParseResult { parser.parseInternal() catch |err| switch (err) { error.ParseFail => { return ParseResult{ .err = parser.err_msg.? }; }, else => |e| return e, }; return ParseResult{ .ok = {} }; } fn parseInternal(parser: *Parser) ParseError!void { while (true) { const pos = parser.token_it.pos; const token = parser.token_it.next(); if (token.id == .eof) break; switch (token.id) { .keyword_enum => { try parser.parseEnum(pos); }, else => { return parser.fail("TODO unhandled token", .{}); }, } } } fn parseEnum(parser: *Parser, start: TokenIndex) ParseError!void { var enum_node = EnumNode{ .loc = .{ .start = start, .end = undefined, }, .name = undefined, }; enum_node.name = try parser.expectToken(.identifier); _ = try parser.expectToken(.l_brace); while (true) { const pos = parser.token_it.pos; const token = parser.token_it.next(); switch (token.id) { .identifier => { const field_name = pos; _ = try parser.expectToken(.equal); const field_value = try parser.expectToken(.int_literal); _ = try parser.expectToken(.semicolon); try enum_node.fields.append(parser.arena, .{ field_name, field_value }); }, .r_brace => { enum_node.loc.end = pos; break; }, else => { return parser.fail("unexpected token: {}", .{token.id}); }, } } // log.debug("enum := {}", .{enum_node}); try parser.scope.nodes.append(parser.arena, Node{ .@"enum" = enum_node, }); } fn expectToken(parser: *Parser, id: Token.Id) ParseError!TokenIndex { const pos = parser.token_it.pos; _ = parser.token_it.peek() orelse return parser.fail("unexpected end of file", .{}); const token = parser.token_it.next(); if (token.id == id) { return pos; } else { parser.token_it.seekTo(pos); return parser.fail("wrong token: expected {}, found {}", .{ id, token.id, }); } } };
src/parser.zig
const std = @import("std"); const os = std.os; const net = std.net; const Allocator = std.mem.Allocator; const RESP3 = @import("./parser.zig").RESP3Parser; const CommandSerializer = @import("./serializer.zig").CommandSerializer; const OrErr = @import("./types/error.zig").OrErr; pub const Buffering = union(enum) { NoBuffering, Fixed: usize, }; pub const Logging = union(enum) { NoLogging, Logging, }; pub const Client = RedisClient(.NoBuffering, .NoLogging); pub const BufferedClient = RedisClient(.{ .Fixed = 4096 }, .NoLogging); pub fn RedisClient(buffering: Buffering, _: Logging) type { const ReadBuffer = switch (buffering) { .NoBuffering => void, .Fixed => |b| std.io.BufferedReader(b, net.Stream.Reader), }; const WriteBuffer = switch (buffering) { .NoBuffering => void, .Fixed => |b| std.io.BufferedWriter(b, net.Stream.Writer), }; return struct { conn: net.Stream, reader: switch (buffering) { .NoBuffering => net.Stream.Reader, .Fixed => ReadBuffer.Reader, }, writer: switch (buffering) { .NoBuffering => net.Stream.Writer, .Fixed => WriteBuffer.Writer, }, readBuffer: ReadBuffer, writeBuffer: WriteBuffer, readLock: if (std.io.is_async) std.event.Lock else void, writeLock: if (std.io.is_async) std.event.Lock else void, // Connection state broken: bool = false, const Self = @This(); /// Initializes a Client on a connection / pipe provided by the user. pub fn init(self: *Self, conn: net.Stream) !void { self.conn = conn; switch (buffering) { .NoBuffering => { self.reader = conn.reader(); self.writer = conn.writer(); }, .Fixed => { self.readBuffer = ReadBuffer{ .unbuffered_reader = conn.reader() }; self.reader = self.readBuffer.reader(); self.writeBuffer = WriteBuffer{ .unbuffered_writer = conn.writer() }; self.writer = self.writeBuffer.writer(); }, } if (std.io.is_async) { self.readLock = std.event.Lock{}; self.writeLock = std.event.Lock{}; } self.broken = false; self.send(void, .{ "HELLO", "3" }) catch |err| { self.broken = true; if (err == error.GotErrorReply) { return error.ServerTooOld; } else { return err; } }; } pub fn close(self: Self) void { self.conn.close(); } /// Sends a command to Redis and tries to parse the response as the specified type. pub fn send(self: *Self, comptime T: type, cmd: anytype) !T { return self.pipelineImpl(T, cmd, .{ .one = {} }); } /// Like `send`, can allocate memory. pub fn sendAlloc(self: *Self, comptime T: type, allocator: *Allocator, cmd: anytype) !T { return self.pipelineImpl(T, cmd, .{ .one = {}, .ptr = allocator }); } /// Performs a Redis MULTI/EXEC transaction using pipelining. /// It's mostly provided for convenience as the same result /// can be achieved by making explicit use of `pipe` and `pipeAlloc`. pub fn trans(self: *Self, comptime Ts: type, cmds: anytype) !Ts { return self.transactionImpl(Ts, cmds, .{}); } /// Like `trans`, but can allocate memory. pub fn transAlloc(self: *Self, comptime Ts: type, allocator: *Allocator, cmds: anytype) !Ts { return transactionImpl(self, Ts, cmds, .{ .ptr = allocator }); } fn transactionImpl(self: *Self, comptime Ts: type, cmds: anytype, allocator: anytype) !Ts { // TODO: this is not threadsafe. _ = try self.send(void, .{"MULTI"}); try self.pipe(void, cmds); if (@hasField(@TypeOf(allocator), "ptr")) { return self.sendAlloc(Ts, allocator.ptr, .{"EXEC"}); } else { return self.send(Ts, .{"EXEC"}); } } /// Sends a group of commands more efficiently than sending them one by one. pub fn pipe(self: *Self, comptime Ts: type, cmds: anytype) !Ts { return pipelineImpl(self, Ts, cmds, .{}); } /// Like `pipe`, but can allocate memory. pub fn pipeAlloc(self: *Self, comptime Ts: type, allocator: *Allocator, cmds: anytype) !Ts { return pipelineImpl(self, Ts, cmds, .{ .ptr = allocator }); } fn pipelineImpl(self: *Self, comptime Ts: type, cmds: anytype, allocator: anytype) !Ts { // TODO: find a way to express some of the metaprogramming requirements // in a more clear way. Using @hasField this way is ugly. { // if (self.broken) return error.BrokenConnection; // errdefer self.broken = true; } var heldWrite: std.event.Lock.Held = undefined; var heldRead: std.event.Lock.Held = undefined; var heldReadFrame: @Frame(std.event.Lock.acquire) = undefined; // If we're doing async/await we need to first grab the lock // for the write stream. Once we have it, we also need to queue // for the read lock, but we don't have to acquire it fully yet. // For this reason we don't await `self.readLock.acquire()` and in // the meantime we start writing to the write stream. if (std.io.is_async) { heldWrite = self.writeLock.acquire(); heldReadFrame = async self.readLock.acquire(); } var heldReadFrameNotAwaited = true; defer if (std.io.is_async and heldReadFrameNotAwaited) { heldRead = await heldReadFrame; heldRead.release(); }; { // We add a block to release the write lock before we start // reading from the read stream. defer if (std.io.is_async) heldWrite.release(); // Serialize all the commands if (@hasField(@TypeOf(allocator), "one")) { try CommandSerializer.serializeCommand(self.writer, cmds); } else { inline for (std.meta.fields(@TypeOf(cmds))) |field| { const cmd = @field(cmds, field.name); // try ArgSerializer.serialize(&self.out.stream, args); try CommandSerializer.serializeCommand(self.writer, cmd); } } // Here is where the write lock gets released by the `defer` statement. if (buffering == .Fixed) { if (std.io.is_async) { // TODO: see if this stuff can be implemented nicely // so that you don't have to depend on magic numbers & implementation details. const held = self.writeLock.mutex.acquire(); defer held.release(); if (self.writeLock.head == 1) { try self.writeBuffer.flush(); } } else { try self.writeBuffer.flush(); } } } if (std.io.is_async) { heldReadFrameNotAwaited = false; heldRead = await heldReadFrame; } defer if (std.io.is_async) heldRead.release(); // TODO: error procedure if (@hasField(@TypeOf(allocator), "one")) { if (@hasField(@TypeOf(allocator), "ptr")) { return RESP3.parseAlloc(Ts, allocator.ptr, self.reader); } else { return RESP3.parse(Ts, self.reader); } } else { var result: Ts = undefined; if (Ts == void) { const cmd_num = std.meta.fields(@TypeOf(cmds)).len; comptime var i: usize = 0; inline while (i < cmd_num) : (i += 1) { try RESP3.parse(void, self.reader); } return; } else { switch (@typeInfo(Ts)) { .Struct => { inline for (std.meta.fields(Ts)) |field| { if (@hasField(@TypeOf(allocator), "ptr")) { @field(result, field.name) = try RESP3.parseAlloc(field.field_type, allocator.ptr, self.reader); } else { @field(result, field.name) = try RESP3.parse(field.field_type, self.reader); } } }, .Array => { var i: usize = 0; while (i < Ts.len) : (i += 1) { if (@hasField(@TypeOf(allocator), "ptr")) { result[i] = try RESP3.parseAlloc(Ts.Child, allocator.ptr, self.reader); } else { result[i] = try RESP3.parse(Ts.Child, self.reader); } } }, .Pointer => |ptr| { switch (ptr.size) { .One => { if (@hasField(@TypeOf(allocator), "ptr")) { result = try RESP3.parseAlloc(Ts, allocator.ptr, self.reader); } else { result = try RESP3.parse(Ts, self.reader); } }, .Many => { if (@hasField(@TypeOf(allocator), "ptr")) { result = try allocator.alloc(ptr.child, ptr.size); errdefer allocator.free(result); for (result) |*elem| { elem.* = try RESP3.parseAlloc(Ts.Child, allocator.ptr, self.reader); } } else { @compileError("Use sendAlloc / pipeAlloc / transAlloc to decode pointer types."); } }, } }, else => @compileError("Unsupported type"), } } return result; } } }; } test "docs" { @import("std").testing.refAllDecls(Client); }
src/client.zig
usingnamespace @import("root").preamble; /// IPC message pub const Message = packed struct { /// Opaque value opaque_val: usize, /// Message data data: [56]u8, /// Encode reference to the token fn encodeTokenToOpaque(self: *@This(), token: *Token) void { self.opaque_val = @ptrToInt(token); } /// Decode token reference from opaque value fn decodeTokenFromOpaque(self: *@This()) *Token { return @intToPtr(*Token, self.opaque_val); } }; /// IPC token. Process that gets its hands on the token can accept it and use it to send messages /// Token also allows owner to set quota on the maximum number of messages that could be sent at once pub const Token = struct { /// Reference count refcount: usize = 1, /// Reference to the owning mailbox owner: *Mailbox, /// True if token has been shut down is_shut_down: bool = false, /// Token lock lock: os.thread.Spinlock = .{}, /// Number of messages that could be sent current_quota: usize, /// Token quota token_quota: usize, /// Token opaque value opaque_val: usize, /// Allocator used to allocate the token allocator: *std.mem.Allocator, /// Create token pub fn create( allocator: *std.mem.Allocator, owner: *Mailbox, quota: usize, opaque_val: usize, ) !*@This() { const result = try allocator.create(@This()); errdefer allocator.destroy(result); const int_state = owner.lock.lock(); defer owner.lock.unlock(int_state); if (owner.available_quota < quota) { return error.NotEnoughBuffers; } const borrowed = owner.borrow(); owner.available_quota -= quota; result.* = .{ .owner = borrowed, .current_quota = quota, .token_quota = quota, .opaque_val = opaque_val, .allocator = allocator, }; return result; } /// Attempt to reserve one message slot fn reserve(self: *@This()) !void { const int_state = self.lock.lock(); defer self.lock.unlock(int_state); if (self.is_shut_down) { return error.TokenExpired; } if (self.current_quota == 0) { return error.QuotaExceeded; } self.current_quota -= 1; } /// Free message slot fn freeSlot(self: *@This()) void { const int_state = self.lock.lock(); defer self.lock.unlock(int_state); self.current_quota += 1; } /// Borrow reference to the token pub fn borrow(self: *@This()) *@This() { _ = @atomicRmw(usize, &self.refcount, .Add, 1, .AcqRel); return self; } /// Drop reference to the toke pub fn drop(self: *@This()) void { if (@atomicRmw(usize, &self.refcount, .Sub, 1, .AcqRel) == 1) { self.dispose(); } } /// Dispose token fn dispose(self: *@This()) void { self.owner.drop(); self.allocator.destroy(self); } /// Shutdown token pub fn shutdown(self: *@This()) void { const int_state = self.lock.lock(); self.is_shut_down = true; self.owner.lock.grab(); self.owner.available_quota += self.token_quota; self.owner.lock.ungrab(); self.lock.unlock(int_state); self.drop(); } /// Send message to token pub fn send(self: *@This(), msg: *Message) !void { try self.reserve(); const int_state = self.owner.lock.lock(); defer self.owner.lock.unlock(int_state); if (self.owner.is_shut_down) { return error.MailboxUnreachable; } if (self.owner.sleep_queue.dequeue()) |sleep_node| { sleep_node.recv_buf.opaque_val = self.opaque_val; sleep_node.recv_buf.data = msg.data; os.thread.scheduler.wake(sleep_node.task); } else { const send_node = self.owner.free_queue.dequeue().?; const send_buf = self.owner.msgQueueNodeToBuffer(send_node); send_buf.encodeTokenToOpaque(self.borrow()); send_buf.data = msg.data; self.owner.pending_queue.enqueue(send_node); } } }; /// IPC mailbox. Allows to recieve IPC messages. pub const Mailbox = struct { /// Message queue node const MsgQueueNode = struct { /// Queue node hook: lib.containers.queue.Node = .{}, }; /// Thread sleep queue node const TaskSleepQueueNode = struct { /// Queue node hook: lib.containers.queue.Node = .{}, /// Pointer to the recieve buffer recv_buf: *Message, /// Pointer to the sleeping task task: *os.thread.Task, }; /// Mailbox spinlock lock: os.thread.Spinlock = .{}, /// Reference count refcount: usize = 1, /// Message buffers messages: []Message, /// Message queue nodes msg_queue_nodes: []MsgQueueNode, /// Free buffers queue free_queue: lib.containers.queue.Queue(MsgQueueNode, "hook") = .{}, /// Pending messages queue pending_queue: lib.containers.queue.Queue(MsgQueueNode, "hook") = .{}, /// Sleep queue sleep_queue: lib.containers.queue.Queue(TaskSleepQueueNode, "hook") = .{}, /// Allocator used to allocate the token allocator: *std.mem.Allocator, /// True if mailbox was shut down is_shut_down: bool = false, /// Available quota for new token creation available_quota: usize, /// Create new mailbox pub fn create(allocator: *std.mem.Allocator, quota: usize) !*@This() { const result = try allocator.create(@This()); errdefer allocator.destroy(result); const msg_bufs = try allocator.alloc(Message, quota); errdefer allocator.free(msg_bufs); const msg_nodes = try allocator.alloc(MsgQueueNode, quota); errdefer allocator.free(msg_nodes); result.* = .{ .messages = msg_bufs, .msg_queue_nodes = msg_nodes, .allocator = allocator, .available_quota = quota, }; for (msg_nodes) |*node| { result.free_queue.enqueue(node); } return result; } /// Borrow reference to the mailbox pub fn borrow(self: *@This()) *@This() { _ = @atomicRmw(usize, &self.refcount, .Add, 1, .AcqRel); return self; } /// Drop reference to the mailbox pub fn drop(self: *@This()) void { if (@atomicRmw(usize, &self.refcount, .Sub, 1, .AcqRel) == 1) { self.dispose(); } } /// Dispose mailbox fn dispose(self: *@This()) void { self.allocator.free(self.messages); self.allocator.free(self.msg_queue_nodes); self.allocator.destroy(self); } /// Shutdown mailbox pub fn shutdown(self: *@This()) void { const int_state = self.lock.lock(); defer self.lock.unlock(int_state); self.is_shut_down = true; while (self.pending_queue.dequeue()) |incoming| { const msg_buf = self.msgQueueNodeToBuffer(incoming); const token = msg_buf.decodeTokenFromOpaque(); token.drop(); } } /// Convert message queue node pointer to message buffer pointer fn msgQueueNodeToBuffer(self: *const @This(), node: *MsgQueueNode) *Message { return &self.messages[lib.util.pointers.getIndex(node, self.msg_queue_nodes)]; } /// Convert message buffer pointer to message queue node pointer fn bufferToMsgQueueNode(self: *const @This(), buf: *Message) *MsgQueueNode { return &self.msg_queue_nodes[lib.util.pointers.getIndex(buf, self.messages)]; } /// Recieve message pub fn recieve(self: *@This(), buf: *Message) void { const int_state = self.lock.lock(); if (self.pending_queue.dequeue()) |incoming| { const msg_buf = self.msgQueueNodeToBuffer(incoming); const token = msg_buf.decodeTokenFromOpaque(); const opaque_val = token.opaque_val; buf.data = msg_buf.data; buf.opaque_val = opaque_val; self.free_queue.enqueue(incoming); self.lock.unlock(int_state); token.freeSlot(); token.drop(); } else { var sleep_node: TaskSleepQueueNode = .{ .task = os.platform.get_current_task(), .recv_buf = buf, }; self.sleep_queue.enqueue(&sleep_node); os.thread.scheduler.waitReleaseSpinlock(&self.lock); os.platform.set_interrupts(int_state); } } };
subprojects/flork/src/kepler/ipc.zig
const std = @import("std"); const print = std.debug.print; const ArgParser = @import("arg_parser.zig").ArgParser; const Strand = @import("search.zig").Strand; const Mode = enum { dna, protein, }; pub const Args = struct { query: [std.fs.MAX_PATH_BYTES:0]u8 = undefined, db: [std.fs.MAX_PATH_BYTES:0]u8 = undefined, out: [std.fs.MAX_PATH_BYTES:0]u8 = undefined, min_identity: f32 = undefined, strand: Strand = .both, mode: Mode = .dna, max_hits: u32 = 1, max_rejects: u32 = 16, }; const ArgsError = error{ InsufficientArgs, }; fn printUsage() void { print( \\Zig-powered nsearch \\ \\Usage: \\ nsearchz --query <queryfile> --db <dbfile> --out <outfile> --min-identity <minidentity> [--max-hits <maxaccepts>] [--max-rejects <maxrejects>] [--protein] [--strand <strand>] \\ \\Options: \\ --min-identity <minidentity> Minimum identity threshold (e.g. 0.8). \\ --max-hits <maxaccepts> Maximum number of successful hits reported for one query [default: 1]. \\ --max-rejects <maxrejects> Abort after this many candidates were rejected [default: 16]. \\ --strand <strand> Strand to search on (plus, minus or both). If minus (or both), queries are reverse complemented [default: both]. \\ --mode <mode> dna or protein [default: dna]. , .{}); } pub fn parseArgs(allocator: std.mem.Allocator) !Args { const required = [_][]const u8{ "--query", "--db", "--out", "--min-identity", }; const is_arg_missing = for (required) |req| { const found = for (std.os.argv) |arg| { if (std.mem.eql(u8, req, std.mem.sliceTo(arg, 0))) break true; } else false; if (!found) break true; } else false; if (is_arg_missing) { printUsage(); return ArgsError.InsufficientArgs; } var args = Args{}; try ArgParser(Args).parse(allocator, &args); return args; }
src/args.zig
const std = @import("std"); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var global_allocator = gpa.allocator(); var buffer: [1024]u8 = undefined; var fixed_allocator = std.heap.FixedBufferAllocator.init(buffer[0..]); var allocator = fixed_allocator.allocator(); pub fn main() !void { const stdout = std.io.getStdOut().writer(); const n = try get_n(); var perm = try allocator.alloc(usize, n); var perm1 = try allocator.alloc(usize, n); var count = try allocator.alloc(usize, n); var max_flips_count: usize = 0; var perm_count: usize = 0; var checksum: isize = 0; for (perm1) |*e, i| { e.* = i; } var r = n; loop: { while (true) { while (r != 1) : (r -= 1) { count[r - 1] = r; } for (perm) |_, i| { perm[i] = perm1[i]; } var flips_count: usize = 0; while (true) { const k = perm[0]; if (k == 0) { break; } const k2 = (k + 1) >> 1; var i: usize = 0; while (i < k2) : (i += 1) { std.mem.swap(usize, &perm[i], &perm[k - i]); } flips_count += 1; } max_flips_count = std.math.max(max_flips_count, flips_count); if (perm_count % 2 == 0) { checksum += @intCast(isize, flips_count); } else { checksum -= @intCast(isize, flips_count); } while (true) : (r += 1) { if (r == n) { break :loop; } const perm0 = perm1[0]; var i: usize = 0; while (i < r) { const j = i + 1; perm1[i] = perm1[j]; i = j; } perm1[r] = perm0; count[r] -= 1; if (count[r] > 0) { break; } } perm_count += 1; } } try stdout.print("{d}\nPfannkuchen({d}) = {d}\n", .{ checksum, n, max_flips_count }); } fn get_n() !usize { const args = try std.process.argsAlloc(global_allocator); defer std.process.argsFree(global_allocator, args); if (args.len > 1) { return try std.fmt.parseInt(usize, args[1], 10); } else { return 10; } }
bench/algorithm/fannkuch-redux/1.zig
const std = @import("../../std.zig"); const maxInt = std.math.maxInt; const linux = std.os.linux; const SYS = linux.SYS; const iovec = std.os.iovec; const iovec_const = std.os.iovec_const; const socklen_t = linux.socklen_t; const stack_t = linux.stack_t; const sigset_t = linux.sigset_t; const uid_t = linux.uid_t; const gid_t = linux.gid_t; const pid_t = linux.pid_t; const sockaddr = linux.sockaddr; const timespec = linux.timespec; pub fn syscall0(number: SYS) usize { return asm volatile ("svc #0" : [ret] "={r0}" (-> usize), : [number] "{r7}" (@enumToInt(number)), : "memory" ); } pub fn syscall1(number: SYS, arg1: usize) usize { return asm volatile ("svc #0" : [ret] "={r0}" (-> usize), : [number] "{r7}" (@enumToInt(number)), [arg1] "{r0}" (arg1), : "memory" ); } pub fn syscall2(number: SYS, arg1: usize, arg2: usize) usize { return asm volatile ("svc #0" : [ret] "={r0}" (-> usize), : [number] "{r7}" (@enumToInt(number)), [arg1] "{r0}" (arg1), [arg2] "{r1}" (arg2), : "memory" ); } pub fn syscall3(number: SYS, arg1: usize, arg2: usize, arg3: usize) usize { return asm volatile ("svc #0" : [ret] "={r0}" (-> usize), : [number] "{r7}" (@enumToInt(number)), [arg1] "{r0}" (arg1), [arg2] "{r1}" (arg2), [arg3] "{r2}" (arg3), : "memory" ); } pub fn syscall4(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize { return asm volatile ("svc #0" : [ret] "={r0}" (-> usize), : [number] "{r7}" (@enumToInt(number)), [arg1] "{r0}" (arg1), [arg2] "{r1}" (arg2), [arg3] "{r2}" (arg3), [arg4] "{r3}" (arg4), : "memory" ); } pub fn syscall5(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize { return asm volatile ("svc #0" : [ret] "={r0}" (-> usize), : [number] "{r7}" (@enumToInt(number)), [arg1] "{r0}" (arg1), [arg2] "{r1}" (arg2), [arg3] "{r2}" (arg3), [arg4] "{r3}" (arg4), [arg5] "{r4}" (arg5), : "memory" ); } pub fn syscall6( number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize, arg6: usize, ) usize { return asm volatile ("svc #0" : [ret] "={r0}" (-> usize), : [number] "{r7}" (@enumToInt(number)), [arg1] "{r0}" (arg1), [arg2] "{r1}" (arg2), [arg3] "{r2}" (arg3), [arg4] "{r3}" (arg4), [arg5] "{r4}" (arg5), [arg6] "{r5}" (arg6), : "memory" ); } /// This matches the libc clone function. pub extern fn clone( func: switch (@import("builtin").zig_backend) { .stage1 => fn (arg: usize) callconv(.C) u8, else => *const fn (arg: usize) callconv(.C) u8, }, stack: usize, flags: u32, arg: usize, ptid: *i32, tls: usize, ctid: *i32, ) usize; pub fn restore() callconv(.Naked) void { return asm volatile ("svc #0" : : [number] "{r7}" (@enumToInt(SYS.sigreturn)), : "memory" ); } pub fn restore_rt() callconv(.Naked) void { return asm volatile ("svc #0" : : [number] "{r7}" (@enumToInt(SYS.rt_sigreturn)), : "memory" ); } pub const MMAP2_UNIT = 4096; pub const O = struct { pub const CREAT = 0o100; pub const EXCL = 0o200; pub const NOCTTY = 0o400; pub const TRUNC = 0o1000; pub const APPEND = 0o2000; pub const NONBLOCK = 0o4000; pub const DSYNC = 0o10000; pub const SYNC = 0o4010000; pub const RSYNC = 0o4010000; pub const DIRECTORY = 0o40000; pub const NOFOLLOW = 0o100000; pub const CLOEXEC = 0o2000000; pub const ASYNC = 0o20000; pub const DIRECT = 0o200000; pub const LARGEFILE = 0o400000; pub const NOATIME = 0o1000000; pub const PATH = 0o10000000; pub const TMPFILE = 0o20040000; pub const NDELAY = NONBLOCK; }; pub const F = struct { pub const DUPFD = 0; pub const GETFD = 1; pub const SETFD = 2; pub const GETFL = 3; pub const SETFL = 4; pub const SETOWN = 8; pub const GETOWN = 9; pub const SETSIG = 10; pub const GETSIG = 11; pub const GETLK = 12; pub const SETLK = 13; pub const SETLKW = 14; pub const RDLCK = 0; pub const WRLCK = 1; pub const UNLCK = 2; pub const SETOWN_EX = 15; pub const GETOWN_EX = 16; pub const GETOWNER_UIDS = 17; }; pub const LOCK = struct { pub const SH = 1; pub const EX = 2; pub const UN = 8; pub const NB = 4; }; pub const MAP = struct { /// stack-like segment pub const GROWSDOWN = 0x0100; /// ETXTBSY pub const DENYWRITE = 0x0800; /// mark it as an executable pub const EXECUTABLE = 0x1000; /// pages are locked pub const LOCKED = 0x2000; /// don't check for reservations pub const NORESERVE = 0x4000; }; pub const VDSO = struct { pub const CGT_SYM = "__vdso_clock_gettime"; pub const CGT_VER = "LINUX_2.6"; }; pub const HWCAP = struct { pub const SWP = 1 << 0; pub const HALF = 1 << 1; pub const THUMB = 1 << 2; pub const @"26BIT" = 1 << 3; pub const FAST_MULT = 1 << 4; pub const FPA = 1 << 5; pub const VFP = 1 << 6; pub const EDSP = 1 << 7; pub const JAVA = 1 << 8; pub const IWMMXT = 1 << 9; pub const CRUNCH = 1 << 10; pub const THUMBEE = 1 << 11; pub const NEON = 1 << 12; pub const VFPv3 = 1 << 13; pub const VFPv3D16 = 1 << 14; pub const TLS = 1 << 15; pub const VFPv4 = 1 << 16; pub const IDIVA = 1 << 17; pub const IDIVT = 1 << 18; pub const VFPD32 = 1 << 19; pub const IDIV = IDIVA | IDIVT; pub const LPAE = 1 << 20; pub const EVTSTRM = 1 << 21; }; pub const Flock = extern struct { type: i16, whence: i16, __pad0: [4]u8, start: off_t, len: off_t, pid: pid_t, __unused: [4]u8, }; pub const msghdr = extern struct { name: ?*sockaddr, namelen: socklen_t, iov: [*]iovec, iovlen: i32, control: ?*anyopaque, controllen: socklen_t, flags: i32, }; pub const msghdr_const = extern struct { name: ?*const sockaddr, namelen: socklen_t, iov: [*]const iovec_const, iovlen: i32, control: ?*const anyopaque, controllen: socklen_t, flags: i32, }; pub const blksize_t = i32; pub const nlink_t = u32; pub const time_t = isize; pub const mode_t = u32; pub const off_t = i64; pub const ino_t = u64; pub const dev_t = u64; pub const blkcnt_t = i64; // The `stat` definition used by the Linux kernel. pub const Stat = extern struct { dev: dev_t, __dev_padding: u32, __ino_truncated: u32, mode: mode_t, nlink: nlink_t, uid: uid_t, gid: gid_t, rdev: dev_t, __rdev_padding: u32, size: off_t, blksize: blksize_t, blocks: blkcnt_t, atim: timespec, mtim: timespec, ctim: timespec, ino: ino_t, pub fn atime(self: @This()) timespec { return self.atim; } pub fn mtime(self: @This()) timespec { return self.mtim; } pub fn ctime(self: @This()) timespec { return self.ctim; } }; pub const timeval = extern struct { tv_sec: i32, tv_usec: i32, }; pub const timezone = extern struct { tz_minuteswest: i32, tz_dsttime: i32, }; pub const mcontext_t = extern struct { trap_no: usize, error_code: usize, oldmask: usize, arm_r0: usize, arm_r1: usize, arm_r2: usize, arm_r3: usize, arm_r4: usize, arm_r5: usize, arm_r6: usize, arm_r7: usize, arm_r8: usize, arm_r9: usize, arm_r10: usize, arm_fp: usize, arm_ip: usize, arm_sp: usize, arm_lr: usize, arm_pc: usize, arm_cpsr: usize, fault_address: usize, }; pub const ucontext_t = extern struct { flags: usize, link: ?*ucontext_t, stack: stack_t, mcontext: mcontext_t, sigmask: sigset_t, regspace: [64]u64, }; pub const Elf_Symndx = u32;
lib/std/os/linux/arm-eabi.zig
const std = @import("std"); const Object = @import("value.zig").Object; const String = @import("value.zig").String; const Value = @import("value.zig").Value; const vm = @import("vm.zig").vm; const Data = union(enum) { junked: void, string: *String, object: *Object, }; pub const HeapId = usize; pub const Heap = struct { // FIXME: We are using the allocator provided by the VM here (probably a GPA), // we probably need a smarter allocator though allocator: std.mem.Allocator, data: std.ArrayList(Data), used: std.ArrayList(bool), next_id: usize = 0, free_ids: std.AutoHashMap(HeapId, void), string_pool: std.StringHashMap(*String), const garbage_on_each_alloc = true; const Self = @This(); pub fn init(allocator: std.mem.Allocator) Self { return Self{ .allocator = allocator, .data = std.ArrayList(Data).init(allocator), .used = std.ArrayList(bool).init(allocator), .free_ids = std.AutoHashMap(HeapId, void).init(allocator), .string_pool = std.StringHashMap(*String).init(allocator), }; } pub fn deinit(self: *Self) void { // Cleanup remaining entries for (self.data.items) |*data| { self.destroy(data); } self.string_pool.deinit(); self.free_ids.deinit(); self.used.deinit(); self.data.deinit(); } fn destroy(self: *Self, data: *Data) void { switch (data.*) { .string => |s| { _ = self.string_pool.remove(s.str()); s.deinit(); self.allocator.destroy(s); }, .object => |o| { o.deinit(); self.allocator.destroy(o); }, .junked => {}, } data.* = Data{ .junked = {} }; } fn garbage(self: *Self) void { if (!vm().running) return; var roots = vm().gatherRoots(); for (roots) |root| { self.mark(root); } for (self.used.items) |used, id| { if (!used) { self.destroy(&self.data.items[id]); self.free_ids.put(id, {}) catch unreachable; } } std.mem.set(bool, self.used.items, false); } fn mark(self: *Self, value: *const Value) void { switch (value.*) { .string => |s| self.used.items[s.id] = true, .object => |o| { if (!self.used.items[o.id]) { self.used.items[o.id] = true; // Recurse var it = o.members.valueIterator(); while (it.next()) |v| { self.mark(&v.*); } } }, else => {}, // Non managed data } } fn create(self: *Self, comptime T: type) !*T { if (garbage_on_each_alloc) { self.garbage(); } const id = self.acquireId(); // var alloc_result = self.allocator.create(T); if (self.allocator.create(T)) |ptr| { ptr.* = T.init(id, self.allocator); return ptr; } else |err| { // Try to garbage, then try allocating again self.garbage(); var ptr = self.allocator.create(T) catch return err; ptr.* = T.init(id, self.allocator); return ptr; } } fn acquireId(self: *Self) HeapId { var id = @as(HeapId, 0); if (self.free_ids.count() == 0) { id = self.next_id; self.next_id += 1; } else { var it = self.free_ids.keyIterator(); id = it.next().?.*; _ = self.free_ids.remove(id); } return id; } fn insertData(self: *Self, id: HeapId, data: Data) void { if (id >= self.data.items.len) { self.data.append(data) catch unreachable; self.used.append(false) catch unreachable; } else { self.data.items[id] = data; } } pub fn makeObject(self: *Self) *Object { var object = self.create(Object) catch unreachable; self.insertData(object.id, Data{ .object = object }); return object; } pub fn makeString(self: *Self) *String { var string = self.create(String) catch unreachable; self.insertData(string.id, Data{ .string = string }); return string; } // pub fn copyString(self: *Self, source: []const u8) HeapId { // var string = Data{ // .string = self.alloc(u8, source.len), // }; // std.mem.copy(u8, string.string, source); // var id = self.next_id; // self.next_id += 1; // self.entries.put(id, Value{ .data = string }) catch unreachable; // FIXME: Same // return id; // } };
src/gc.zig
const std = @import("std"); const print = std.debug.print; const Op = enum { AND, OR, LSHIFT, RSHIFT, NOT, }; const Wire = union(enum) { name: [2]u8, constant: u16, }; const Gate = struct { operands: [2]Wire, operand_count: u8, op: ?Op, }; pub fn main() anyerror!void { const allocator = std.heap.page_allocator; var file = try std.fs.cwd().openFile( "./inputs/day07.txt", .{ .read = true, }, ); var reader = std.io.bufferedReader(file.reader()).reader(); var line = std.ArrayList(u8).init(allocator); defer line.deinit(); var connections = std.AutoHashMap([2]u8, Gate).init(allocator); defer connections.deinit(); while (reader.readUntilDelimiterArrayList(&line, '\n', 100)) { var tokens = std.mem.tokenize(u8, line.items, " "); var gate = Gate{ .operands = undefined, .operand_count = 0, .op = null, }; while (tokens.next()) |token| { if (std.mem.eql(u8, token, "->")) { break; } else if (std.mem.eql(u8, token, "AND")) { gate.op = Op.AND; } else if (std.mem.eql(u8, token, "OR")) { gate.op = Op.OR; } else if (std.mem.eql(u8, token, "LSHIFT")) { gate.op = Op.LSHIFT; } else if (std.mem.eql(u8, token, "RSHIFT")) { gate.op = Op.RSHIFT; } else if (std.mem.eql(u8, token, "NOT")) { gate.op = Op.NOT; } else if (std.ascii.isDigit(token[0])) { gate.operands[gate.operand_count] = Wire{ .constant = try std.fmt.parseInt(u16, token, 10) }; gate.operand_count += 1; } else { var name = [2]u8{ 0, 0 }; std.mem.copy(u8, &name, token); gate.operands[gate.operand_count] = Wire{ .name = name }; gate.operand_count += 1; } } var key = [2]u8{ 0, 0 }; std.mem.copy(u8, &key, tokens.next().?); try connections.put(key, gate); } else |err| { if (err != error.EndOfStream) { return err; } } const a_key = [2]u8{ 'a', 0 }; // PART 1 var resolved = try resolve(allocator, connections); const a = resolved.get(a_key).?; print("Part 1 | a: {d}\n", .{a}); resolved.deinit(); // PART 2 const new_b = Gate{ .operands = [2]Wire{ Wire{ .constant = a }, undefined }, .operand_count = 1, .op = null }; try connections.put([2]u8{ 'b', 0 }, new_b); resolved = try resolve(allocator, connections); const new_a = resolved.get(a_key).?; print("Part 2 | a: {d}\n", .{new_a}); resolved.deinit(); } fn resolve(allocator: *std.mem.Allocator, connections: std.AutoHashMap([2]u8, Gate)) anyerror!std.AutoHashMap([2]u8, u16) { var resolved = std.AutoHashMap([2]u8, u16).init(allocator); var todo = std.ArrayList([2]u8).init(allocator); defer todo.deinit(); try todo.append([2]u8{ 'a', 0 }); while (todo.popOrNull()) |name| { if (resolved.contains(name)) { continue; } const gate = connections.get(name).?; var resolved_operands: [2]u16 = undefined; var resolved_operand_count: u8 = 0; var un_resolved_operands: [2][2]u8 = undefined; var un_resolved_operand_count: u8 = 0; for (gate.operands[0..gate.operand_count]) |operand| { switch (operand) { Wire.constant => |c| { resolved_operands[resolved_operand_count] = c; resolved_operand_count += 1; }, Wire.name => |n| { if (resolved.get(n)) |v| { resolved_operands[resolved_operand_count] = v; resolved_operand_count += 1; } else { un_resolved_operands[un_resolved_operand_count] = n; un_resolved_operand_count += 1; } }, } } if (un_resolved_operand_count > 0) { try todo.append(name); for (un_resolved_operands[0..un_resolved_operand_count]) |u| { try todo.append(u); } } else { if (gate.op) |op| { switch (op) { Op.AND => { std.debug.assert(resolved_operand_count == 2); try resolved.put(name, resolved_operands[0] & resolved_operands[1]); }, Op.OR => { std.debug.assert(resolved_operand_count == 2); try resolved.put(name, resolved_operands[0] | resolved_operands[1]); }, Op.LSHIFT => { std.debug.assert(resolved_operand_count == 2); try resolved.put(name, resolved_operands[0] << @intCast(u4, resolved_operands[1])); }, Op.RSHIFT => { std.debug.assert(resolved_operand_count == 2); try resolved.put(name, resolved_operands[0] >> @intCast(u4, resolved_operands[1])); }, Op.NOT => { std.debug.assert(resolved_operand_count == 1); try resolved.put(name, ~resolved_operands[0]); }, } } else { std.debug.assert(resolved_operand_count == 1); try resolved.put(name, resolved_operands[0]); } } } return resolved; }
src/day07.zig
usingnamespace @import("ncurses").ncurses; const WIN_BORDER = struct { ls: chtype, rs: chtype, ts: chtype, bs: chtype, tl: chtype, tr: chtype, bl: chtype, br: chtype, }; const WIN = struct { startx: c_int, starty: c_int, height: c_int, width: c_int, border: WIN_BORDER, }; pub fn main() anyerror!void { var win: WIN = undefined; var ch: c_int = undefined; _ = try initscr(); defer endwin() catch {}; try start_color(); try cbreak(); try stdscr.keypad(true); try noecho(); try init_pair(1, COLOR_CYAN, COLOR_BLACK); try init_win_params(&win); try attron(COLOR_PAIR(1)); try printw("Press F1 to exit", .{}); try attroff(COLOR_PAIR(1)); try print_win_params(&win); try refresh(); try create_box(&win, true); ch = try getch(); while (ch != KEY_F(1)) : (ch = try getch()) { switch (ch) { KEY_LEFT => { try create_box(&win, false); win.startx -= 1; try create_box(&win, true); }, KEY_RIGHT => { try create_box(&win, false); win.startx += 1; try create_box(&win, true); }, KEY_UP => { try create_box(&win, false); win.starty -= 1; try create_box(&win, true); }, KEY_DOWN => { try create_box(&win, false); win.starty += 1; try create_box(&win, true); }, else => {}, } } } fn init_win_params(p_win: *WIN) !void { p_win.*.height = 3; p_win.*.width = 10; p_win.*.starty = @divTrunc(LINES - p_win.height, 2); p_win.*.startx = @divTrunc(COLS - p_win.width, 2); p_win.*.border.ls = '|'; p_win.*.border.rs = '|'; p_win.*.border.ts = '-'; p_win.*.border.bs = '-'; p_win.*.border.tl = '+'; p_win.*.border.tr = '+'; p_win.*.border.bl = '+'; p_win.*.border.br = '+'; } fn print_win_params(p_win: *WIN) !void { try mvprintw(25, 0, "%d %d %d %d", .{ p_win.startx, p_win.starty, p_win.width, p_win.height }); try refresh(); } fn create_box(p_win: *WIN, flag: bool) !void { var i: c_int = undefined; var j: c_int = undefined; var x: c_int = undefined; var y: c_int = undefined; var w: c_int = undefined; var h: c_int = undefined; x = p_win.startx; y = p_win.starty; w = p_win.width; h = p_win.height; if (flag) { try mvaddch(y, x, p_win.border.tl); try mvaddch(y, x + w, p_win.border.tr); try mvaddch(y + h, x, p_win.border.bl); try mvaddch(y + h, x + w, p_win.border.br); try mvhline(y, x + 1, p_win.border.ts, w - 1); try mvhline(y + h, x + 1, p_win.border.bs, w - 1); try mvvline(y + 1, x, p_win.border.ls, h - 1); try mvvline(y + 1, x + w, p_win.border.rs, h - 1); } else { j = y; while (j <= y + h) : (j += 1) { i = x; while (i <= x + w) : (i += 1) { try mvaddch(j, i, ' '); } } } }
examples/borders.zig
const std = @import("std"); const builtin = @import("builtin"); const assert = std.debug.assert; const assertError = std.debug.assertError; const mem = std.mem; const Allocator = mem.Allocator; const Error = Allocator.Error; pub const Seal = struct { allocator: Allocator, wrapped_allocator: *Allocator, count: std.atomic.Int(u64), allowed_leaks: u64, pub fn init(allocator: *Allocator) Seal { var self_allocator: Allocator = undefined; if (builtin.mode == builtin.Mode.Debug or builtin.mode == builtin.Mode.ReleaseSafe){ self_allocator = Allocator { .allocFn = alloc, .reallocFn = realloc, .freeFn = free, }; } else { self_allocator = Allocator { .allocFn = allocator.allocFn, .reallocFn = allocator.reallocFn, .freeFn = allocator.freeFn, }; } return Seal { .wrapped_allocator = allocator, .allocator = self_allocator, .count = std.atomic.Int(u64).init(0), .allowed_leaks = 0, }; } fn alloc(allocself: *Allocator, byte_count: usize, alignment: u29) Error![]u8 { const self = @fieldParentPtr(Seal, "allocator", allocself); const ret = try self.wrapped_allocator.allocFn(self.wrapped_allocator, byte_count, alignment); _ = self.count.incr(); return ret; } fn realloc(allocself: *Allocator, old_mem: []u8, new_mem_size: usize, alignment: u29) Error![]u8 { const self = @fieldParentPtr(Seal, "allocator", allocself); return try self.wrapped_allocator.reallocFn( self.wrapped_allocator, old_mem, new_mem_size, alignment ); } fn free(allocself: *Allocator, old_mem: []u8) void { const self = @fieldParentPtr(Seal, "allocator", allocself); var ret = self.wrapped_allocator.freeFn(self.wrapped_allocator, old_mem); _ = self.count.decr(); return ret; } pub fn deinit(self: *Seal) !void { if (builtin.mode != builtin.Mode.Debug and builtin.mode != builtin.Mode.ReleaseSafe){ return; } if (self.count.get() > self.allowed_leaks) { return error.LeakDetected; } } pub fn allowLeaks(self: *Seal, num_of_leaks: u64) void { self.allowed_leaks = num_of_leaks; } }; test "Wrapping another allocator" { var glob_alloc = std.debug.global_allocator; var seal = Seal.init(glob_alloc); defer seal.deinit() catch {@panic("Leaked memory");}; var allocator = &seal.allocator; var one: []u32 = try allocator.alloc(u32, 1); one[0] = 1; assert(one[0] == 1); allocator.free(one); } test "Throw error on mem leakage" { var glob_alloc = std.debug.global_allocator; var seal = Seal.init(glob_alloc); var allocator = &seal.allocator; const num = try allocator.createOne(u32); assertError(seal.deinit(), error.LeakDetected); } test "Allow a value to be leaked" { var glob_alloc = std.debug.global_allocator; var seal = Seal.init(glob_alloc); defer seal.deinit() catch {@panic("Leaked memory");}; seal.allowLeaks(1); var allocator = &seal.allocator; const num = try allocator.createOne(u32); defer allocator.destroy(num); const num2 = try allocator.createOne(u32); }
seal.zig
const std = @import("std"); const cop0 = @import("cop0.zig"); const MIReg = enum(u64) { MIVersion = 0x4, MIInterrupt = 0x8, MIMask = 0xC, }; pub const InterruptSource = enum(u6) { SP = 1 << 0, SI = 1 << 1, AI = 1 << 2, VI = 1 << 3, PI = 1 << 4, DP = 1 << 5, }; var miVersion: u32 = 0x0202_0102; var miInterrupt: u6 = 0; var miMask : u6 = 0; pub fn read32(pAddr: u64) u32 { var data: u32 = undefined; switch (pAddr & 0xFF) { @enumToInt(MIReg.MIVersion) => { std.log.info("[MI] Read32 @ pAddr {X}h (MI Version).", .{pAddr}); data = miVersion; }, @enumToInt(MIReg.MIInterrupt) => { std.log.info("[MI] Read32 @ pAddr {X}h (MI Interrupt).", .{pAddr}); data = @intCast(u32, miInterrupt); }, @enumToInt(MIReg.MIMask) => { std.log.info("[MI] Read32 @ pAddr {X}h (MI Mask).", .{pAddr}); data = @intCast(u32, miMask); }, else => { std.log.warn("[MI] Unhandled read32 @ pAddr {X}h.", .{pAddr}); } } return data; } pub fn write32(pAddr: u64, data: u32) void { switch (pAddr & 0xFF) { @enumToInt(MIReg.MIMask) => { std.log.info("[MI] Write32 @ pAddr {X}h (MI Mask), data: {X}h.", .{pAddr, data}); if ((data & (1 << 0)) != 0) miMask &= ~@enumToInt(InterruptSource.SP); if ((data & (1 << 1)) != 0) miMask |= @enumToInt(InterruptSource.SP); if ((data & (1 << 2)) != 0) miMask &= ~@enumToInt(InterruptSource.SI); if ((data & (1 << 3)) != 0) miMask |= @enumToInt(InterruptSource.SI); if ((data & (1 << 4)) != 0) miMask &= ~@enumToInt(InterruptSource.AI); if ((data & (1 << 5)) != 0) miMask |= @enumToInt(InterruptSource.AI); if ((data & (1 << 6)) != 0) miMask &= ~@enumToInt(InterruptSource.VI); if ((data & (1 << 7)) != 0) miMask |= @enumToInt(InterruptSource.VI); if ((data & (1 << 8)) != 0) miMask &= ~@enumToInt(InterruptSource.PI); if ((data & (1 << 9)) != 0) miMask |= @enumToInt(InterruptSource.PI); if ((data & (1 << 10)) != 0) miMask &= ~@enumToInt(InterruptSource.DP); if ((data & (1 << 11)) != 0) miMask |= @enumToInt(InterruptSource.DP); checkForInterrupts(); }, else => { std.log.warn("[MI] Unhandled write32 @ pAddr {X}h, data: {X}h.", .{pAddr, data}); if (pAddr == 0x4300000 and (data & 0x800) > 0) clearPending(InterruptSource.DP); } } } fn checkForInterrupts() void { if ((miInterrupt & miMask) != 0) { // std.log.info("[MI] INTR: {X}h, MASK: {X}h", .{miInterrupt, miMask}); cop0.setPending(2); } else { cop0.clearPending(2); } } pub fn setPending(irq: InterruptSource) void { std.log.info("[MI] IRQ Source: {s}", .{@tagName(irq)}); miInterrupt |= @enumToInt(irq); checkForInterrupts(); } pub fn clearPending(irq: InterruptSource) void { miInterrupt &= ~@enumToInt(irq); checkForInterrupts(); }
src/core/mi.zig
const std = @import("std"); const fifo = std.fifo; const Client = @import("../client.zig").Client; const txrx = @import("txrx.zig"); const AutoHashMap = std.hash_map.AutoHashMap; const LinearFifo = std.fifo.LinearFifo; const LinearFifoBufferType = std.fifo.LinearFifoBufferType; const FdBuffer = LinearFifo(i32, LinearFifoBufferType{ .Static = MAX_FDS }); const MAX_FDS = @import("txrx.zig").MAX_FDS; const BUFFER_SIZE = 4096; pub fn Context(comptime T: type) type { return struct { client: T, fd: i32 = -1, read_offset: usize = 0, write_offset: usize = 0, rx_fds: FdBuffer, rx_buf: [BUFFER_SIZE]u8, objects: AutoHashMap(u32, Object), tx_fds: FdBuffer, tx_buf: [BUFFER_SIZE]u8, tx_write_offset: usize = 0, const Self = @This(); pub const Object = struct { dispatch: fn (Object, u16) anyerror!void, context: *Self, container: usize, id: u32, version: u32, }; pub fn init(self: *Self, fd: i32, client: T) void { self.fd = fd; self.client = client; self.read_offset = 0; self.write_offset = 0; self.rx_fds = FdBuffer.init(); self.tx_fds = FdBuffer.init(); self.objects = AutoHashMap(u32, Object).init(std.heap.page_allocator); } pub fn deinit(self: *Self) void { self.objects.deinit(); } pub fn dispatch(self: *Self) anyerror!void { var n = try txrx.recvMsg(self.fd, self.rx_buf[self.write_offset..self.rx_buf.len], &self.rx_fds); n = self.write_offset + n; self.read_offset = 0; defer { self.write_offset = n - self.read_offset; std.mem.copy(u8, self.rx_buf[0..self.write_offset], self.rx_buf[self.read_offset..n]); } while (self.read_offset < n) { const remaining = n - self.read_offset; // We need to have read at least a header if (remaining < @sizeOf(Header)) return; const message_start_offset = self.read_offset; const header = @ptrCast(*Header, &self.rx_buf[message_start_offset]); // We need to have read a full message if (remaining < header.length) return; self.read_offset += @sizeOf(Header); const object = self.objects.get(header.id) orelse return error.CouldntFindExpectedId; try object.dispatch(object, header.opcode); if ((self.read_offset - message_start_offset) != header.length) { self.read_offset = 0; return error.MessageWrongLength; } } } pub fn next_u32(self: *Self) !u32 { var next_offset = self.read_offset + @sizeOf(u32); if (next_offset > self.rx_buf.len) { return error.NextReadsPastEndOfBuffer; } defer { self.read_offset = next_offset; } return @ptrCast(*u32, @alignCast(@alignOf(u32), &self.rx_buf[self.read_offset])).*; } pub fn next_i32(self: *Self) !i32 { var next_offset = self.read_offset + @sizeOf(i32); if (next_offset > self.rx_buf.len) { return error.NextReadsPastEndOfBuffer; } defer { self.read_offset = next_offset; } return @ptrCast(*i32, @alignCast(@alignOf(i32), &self.rx_buf[self.read_offset])).*; } // we just expose a pointer to the rx_buf for the // extent of the dispatch call. This will become invalid // after the dispatch function returns and so we cannot // hang on to this pointer. If we want to retain the string // we should copy it. pub fn next_string(self: *Self) ![]u8 { var length = try self.next_u32(); var next_offset = self.read_offset + @sizeOf(u32) * @divTrunc(length - 1, @sizeOf(u32)) + @sizeOf(u32); if (next_offset > self.rx_buf.len) { return error.NextReadsPastEndOfBuffer; } var s: []u8 = undefined; s.ptr = @ptrCast([*]u8, &self.rx_buf[self.read_offset]); s.len = length; self.read_offset = next_offset; return s; } // we just expose a pointer to the rx_buf for the // extent of the dispatch call. This will become invalid // after the dispatch function returns and so we cannot // hang on to this pointer. If we want to retain the array // we should copy it. pub fn next_array(self: *Self) ![]u32 { var length = try self.next_u32(); var next_offset = self.read_offset + length; if (next_offset > self.rx_buf.len) { return error.NextReadsPastEndOfBuffer; } var s: []u32 = undefined; s.ptr = @ptrCast(*u32, @alignCast(@alignOf(u32), &self.rx_buf[self.read_offset])); s.len = length / @sizeOf(u32); self.read_offset = next_offset; return s; } pub fn next_fd(self: *Self) !i32 { return self.rx_fds.readItem() orelse return error.FdReadFailed; } pub fn get(self: *Self, id: u32) ?Object { return self.objects.get(id); } pub fn register(self: *Self, object: Object) !void { _ = try self.objects.put(object.id, object); return; } pub fn unregister(self: *Self, object: Object) !void { if (self.objects.remove(object.id)) { // std.debug.warn("unregistered: {}\n", .{x.key}); } else { std.debug.warn("attempted to deregister object ({}) that didn't exist\n", .{object.id}); } return; } pub fn startWrite(self: *Self) void { self.tx_write_offset = 0; self.tx_write_offset += @sizeOf(Header); } pub fn finishWrite(self: *Self, id: u32, opcode: u16) void { var h = Header{ .id = id, .opcode = opcode, .length = @intCast(u16, self.tx_write_offset), }; var h_ptr = @ptrCast(*Header, &self.tx_buf[0]); h_ptr.* = h; var x = txrx.sendMsg(self.fd, self.tx_buf[0..self.tx_write_offset], &self.tx_fds); } pub fn putU32(self: *Self, value: u32) void { var u32_ptr = @ptrCast(*u32, @alignCast(@alignOf(u32), &self.tx_buf[self.tx_write_offset])); u32_ptr.* = value; self.tx_write_offset += @sizeOf(u32); } pub fn putI32(self: *Self, value: i32) void { var i32_ptr = @ptrCast(*i32, @alignCast(@alignOf(i32), &self.tx_buf[self.tx_write_offset])); i32_ptr.* = value; self.tx_write_offset += @sizeOf(i32); } pub fn putFd(self: *Self, value: i32) void { // TODO: I guess we need to error self.tx_fds.writeItem(value) catch return; } pub fn putFixed(self: *Self, value: f64) void { var fixed = doubleToFixed(value); var i32_ptr = @ptrCast(*i32, @alignCast(@alignOf(i32), &self.tx_buf[self.tx_write_offset])); i32_ptr.* = fixed; self.tx_write_offset += @sizeOf(i32); } pub fn putArray(self: *Self, array: []u32) void { // Write our array length (in bytes) into buffer var len_ptr = @ptrCast(*u32, @alignCast(@alignOf(u32), &self.tx_buf[self.tx_write_offset])); len_ptr.* = @intCast(u32, @sizeOf(u32) * array.len); self.tx_write_offset += @sizeOf(u32); // Copy data from array into tx_buf var tx_buf: []u32 = undefined; tx_buf.ptr = @ptrCast([*]u32, @alignCast(@alignOf(u32), &self.tx_buf[self.tx_write_offset])); tx_buf.len = (self.tx_buf.len - self.tx_write_offset) / @sizeOf(u32); std.mem.copy(u32, tx_buf, array[0..array.len]); self.tx_write_offset += @sizeOf(u32) * array.len; } // string is assumed to have a null byte within its contents / length pub fn putString(self: *Self, string: []const u8) void { // Write our array length (in bytes) into buffer var length = @sizeOf(u32) * @divTrunc(string.len - 1, @sizeOf(u32)) + @sizeOf(u32); var len_ptr = @ptrCast(*u32, @alignCast(@alignOf(u32), &self.tx_buf[self.tx_write_offset])); len_ptr.* = @intCast(u32, length); self.tx_write_offset += @sizeOf(u32); std.mem.copy(u8, self.tx_buf[self.tx_write_offset .. self.tx_write_offset + string.len], string); std.mem.set(u8, self.tx_buf[self.tx_write_offset + string.len .. self.tx_write_offset + length], 0); self.tx_write_offset += length; } }; } pub const Header = packed struct { id: u32, opcode: u16, length: u16, }; pub fn doubleToFixed(f: f64) i32 { var x: f64 = f + (3 << (51 - 8)); var x_ptr = @ptrCast(*i32, &x); return x_ptr.*; } pub fn fixedToDouble(f: i32) f64 { var x: i32 = ((1023 + 44) << 52) + (1 << 51) + f; var x_ptr = @ptrCast(*f64, &x); return x_ptr.*; }
src/wl/context.zig
pub const env = @import("./env.zig"); pub const err = @import("./error.zig"); pub const http = @import("./http.zig"); pub const log = @import("./log.zig"); pub const random = @import("./random.zig"); pub const resource = @import("./resource.zig"); pub const time = @import("./time.zig"); pub const runtime = @import("./runtime.zig"); pub const startup = @import("./startup.zig"); // cwagi pub const cwagi = @import("./cwagi.zig"); pub const ReadError = err.OlinError; // not directly used, but imported like this to force the compiler to actually consider it. pub const panic = @import("./panic.zig").panic; fn hack(inp: i32) usize { if (err.parse(inp)) |resp| { return @intCast(usize, resp); } else |errVal| { errno = @intCast(u12, inp*-1); return 0; } } pub export fn _start() noreturn { runtime.exit(@intCast(i32, @import("std").start.callMain())); } pub const io = struct { pub fn getStdInHandle() bits.fd_t { if (bits.STDIN_FILENO == -1) { bits.STDIN_FILENO = resource.io_get_stdin(); } return bits.STDIN_FILENO; } pub fn getStdErrHandle() bits.fd_t { if (bits.STDERR_FILENO == -1) { bits.STDERR_FILENO = resource.io_get_stderr(); } return bits.STDERR_FILENO; } pub fn getStdOutHandle() bits.fd_t { if (bits.STDOUT_FILENO == -1) { bits.STDOUT_FILENO = resource.io_get_stdout(); } return bits.STDOUT_FILENO; } }; pub const system = struct { const std = @import("std"); const mem = std.mem; pub fn raise(sig: bits.signal_t) noreturn { runtime.exit(sig); } pub fn write(fd: i32, buf: [*]const u8, count: usize) usize { return hack(resource.resource_write(fd, buf, count)); } pub fn read(fd: i32, buf: [*]u8, count: usize) usize { return hack(resource.resource_read(fd, buf, count)); } pub fn close(fd: i32) usize { resource.resource_close(fd); } pub fn openat(fd: bits.fd_t, path: [*:0]const u8, flags: u32, mode: usize) usize { return open(path, flags, mode); } pub fn open(path: [*:0]const u8, flags: u32, mode: usize) usize { const inner_path = mem.toSlice(path); return hack(resource.resource_open(inner_path.ptr, inner_path.len)); } pub fn lseek(fd: i32, offset: i64, whence: u2) i64 { return std.os.EINVAL; } pub fn getErrno(arg: i64) u12 { return errno; } pub fn exit(status: u8) noreturn { runtime.exit(@intCast(i32, status)); } pub fn abort() noreturn { exit(1); } }; var errno: u12 = 0; pub const bits = @import("bits.zig");
zig/src/olin/olin.zig
const windows = @import("windows.zig"); const IUnknown = windows.IUnknown; const UINT = windows.UINT; const WINAPI = windows.WINAPI; const GUID = windows.GUID; const HRESULT = windows.HRESULT; const HINSTANCE = windows.HINSTANCE; const SIZE_T = windows.SIZE_T; const LPCSTR = windows.LPCSTR; const FLOAT = windows.FLOAT; const BOOL = windows.BOOL; const TRUE = windows.TRUE; const FALSE = windows.FALSE; const INT = windows.INT; const UINT8 = windows.UINT8; const d3dcommon = @import("d3dcommon.zig"); const FEATURE_LEVEL = d3dcommon.FEATURE_LEVEL; const DRIVER_TYPE = d3dcommon.DRIVER_TYPE; const dxgi = @import("dxgi.zig"); pub const CREATE_DEVICE_FLAG = UINT; pub const CREATE_DEVICE_SINGLETHREADED = 0x1; pub const CREATE_DEVICE_DEBUG = 0x2; pub const CREATE_DEVICE_SWITCH_TO_REF = 0x4; pub const CREATE_DEVICE_PREVENT_INTERNAL_THREADING_OPTIMIZATIONS = 0x8; pub const CREATE_DEVICE_BGRA_SUPPORT = 0x20; pub const CREATE_DEVICE_DEBUGGABLE = 0x40; pub const CREATE_DEVICE_PREVENT_ALTERING_LAYER_SETTINGS_FROM_REGISTRY = 0x80; pub const CREATE_DEVICE_DISABLE_GPU_TIMEOUT = 0x100; pub const CREATE_DEVICE_VIDEO_SUPPORT = 0x800; pub const SDK_VERSION: UINT = 7; pub const BIND_FLAG = UINT; pub const BIND_VERTEX_BUFFER = 0x1; pub const BIND_INDEX_BUFFER = 0x2; pub const BIND_CONSTANT_BUFFER = 0x4; pub const BIND_SHADER_RESOURCE = 0x8; pub const BIND_STREAM_OUTPUT = 0x10; pub const BIND_RENDER_TARGET = 0x20; pub const BIND_DEPTH_STENCIL = 0x40; pub const BIND_UNORDERED_ACCESS = 0x80; pub const BIND_DECODER = 0x200; pub const BIND_VIDEO_ENCODER = 0x400; pub const RESOURCE_DIMENSION = enum(UINT) { UNKNOWN = 0, BUFFER = 1, TEXTURE1D = 2, TEXTURE2D = 3, TEXTURE3D = 4, }; pub const RTV_DIMENSION = enum(UINT) { UNKNOWN = 0, BUFFER = 1, TEXTURE1D = 2, TEXTURE1DARRAY = 3, TEXTURE2D = 4, TEXTURE2DARRAY = 5, TEXTURE2DMS = 6, TEXTURE2DMSARRAY = 7, TEXTURE3D = 8, }; pub const BUFFER_RTV = extern struct { u0: extern union { FirstElement: UINT, ElementOffset: UINT, }, u1: extern union { NumElements: UINT, ElementWidth: UINT, }, }; pub const TEX1D_RTV = extern struct { MipSlice: UINT, }; pub const TEX1D_ARRAY_RTV = extern struct { MipSlice: UINT, FirstArraySlice: UINT, ArraySize: UINT, }; pub const TEX2D_RTV = extern struct { MipSlice: UINT, }; pub const TEX2D_ARRAY_RTV = extern struct { MipSlice: UINT, FirstArraySlice: UINT, ArraySize: UINT, }; pub const TEX2DMS_RTV = extern struct { UnusedField_NothingToDefine: UINT = undefined, }; pub const TEX2DMS_ARRAY_RTV = extern struct { FirstArraySlice: UINT, ArraySlice: UINT, }; pub const TEX3D_RTV = extern struct { MipSlice: UINT, FirstWSlice: UINT, WSize: UINT, }; pub const RENDER_TARGET_VIEW_DESC = extern struct { Format: dxgi.FORMAT, ViewDimension: RTV_DIMENSION, u: extern union { Buffer: BUFFER_RTV, Texture1D: TEX1D_RTV, Texture1DArray: TEX1D_ARRAY_RTV, Texture2D: TEX2D_RTV, Texture2DArray: TEX2D_ARRAY_RTV, Texture2DMS: TEX2DMS_RTV, Texture2DMSArray: TEX2DMS_ARRAY_RTV, Texture3D: TEX3D_RTV, }, }; pub const INPUT_CLASSIFICATION = enum(UINT) { INPUT_PER_VERTEX_DATA = 0, INPUT_PER_INSTNACE_DATA = 1, }; pub const INPUT_ELEMENT_DESC = extern struct { SemanticName: LPCSTR, SemanticIndex: UINT, Format: dxgi.FORMAT, InputSlot: UINT, AlignedByteOffset: UINT, InputSlotClass: INPUT_CLASSIFICATION, InstanceDataStepRate: UINT, }; pub const SUBRESOURCE_DATA = extern struct { pSysMem: ?*const anyopaque, SysMemPitch: UINT = 0, SysMemSlicePitch: UINT = 0, }; pub const USAGE = UINT; pub const USAGE_DEFAULT = 0; pub const USAGE_IMMUTABLE = 1; pub const USAGE_DYNAMIC = 2; pub const USAGE_STAGING = 3; pub const CPU_ACCCESS_FLAG = UINT; pub const CPU_ACCESS_WRITE = 0x10000; pub const CPU_ACCESS_READ = 0x20000; pub const BUFFER_DESC = extern struct { ByteWidth: UINT, Usage: USAGE, BindFlags: BIND_FLAG, CPUAccessFlags: CPU_ACCCESS_FLAG = 0, MiscFlags: UINT = 0, StructureByteStride: UINT = 0, }; pub const VIEWPORT = extern struct { TopLeftX: FLOAT, TopLeftY: FLOAT, Width: FLOAT, Height: FLOAT, MinDepth: FLOAT, MaxDepth: FLOAT, }; pub const CPU_DESCRIPTOR_HANDLE = extern struct { ptr: SIZE_T, }; pub const MAP = enum(UINT) { READ = 1, WRITE = 2, READ_WRITE = 3, WRITE_DISCARD = 4, WRITE_NO_OVERWRITE = 5, }; pub const MAP_FLAG = UINT; pub const MAP_FLAG_DO_NOT_WAIT = 0x100000; pub const MAPPED_SUBRESOURCE = extern struct { pData: *anyopaque, RowPitch: UINT, DepthPitch: UINT, }; pub const PRIMITIVE_TOPOLOGY = d3dcommon.PRIMITIVE_TOPOLOGY; pub const FILL_MODE = enum(UINT) { WIREFRAME = 2, SOLID = 3, }; pub const CULL_MODE = enum(UINT) { NONE = 1, FRONT = 2, BACK = 3, }; pub const RASTERIZER_DESC = extern struct { FillMode: FILL_MODE = FILL_MODE.SOLID, CullMode: CULL_MODE = CULL_MODE.BACK, FrontCounterClockwise: BOOL = FALSE, DepthBias: INT = 0, DepthBiasClamp: FLOAT = 0, SlopeScaledDepthBias: FLOAT = 0, DepthClipEnable: BOOL = TRUE, ScissorEnable: BOOL = FALSE, MultisampleEndable: BOOL = FALSE, AntialiasedLineEnable: BOOL = FALSE, }; pub const BLEND = enum(UINT) { ZERO = 1, ONE = 2, SRC_COLOR = 3, INV_SRC_COLOR = 4, SRC_ALPHA = 5, INV_SRC_ALPHA = 6, DEST_ALPHA = 7, INV_DEST_ALPHA = 8, DEST_COLOR = 9, INV_DEST_COLOR = 10, SRC_ALPHA_SAT = 11, BLEND_FACTOR = 14, INV_BLEND_FACTOR = 15, SRC1_COLOR = 16, INV_SRC1_COLOR = 17, SRC1_ALPHA = 18, INV_SRC1_ALPHA = 19, }; pub const BLEND_OP = enum(UINT) { ADD = 1, SUBTRACT = 2, REV_SUBTRACT = 3, MIN = 4, MAX = 5, }; pub const COLOR_WRITE_ENABLE = UINT; pub const COLOR_WRITE_ENABLE_RED = 1; pub const COLOR_WRITE_ENABLE_GREEN = 2; pub const COLOR_WRITE_ENABLE_BLUE = 4; pub const COLOR_WRITE_ENABLE_ALPHA = 8; pub const COLOR_WRITE_ENABLE_ALL = COLOR_WRITE_ENABLE_RED | COLOR_WRITE_ENABLE_GREEN | COLOR_WRITE_ENABLE_BLUE | COLOR_WRITE_ENABLE_ALPHA; pub const RENDER_TARGET_BLEND_DESC = extern struct { BlendEnable: BOOL, SrcBlend: BLEND, DestBlend: BLEND, BlendOp: BLEND_OP, SrcBlendAlpha: BLEND, DestBlendAlpha: BLEND, BlendOpAlpha: BLEND_OP, RenderTargetWriteMask: UINT8, }; pub const BLEND_DESC = extern struct { AlphaToCoverageEnable: BOOL, IndependentBlendEnable: BOOL, RenderTarget: [8]RENDER_TARGET_BLEND_DESC, }; pub const TEXTURE2D_DESC = struct { Width: UINT, Height: UINT, MipLevels: UINT, ArraySize: UINT, Format: dxgi.FORMAT, SampleDesc: dxgi.SAMPLE_DESC, Usage: USAGE, BindFlags: BIND_FLAG, CPUAccessFlags: CPU_ACCCESS_FLAG, MiscFlags: UINT, }; pub const BUFFER_SRV = extern struct { FirstElement: UINT, NumElements: UINT, }; pub const TEX1D_SRV = extern struct { MostDetailedMip: UINT, MipLevels: UINT, }; pub const TEX1D_ARRAY_SRV = extern struct { MostDetailedMip: UINT, MipLevels: UINT, FirstArraySlice: UINT, ArraySize: UINT, }; pub const TEX2D_SRV = extern struct { MostDetailedMip: UINT, MipLevels: UINT, }; pub const TEX2D_ARRAY_SRV = extern struct { MostDetailedMip: UINT, MipLevels: UINT, FirstArraySlice: UINT, ArraySize: UINT, }; pub const TEX3D_SRV = extern struct { MostDetailedMip: UINT, MipLevels: UINT, }; pub const TEXCUBE_SRV = extern struct { MostDetailedMip: UINT, MipLevels: UINT, }; pub const TEXCUBE_ARRAY_SRV = extern struct { MostDetailedMip: UINT, MipLevels: UINT, First2DArrayFace: UINT, NumCubes: UINT, }; pub const TEX2DMS_SRV = extern struct { UnusedField_NothingToDefine: UINT, }; pub const TEX2DMS_ARRAY_SRV = extern struct { FirstArraySlice: UINT, ArraySize: UINT, }; pub const BUFFEREX_SRV_FLAG = UINT; pub const BUFFEREX_SRV_FLAG_RAW = 0x1; pub const BUFFEREX_SRV = extern struct { FirstElement: UINT, NumElements: UINT, Flags: BUFFEREX_SRV_FLAG, }; pub const SRV_DIMENSION = enum(UINT) { UNKNOWN = 0, BUFFER = 1, TEXTURE1D = 2, TEXTURE1DARRAY = 3, TEXTURE2D = 4, TEXTURE2DARRAY = 5, TEXTURE2DMS = 6, TEXTURE2DMSARRAY = 7, TEXTURE3D = 8, TEXTURECUBE = 9, TEXTURECUBEARRAY = 10, BUFFEREX = 11, }; pub const SHADER_RESOURCE_VIEW_DESC = extern struct { Format: dxgi.FORMAT, ViewDimension: SRV_DIMENSION, u: extern union { Buffer: BUFFER_SRV, Texture1D: TEX1D_SRV, Texture1DArray: TEX1D_ARRAY_SRV, Texture2D: TEX2D_SRV, Texture2DArray: TEX2D_ARRAY_SRV, Texture2DMS: TEX2DMS_SRV, Texture2DMSArray: TEX2DMS_ARRAY_SRV, Texture3D: TEX3D_SRV, TextureCube: TEXCUBE_SRV, TextureCubeArray: TEXCUBE_ARRAY_SRV, BufferEx: BUFFEREX_SRV, }, }; pub const FILTER = enum(UINT) { MIN_MAG_MIP_POINT = 0, MIN_MAG_POINT_MIP_LINEAR = 0x1, MIN_POINT_MAG_LINEAR_MIP_POINT = 0x4, MIN_POINT_MAG_MIP_LINEAR = 0x5, MIN_LINEAR_MAG_MIP_POINT = 0x10, MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x11, MIN_MAG_LINEAR_MIP_POINT = 0x14, MIN_MAG_MIP_LINEAR = 0x15, ANISOTROPIC = 0x55, COMPARISON_MIN_MAG_MIP_POINT = 0x80, COMPARISON_MIN_MAG_POINT_MIP_LINEAR = 0x81, COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x84, COMPARISON_MIN_POINT_MAG_MIP_LINEAR = 0x85, COMPARISON_MIN_LINEAR_MAG_MIP_POINT = 0x90, COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x91, COMPARISON_MIN_MAG_LINEAR_MIP_POINT = 0x94, COMPARISON_MIN_MAG_MIP_LINEAR = 0x95, COMPARISON_ANISOTROPIC = 0xd5, MINIMUM_MIN_MAG_MIP_POINT = 0x100, MINIMUM_MIN_MAG_POINT_MIP_LINEAR = 0x101, MINIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x104, MINIMUM_MIN_POINT_MAG_MIP_LINEAR = 0x105, MINIMUM_MIN_LINEAR_MAG_MIP_POINT = 0x110, MINIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x111, MINIMUM_MIN_MAG_LINEAR_MIP_POINT = 0x114, MINIMUM_MIN_MAG_MIP_LINEAR = 0x115, MINIMUM_ANISOTROPIC = 0x155, MAXIMUM_MIN_MAG_MIP_POINT = 0x180, MAXIMUM_MIN_MAG_POINT_MIP_LINEAR = 0x181, MAXIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x184, MAXIMUM_MIN_POINT_MAG_MIP_LINEAR = 0x185, MAXIMUM_MIN_LINEAR_MAG_MIP_POINT = 0x190, MAXIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x191, MAXIMUM_MIN_MAG_LINEAR_MIP_POINT = 0x194, MAXIMUM_MIN_MAG_MIP_LINEAR = 0x195, MAXIMUM_ANISOTROPIC = 0x1d5, }; pub const TEXTURE_ADDRESS_MODE = enum(UINT) { WRAP = 1, MIRROR = 2, CLAMP = 3, BORDER = 4, MIRROR_ONCE = 5, }; pub const COMPARISON_FUNC = enum(UINT) { NEVER = 1, LESS = 2, EQUAL = 3, LESS_EQUAL = 4, GREATER = 5, NOT_EQUAL = 6, GREATER_EQUAL = 7, ALWAYS = 8, }; pub const SAMPLER_DESC = extern struct { Filter: FILTER, AddressU: TEXTURE_ADDRESS_MODE, AddressV: TEXTURE_ADDRESS_MODE, AddressW: TEXTURE_ADDRESS_MODE, MipLODBias: FLOAT, MaxAnisotropy: UINT, ComparisonFunc: COMPARISON_FUNC, BorderColor: [4]FLOAT, MinLOD: FLOAT, MaxLOD: FLOAT, }; pub const IID_IDeviceChild = GUID.parse("{1841e5c8-16b0-489b-bcc8-44cfb0d5deae}"); pub const IDeviceChild = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), devchild: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace Methods(Self); pub fn Methods(comptime T: type) type { _ = T; return extern struct {}; } pub fn VTable(comptime T: type) type { _ = T; return extern struct { GetDevice: *anyopaque, GetPrivateData: *anyopaque, SetPrivateData: *anyopaque, SetPrivateDataInterface: *anyopaque, }; } }; pub const IID_IClassLinkage = GUID.parse("{ddf57cba-9543-46e4-a12b-f207a0fe7fed}"); pub const IClassLinkage = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), devchild: IDeviceChild.VTable(Self), classlinkage: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace IDeviceChild.Methods(Self); usingnamespace Methods(Self); pub fn Methods(comptime T: type) type { _ = T; return extern struct {}; } pub fn VTable(comptime T: type) type { _ = T; return extern struct { GetClassInstance: *anyopaque, CreateClassInstance: *anyopaque, }; } }; pub const IID_IClassInstance = GUID.parse("{a6cd7faa-b0b7-4a2f-9436-8662a65797cb}"); pub const IClassInstance = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), devchild: IDeviceChild.VTable(Self), classinst: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace IDeviceChild.Methods(Self); usingnamespace Methods(Self); pub fn Methods(comptime T: type) type { _ = T; return extern struct {}; } pub fn VTable(comptime T: type) type { _ = T; return extern struct { GetClassLinkage: *anyopaque, GetDesc: *anyopaque, GetInstanceName: *anyopaque, GetTypeName: *anyopaque, }; } }; pub const IID_IResource = GUID.parse("{dc8e63f3-d12b-4952-b47b-5e45026a862d}"); pub const IResource = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), devchild: IDeviceChild.VTable(Self), resource: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace IDeviceChild.Methods(Self); usingnamespace Methods(Self); pub fn Methods(comptime T: type) type { _ = T; return extern struct {}; } pub fn VTable(comptime T: type) type { _ = T; return extern struct { GetType: *anyopaque, SetEvictionPriority: *anyopaque, GetEvictionPriority: *anyopaque, }; } }; pub const IID_IDeviceContext = GUID.parse("{c0bfa96c-e089-44fb-8eaf-26f8796190da}"); pub const IDeviceContext = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), devchild: IDeviceChild.VTable(Self), devctx: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace IDeviceChild.Methods(Self); usingnamespace Methods(Self); pub fn Methods(comptime T: type) type { return extern struct { pub inline fn VSSetConstantBuffers( self: *T, StartSlot: UINT, NumBuffers: UINT, ppConstantBuffers: ?[*]const *IBuffer, ) void { self.v.devctx.VSSetConstantBuffers( self, StartSlot, NumBuffers, ppConstantBuffers, ); } pub inline fn PSSetShaderResources( self: *T, StartSlot: UINT, NumViews: UINT, ppShaderResourceViews: ?[*]const *IShaderResourceView, ) void { self.v.devctx.PSSetShaderResources( self, StartSlot, NumViews, ppShaderResourceViews, ); } pub inline fn PSSetShader( self: *T, pPixelShader: ?*IPixelShader, ppClassInstance: ?[*]const *IClassInstance, NumClassInstances: UINT, ) void { self.v.devctx.PSSetShader( self, pPixelShader, ppClassInstance, NumClassInstances, ); } pub inline fn PSSetSamplers( self: *T, StartSlot: UINT, NumSamplers: UINT, ppSamplers: ?[*]const *ISamplerState, ) void { self.v.devctx.PSSetSamplers( self, StartSlot, NumSamplers, ppSamplers, ); } pub inline fn VSSetShader( self: *T, pVertexShader: ?*IVertexShader, ppClassInstance: ?[*]const *IClassInstance, NumClassInstances: UINT, ) void { self.v.devctx.VSSetShader( self, pVertexShader, ppClassInstance, NumClassInstances, ); } pub inline fn Draw( self: *T, VertexCount: UINT, StartVertexLocation: UINT, ) void { self.v.devctx.Draw(self, VertexCount, StartVertexLocation); } pub inline fn Map( self: *T, pResource: *IResource, Subresource: UINT, MapType: MAP, MapFlags: MAP_FLAG, pMappedResource: ?*MAPPED_SUBRESOURCE, ) HRESULT { return self.v.devctx.Map( self, pResource, Subresource, MapType, MapFlags, pMappedResource, ); } pub inline fn Unmap(self: *T, pResource: *IResource, Subresource: UINT) void { self.v.devctx.Unmap(self, pResource, Subresource); } pub inline fn PSSetConstantBuffers( self: *T, StartSlot: UINT, NumBuffers: UINT, ppConstantBuffers: ?[*]const *IBuffer, ) void { self.v.devctx.PSSetConstantBuffers( self, StartSlot, NumBuffers, ppConstantBuffers, ); } pub inline fn IASetInputLayout(self: *T, pInputLayout: ?*IInputLayout) void { self.v.devctx.IASetInputLayout(self, pInputLayout); } pub inline fn IASetVertexBuffers( self: *T, StartSlot: UINT, NumBuffers: UINT, ppVertexBuffers: ?[*]const *IBuffer, pStrides: ?[*]const UINT, pOffsets: ?[*]const UINT, ) void { self.v.devctx.IASetVertexBuffers( self, StartSlot, NumBuffers, ppVertexBuffers, pStrides, pOffsets, ); } pub inline fn IASetPrimitiveTopology(self: *T, Topology: PRIMITIVE_TOPOLOGY) void { self.v.devctx.IASetPrimitiveTopology(self, Topology); } pub inline fn VSSetShaderResources( self: *T, StartSlot: UINT, NumViews: UINT, ppShaderResourceViews: ?[*]const *IShaderResourceView, ) void { self.v.devctx.VSSetShaderResources( self, StartSlot, NumViews, ppShaderResourceViews, ); } pub inline fn OMSetRenderTargets( self: *T, NumViews: UINT, ppRenderTargetViews: ?[*]const IRenderTargetView, pDepthStencilView: ?*IDepthStencilView, ) void { self.v.devctx.OMSetRenderTargets( self, NumViews, ppRenderTargetViews, pDepthStencilView, ); } pub inline fn OMSetBlendState( self: *T, pBlendState: ?*IBlendState, BlendFactor: ?*const [4]FLOAT, SampleMask: UINT, ) void { self.v.devctx.OMSetBlendState( self, pBlendState, BlendFactor, SampleMask, ); } pub inline fn RSSetState(self: *T, pRasterizerState: ?*IRasterizerState) void { self.v.devctx.RSSetState(self, pRasterizerState); } pub inline fn RSSetViewports( self: *T, NumViewports: UINT, pViewports: [*]const VIEWPORT, ) void { self.v.devctx.RSSetViewports(self, NumViewports, pViewports); } pub inline fn ClearRenderTargetView( self: *T, pRenderTargetView: *IRenderTargetView, ColorRGBA: *const [4]FLOAT, ) void { self.v.devctx.ClearRenderTargetView(self, pRenderTargetView, ColorRGBA); } pub inline fn Flush(self: *T) void { self.v.devctx.Flush(self); } }; } pub fn VTable(comptime T: type) type { return extern struct { VSSetConstantBuffers: fn ( *T, UINT, UINT, ?[*]const *IBuffer, ) callconv(WINAPI) void, PSSetShaderResources: fn ( *T, UINT, UINT, ?[*]const *IShaderResourceView, ) callconv(WINAPI) void, PSSetShader: fn ( *T, ?*IPixelShader, ?[*]const *IClassInstance, UINT, ) callconv(WINAPI) void, PSSetSamplers: fn ( *T, UINT, UINT, ?[*]const *ISamplerState, ) callconv(WINAPI) void, VSSetShader: fn ( *T, ?*IVertexShader, ?[*]const *IClassInstance, UINT, ) callconv(WINAPI) void, DrawIndexed: *anyopaque, Draw: fn (*T, UINT, UINT) callconv(WINAPI) void, Map: fn ( *T, *IResource, UINT, MAP, MAP_FLAG, ?*MAPPED_SUBRESOURCE, ) callconv(WINAPI) HRESULT, Unmap: fn (*T, *IResource, UINT) callconv(WINAPI) void, PSSetConstantBuffers: fn ( *T, UINT, UINT, ?[*]const *IBuffer, ) callconv(WINAPI) void, IASetInputLayout: fn (*T, ?*IInputLayout) callconv(WINAPI) void, IASetVertexBuffers: fn ( *T, UINT, UINT, ?[*]const *IBuffer, ?[*]const UINT, ?[*]const UINT, ) callconv(WINAPI) void, IASetIndexBuffer: *anyopaque, DrawIndexedInstanced: *anyopaque, DrawInstanced: *anyopaque, GSSetConstantBuffers: *anyopaque, GSSetShader: *anyopaque, IASetPrimitiveTopology: fn (*T, PRIMITIVE_TOPOLOGY) callconv(WINAPI) void, VSSetShaderResources: fn ( *T, UINT, UINT, ?[*]const *IShaderResourceView, ) callconv(WINAPI) void, VSSetSamplers: *anyopaque, Begin: *anyopaque, End: *anyopaque, GetData: *anyopaque, SetPredication: *anyopaque, GSSetShaderResources: *anyopaque, GSSetSamplers: *anyopaque, OMSetRenderTargets: fn ( *T, UINT, ?[*]const IRenderTargetView, ?*IDepthStencilView, ) callconv(WINAPI) void, OMSetRenderTargetsAndUnorderedAccessViews: *anyopaque, OMSetBlendState: fn ( *T, ?*IBlendState, ?*const [4]FLOAT, UINT, ) callconv(WINAPI) void, OMSetDepthStencilState: *anyopaque, SOSetTargets: *anyopaque, DrawAuto: *anyopaque, DrawIndexedInstancedIndirect: *anyopaque, DrawInstancedIndirect: *anyopaque, Dispatch: *anyopaque, DispatchIndirect: *anyopaque, RSSetState: fn (*T, ?*IRasterizerState) callconv(WINAPI) void, RSSetViewports: fn (*T, UINT, [*]const VIEWPORT) callconv(WINAPI) void, RSSetScissorRects: *anyopaque, CopySubresourceRegion: *anyopaque, CopyResource: *anyopaque, UpdateSubresource: *anyopaque, CopyStructureCount: *anyopaque, ClearRenderTargetView: fn (*T, *IRenderTargetView, *const [4]FLOAT) callconv(WINAPI) void, ClearUnorderedAccessViewUint: *anyopaque, ClearUnorderedAccessViewFloat: *anyopaque, ClearDepthStencilView: *anyopaque, GenerateMips: *anyopaque, SetResourceMinLOD: *anyopaque, GetResourceMinLOD: *anyopaque, ResolveSubresource: *anyopaque, ExecuteCommandList: *anyopaque, HSSetShaderResources: *anyopaque, HSSetShader: *anyopaque, HSSetSamplers: *anyopaque, HSSetConstantBuffers: *anyopaque, DSSetShaderResources: *anyopaque, DSSetShader: *anyopaque, DSSetSamplers: *anyopaque, DSSetConstantBuffers: *anyopaque, CSSetShaderResources: *anyopaque, CSSetUnorderedAccessViews: *anyopaque, CSSetShader: *anyopaque, CSSetSamplers: *anyopaque, CSSetConstantBuffers: *anyopaque, VSGetConstantBuffers: *anyopaque, PSGetShaderResources: *anyopaque, PSGetShader: *anyopaque, PSGetSamplers: *anyopaque, VSGetShader: *anyopaque, PSGetConstantBuffers: *anyopaque, IAGetInputLayout: *anyopaque, IAGetVertexBuffers: *anyopaque, IAGetIndexBuffer: *anyopaque, GSGetConstantBuffers: *anyopaque, GSGetShader: *anyopaque, IAGetPrimitiveTopology: *anyopaque, VSGetShaderResources: *anyopaque, VSGetSamplers: *anyopaque, GetPredication: *anyopaque, GSGetShaderResources: *anyopaque, GSGetSamplers: *anyopaque, OMGetRenderTargets: *anyopaque, OMGetRenderTargetsAndUnorderedAccessViews: *anyopaque, OMGetBlendState: *anyopaque, OMGetDepthStencilState: *anyopaque, SOGetTargets: *anyopaque, RSGetState: *anyopaque, RSGetViewports: *anyopaque, RSGetScissorRects: *anyopaque, HSGetShaderResources: *anyopaque, HSGetShader: *anyopaque, HSGetSamplers: *anyopaque, HSGetConstantBuffers: *anyopaque, DSGetShaderResources: *anyopaque, DSGetShader: *anyopaque, DSGetSamplers: *anyopaque, DSGetConstantBuffers: *anyopaque, CSGetShaderResources: *anyopaque, CSGetUnorderedAccessViews: *anyopaque, CSGetShader: *anyopaque, CSGetSamplers: *anyopaque, CSGetConstantBuffers: *anyopaque, ClearState: *anyopaque, Flush: fn (*T) callconv(WINAPI) void, GetType: *anyopaque, GetContextFlags: *anyopaque, FinishCommandList: *anyopaque, }; } }; pub const IID_IDevice = GUID.parse("{db6f6ddb-ac77-4e88-8253-819df9bbf140}"); pub const IDevice = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), device: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace Methods(Self); pub fn Methods(comptime T: type) type { return extern struct { pub inline fn CreateBuffer( self: *T, pDesc: *const BUFFER_DESC, pInitialData: ?*const SUBRESOURCE_DATA, ppBuffer: *?*IBuffer, ) HRESULT { return self.v.device.CreateBuffer( self, pDesc, pInitialData, ppBuffer, ); } pub inline fn CreateTexture2D( self: *T, pDesc: *const TEXTURE2D_DESC, pInitialData: ?*const SUBRESOURCE_DATA, ppTexture2D: ?*?*ITexture2D, ) HRESULT { return self.v.device.CreateTexture2D( self, pDesc, pInitialData, ppTexture2D, ); } pub inline fn CreateShaderResourceView( self: *T, pResource: *IResource, pDesc: ?*const SHADER_RESOURCE_VIEW_DESC, ppSRView: ?*?*IShaderResourceView, ) HRESULT { return self.v.device.CreateShaderResourceView( self, pResource, pDesc, ppSRView, ); } pub inline fn CreateRenderTargetView( self: *T, pResource: ?*IResource, pDesc: ?*const RENDER_TARGET_VIEW_DESC, ppRTView: ?*?*IRenderTargetView, ) HRESULT { return self.v.device.CreateRenderTargetView( self, pResource, pDesc, ppRTView, ); } pub inline fn CreateInputLayout( self: *T, pInputElementDescs: *const INPUT_ELEMENT_DESC, NumElements: UINT, pShaderBytecodeWithInputSignature: *anyopaque, BytecodeLength: SIZE_T, ppInputLayout: *?*IInputLayout, ) HRESULT { return self.v.device.CreateInputLayout( self, pInputElementDescs, NumElements, pShaderBytecodeWithInputSignature, BytecodeLength, ppInputLayout, ); } pub inline fn CreateVertexShader( self: *T, pShaderBytecode: *anyopaque, BytecodeLength: SIZE_T, pClassLinkage: ?*IClassLinkage, ppVertexShader: ?*?*IVertexShader, ) HRESULT { return self.v.device.CreateVertexShader( self, pShaderBytecode, BytecodeLength, pClassLinkage, ppVertexShader, ); } pub inline fn CreatePixelShader( self: *T, pShaderBytecode: *anyopaque, BytecodeLength: SIZE_T, pClassLinkage: ?*IClassLinkage, ppPixelShader: ?*?*IPixelShader, ) HRESULT { return self.v.device.CreatePixelShader( self, pShaderBytecode, BytecodeLength, pClassLinkage, ppPixelShader, ); } pub inline fn CreateBlendState( self: *T, pBlendStateDesc: *const BLEND_DESC, ppBlendState: ?*?*IBlendState, ) HRESULT { return self.v.device.CreateBlendState(self, pBlendStateDesc, ppBlendState); } pub inline fn CreateRasterizerState( self: *T, pRasterizerDesc: *const RASTERIZER_DESC, ppRasterizerState: ?*?*IRasterizerState, ) HRESULT { return self.v.device.CreateRasterizerState( self, pRasterizerDesc, ppRasterizerState, ); } pub inline fn CreateSamplerState( self: *T, pSamplerDesc: *const SAMPLER_DESC, ppSamplerState: ?*?*ISamplerState, ) HRESULT { return self.v.device.CreateSamplerState( self, pSamplerDesc, ppSamplerState, ); } }; } pub fn VTable(comptime T: type) type { return extern struct { CreateBuffer: fn ( *T, *const BUFFER_DESC, ?*const SUBRESOURCE_DATA, *?*IBuffer, ) callconv(WINAPI) HRESULT, CreateTexture1D: *anyopaque, CreateTexture2D: fn ( *T, *const TEXTURE2D_DESC, ?*const SUBRESOURCE_DATA, ?*?*ITexture2D, ) callconv(WINAPI) HRESULT, CreateTexture3D: *anyopaque, CreateShaderResourceView: fn ( *T, *IResource, ?*const SHADER_RESOURCE_VIEW_DESC, ?*?*IShaderResourceView, ) callconv(WINAPI) HRESULT, CreateUnorderedAccessView: *anyopaque, CreateRenderTargetView: fn ( *T, ?*IResource, ?*const RENDER_TARGET_VIEW_DESC, ?*?*IRenderTargetView, ) callconv(WINAPI) HRESULT, CreateDepthStencilView: *anyopaque, CreateInputLayout: fn ( *T, *const INPUT_ELEMENT_DESC, UINT, *anyopaque, SIZE_T, *?*IInputLayout, ) callconv(WINAPI) HRESULT, CreateVertexShader: fn ( *T, ?*anyopaque, SIZE_T, ?*IClassLinkage, ?*?*IVertexShader, ) callconv(WINAPI) HRESULT, CreateGeometryShader: *anyopaque, CreateGeometryShaderWithStreamOutput: *anyopaque, CreatePixelShader: fn ( *T, ?*anyopaque, SIZE_T, ?*IClassLinkage, ?*?*IPixelShader, ) callconv(WINAPI) HRESULT, CreateHullShader: *anyopaque, CreateDomainShader: *anyopaque, CreateComputeShader: *anyopaque, CreateClassLinkage: *anyopaque, CreateBlendState: fn ( *T, *const BLEND_DESC, ?*?*IBlendState, ) callconv(WINAPI) HRESULT, CreateDepthStencilState: *anyopaque, CreateRasterizerState: fn ( *T, *const RASTERIZER_DESC, ?*?*IRasterizerState, ) callconv(WINAPI) HRESULT, CreateSamplerState: fn ( *T, *const SAMPLER_DESC, ?*?*ISamplerState, ) callconv(WINAPI) HRESULT, CreateQuery: *anyopaque, CreatePredicate: *anyopaque, CreateCounter: *anyopaque, CreateDeferredContext: *anyopaque, OpenSharedResource: *anyopaque, CheckFormatSupport: *anyopaque, CheckMultisampleQualityLevels: *anyopaque, CheckCounterInfo: *anyopaque, CheckCounter: *anyopaque, CheckFeatureSupport: *anyopaque, GetPrivateData: *anyopaque, SetPrivateData: *anyopaque, SetPrivateDataInterface: *anyopaque, GetFeatureLevel: *anyopaque, GetCreationFlags: *anyopaque, GetDeviceRemovedReason: *anyopaque, GetImmediateContext: *anyopaque, SetExceptionMode: *anyopaque, GetExceptionMode: *anyopaque, }; } }; pub const IID_IView = GUID.parse("{839d1216-bb2e-412b-b7f4-a9dbebe08ed1}"); pub const IView = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), devchild: IDeviceChild.VTable(Self), view: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace IDeviceChild.Methods(Self); usingnamespace Methods(Self); pub fn Methods(comptime T: type) type { _ = T; return extern struct {}; } pub fn VTable(comptime T: type) type { _ = T; return extern struct { GetResource: *anyopaque, }; } }; pub const IID_IRenderTargetView = GUID.parse("{dfdba067-0b8d-4865-875b-d7b4516cc164}"); pub const IRenderTargetView = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), devchild: IDeviceChild.VTable(Self), view: IView.VTable(Self), rendertargetview: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace IDeviceChild.Methods(Self); usingnamespace IView.Methods(Self); usingnamespace Methods(Self); pub fn Methods(comptime T: type) type { _ = T; return extern struct {}; } pub fn VTable(comptime T: type) type { _ = T; return extern struct { GetDesc: *anyopaque, }; } }; pub const IID_IDepthStencilView = GUID.parse("{9fdac92a-1876-48c3-afad-25b94f84a9b6}"); pub const IDepthStencilView = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), devchild: IDeviceChild.VTable(Self), view: IView.VTable(Self), dsv: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace IDeviceChild.Methods(Self); usingnamespace IView.Methods(Self); usingnamespace Methods(Self); pub fn Methods(comptime T: type) type { _ = T; return extern struct {}; } pub fn VTable(comptime T: type) type { _ = T; return extern struct { GetDesc: *anyopaque, }; } }; pub const IID_IShaderResourceView = GUID.parse("{b0e06fe0-8192-4e1a-b1ca-36d7414710b}"); pub const IShaderResourceView = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), devchild: IDeviceChild.VTable(Self), view: IView.VTable(Self), shader_res_view: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace IDeviceChild.Methods(Self); usingnamespace IView.Methods(Self); usingnamespace Methods(Self); pub fn Methods(comptime T: type) type { _ = T; return extern struct {}; } pub fn VTable(comptime T: type) type { _ = T; return extern struct { GetDesc: *anyopaque, }; } }; pub const IID_IVertexShader = GUID("{3b301d64-d678-4289-8897-22f8928b72f3}"); pub const IVertexShader = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), devchild: IDeviceChild.VTable(Self), vertexshader: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace IDeviceChild.VTable(Self); usingnamespace Methods(Self); fn Methods(comptime T: type) type { _ = T; return extern struct {}; } fn VTable(comptime T: type) type { _ = T; return extern struct {}; } }; pub const IID_IPixelShader = GUID("{ea82e40d-51dc-4f33-93d4-db7c9125ae8c}"); pub const IPixelShader = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), devchild: IDeviceChild.VTable(Self), pixelshader: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace IDeviceChild.VTable(Self); usingnamespace Methods(Self); fn Methods(comptime T: type) type { _ = T; return extern struct {}; } fn VTable(comptime T: type) type { _ = T; return extern struct {}; } }; pub const IID_IInputLayout = GUID.parse("{e4819ddc-4cf0-4025-bd26-5de82a3e07b7}"); pub const IInputLayout = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), devchild: IDeviceChild.VTable(Self), inputlayout: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace IDeviceChild.VTable(Self); usingnamespace Methods(Self); fn Methods(comptime T: type) type { _ = T; return extern struct {}; } fn VTable(comptime T: type) type { _ = T; return extern struct {}; } }; pub const IID_IRasterizerState = GUID.parse("{9bb4ab81-ab1a-4d8f-b506-fc04200b6ee7}"); pub const IRasterizerState = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), devchild: IDeviceChild.VTable(Self), state: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace IDeviceChild.VTable(Self); usingnamespace Methods(Self); fn Methods(comptime T: type) type { _ = T; return extern struct {}; } fn VTable(comptime T: type) type { _ = T; return extern struct { GetDesc: *anyopaque, }; } }; pub const IID_BlendState = GUID.parse("{75b68faa-347d-4159-8f45-a0640f01cd9a}"); pub const IBlendState = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), devchild: IDeviceChild.VTable(Self), state: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace IDeviceChild.VTable(Self); usingnamespace Methods(Self); fn Methods(comptime T: type) type { _ = T; return extern struct {}; } fn VTable(comptime T: type) type { _ = T; return extern struct { GetDesc: *anyopaque, }; } }; pub const IID_SamplerState = GUID.parse("{da6fea51-564c-4487-9810-f0d0f9b4e3a5}"); pub const ISamplerState = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), devchild: IDeviceChild.VTable(Self), state: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace IDeviceChild.VTable(Self); usingnamespace Methods(Self); fn Methods(comptime T: type) type { _ = T; return extern struct {}; } fn VTable(comptime T: type) type { _ = T; return extern struct { GetDesc: *anyopaque, }; } }; pub const IID_IBuffer = GUID.parse("{48570b85-d1ee-4fcd-a250-eb350722b037}"); pub const IBuffer = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), devchild: IDeviceChild.VTable(Self), resource: IResource.VTable(Self), buffer: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace IDeviceChild.Methods(Self); usingnamespace IResource.Methods(Self); usingnamespace Methods(Self); pub fn Methods(comptime T: type) type { _ = T; return extern struct {}; } pub fn VTable(comptime T: type) type { _ = T; return extern struct { GetDesc: *anyopaque, }; } }; pub const IID_ITexture2D = GUID.parse("{6f15aaf2-d208-4e89-9ab4-489535d34f9c}"); pub const ITexture2D = extern struct { const Self = @This(); v: *const extern struct { unknown: IUnknown.VTable(Self), devchild: IDeviceChild.VTable(Self), resource: IResource.VTable(Self), texture: VTable(Self), }, usingnamespace IUnknown.Methods(Self); usingnamespace IDeviceChild.Methods(Self); usingnamespace IResource.Methods(Self); usingnamespace Methods(Self); pub fn Methods(comptime T: type) type { _ = T; return extern struct {}; } pub fn VTable(comptime T: type) type { _ = T; return extern struct { GetDesc: *anyopaque, }; } }; pub extern "d3d11" fn D3D11CreateDeviceAndSwapChain( pAdapter: ?*dxgi.IAdapter, DriverType: DRIVER_TYPE, Software: ?HINSTANCE, Flags: CREATE_DEVICE_FLAG, pFeatureLevels: ?[*]const FEATURE_LEVEL, FeatureLevels: UINT, SDKVersion: UINT, pSwapChainDesc: ?*const dxgi.SWAP_CHAIN_DESC, ppSwapChain: ?*?*dxgi.ISwapChain, ppDevice: ?*?*IDevice, pFeatureLevel: ?*FEATURE_LEVEL, ppImmediateContext: ?*?*IDeviceContext, ) callconv(WINAPI) HRESULT; // Return codes as defined here: https://docs.microsoft.com/en-us/windows/win32/direct3d11/d3d11-graphics-reference-returnvalues pub const ERROR_FILE_NOT_FOUND = @bitCast(HRESULT, @as(c_ulong, 0x887C0002)); pub const ERROR_TOO_MANY_UNIQUE_STATE_OBJECTS = @bitCast(HRESULT, @as(c_ulong, 0x887C0001)); pub const ERROR_TOO_MANY_UNIQUE_VIEW_OBJECTS = @bitCast(HRESULT, @as(c_ulong, 0x887C0003)); pub const ERROR_DEFERRED_CONTEXT_MAP_WITHOUT_INITIAL_DISCARD = @bitCast(HRESULT, @as(c_ulong, 0x887C0004)); // error set corresponding to the above return codes pub const Error = error{ FILE_NOT_FOUND, TOO_MANY_UNIQUE_STATE_OBJECTS, TOO_MANY_UNIQUE_VIEW_OBJECTS, DEFERRED_CONTEXT_MAP_WITHOUT_INITIAL_DISCARD, };
modules/platform/vendored/zwin32/src/d3d11.zig
const std = @import("std"); const mem = std.mem; const Allocator = mem.Allocator; const testing = std.testing; const builtin = @import("builtin"); const is_debug = builtin.mode == .Debug; const Entity = u32; pub fn TypedEntities(comptime Archetype: type) type { return struct { allocator: Allocator, components: std.MultiArrayList(Archetype), free_slots: std.AutoHashMap(Entity, void), pub const Archetype = Archetype; const Self = @This(); pub const Iterator = struct { e: *Self, index: Entity = 0, pub fn next(it: *Iterator) ?Archetype { std.debug.assert(it.index <= it.e.components.len); if (it.e.components.len == 0) return null; while (it.index < it.e.components.len) { if (it.e.contains(it.index)) { const current = it.index; it.index += 1; return it.e.get(current); } it.index += 1; } return null; } }; pub fn init(allocator: Allocator) Self { return .{ .allocator = allocator, .components = std.MultiArrayList(Archetype){}, .free_slots = std.AutoHashMap(Entity, void).init(allocator), }; } pub fn add(self: *Self, components: Archetype) error{OutOfMemory}!Entity { // Reuse a free slot, if available. if (self.free_slots.count() > 0) { var iter = self.free_slots.keyIterator(); const taken = iter.next().?.*; _ = self.free_slots.remove(taken); self.components.set(taken, components); return taken; } // Create a new slot, potentially allocating. try self.components.append(self.allocator, components); return @intCast(Entity, self.components.len-1); } // In debug builds, panics if the entity does not exist. pub fn update(self: *Self, entity: Entity, partial_components: anytype) void { if (is_debug and !self.contains(entity)) @panic("no such entity"); inline for (@typeInfo(@TypeOf(partial_components)).Struct.fields) |field, i| { const fieldEnum = @intToEnum(std.MultiArrayList(Archetype).Field, i); self.components.items(fieldEnum)[entity] = @field(partial_components, field.name); } } // In debug builds, panics if the entity does not exist. pub fn set(self: *Self, entity: Entity, components: Archetype) void { if (is_debug and !self.contains(entity)) @panic("no such entity"); self.components.set(entity, components); } // In debug builds, panics if the entity does not exist. pub fn remove(self: *Self, entity: Entity) error{OutOfMemory}!void { if (is_debug and !self.contains(entity)) @panic("no such entity"); try self.free_slots.put(entity, {}); } pub fn contains(self: *Self, entity: Entity) bool { if (entity > self.components.len-1) return false; return !self.free_slots.contains(entity); } // In debug builds, panics if the entity does not exist. pub fn get(self: *Self, entity: Entity) Archetype { if (is_debug and !self.contains(entity)) @panic("no such entity"); return self.components.get(entity); } /// Creates a copy using the same allocator pub inline fn clone(self: Self) !Self { return self.cloneWithAllocator(self.allocator); } /// Creates a copy using a specified allocator pub inline fn cloneWithAllocator(self: Self, new_allocator: Allocator) !Self { return Self{ .allocator = new_allocator, .components = try self.components.clone(new_allocator), .free_slots = try self.free_slots.cloneWithAllocator(new_allocator), }; } pub fn iterator(self: *Self) Iterator { return .{ .e = self }; } pub fn deinit(self: *Self) void { self.components.deinit(self.allocator); self.free_slots.deinit(); } }; } pub fn Entities(comptime archetypes: anytype) type { comptime var fields: []const std.builtin.TypeInfo.StructField = &.{}; inline for (archetypes) |Archetype| { fields = fields ++ [_]std.builtin.TypeInfo.StructField{.{ .name = @typeName(Archetype), .field_type = TypedEntities(Archetype), .is_comptime = false, .default_value = null, .alignment = 0, }}; } const ComptimeEntities = @Type(.{ .Struct = .{ .layout = .Auto, .is_tuple = false, .decls = &.{}, .fields = fields, }, }); const RuntimeEntities = struct { erased: *anyopaque, deinit: fn(Allocator, *anyopaque) void, clone: fn(Allocator, *anyopaque) error{OutOfMemory}!*anyopaque, }; return struct { allocator: Allocator, comptime_entities: ComptimeEntities, runtime_entities: std.StringHashMap(RuntimeEntities), const Self = @This(); pub fn init(allocator: Allocator) Self { var comptime_entities: ComptimeEntities = undefined; inline for (archetypes) |Archetype| { @field(comptime_entities, @typeName(Archetype)) = TypedEntities(Archetype).init(allocator); } return .{ .allocator = allocator, .comptime_entities = comptime_entities, .runtime_entities = std.StringHashMap(RuntimeEntities).init(allocator), }; } pub fn get(self: *Self, comptime Archetype: type) !*TypedEntities(Archetype) { // Comptime archetype lookup if (@hasField(ComptimeEntities, @typeName(Archetype))) { return &@field(self.comptime_entities, @typeName(Archetype)); } // Runtime archetype lookup var v = try self.runtime_entities.getOrPut(@typeName(Archetype)); if (!v.found_existing) { const new = try self.allocator.create(TypedEntities(Archetype)); new.* = TypedEntities(Archetype).init(self.allocator); v.value_ptr.* = RuntimeEntities{ .erased = new, .deinit = (struct{ pub fn deinit(allocator: Allocator, erased: *anyopaque) void { const aligned = @alignCast(@alignOf(*TypedEntities(Archetype)), erased); const entities = @ptrCast(*TypedEntities(Archetype), aligned); entities.deinit(); allocator.destroy(entities); } }.deinit), .clone = (struct { pub fn clone(new_allocator: Allocator, erased: *anyopaque) error{OutOfMemory}!*anyopaque { const aligned = @alignCast(@alignOf(*TypedEntities(Archetype)), erased); const entities = @ptrCast(*TypedEntities(Archetype), aligned); const new_erased = try new_allocator.create(TypedEntities(Archetype)); new_erased.* = try entities.cloneWithAllocator(new_allocator); return new_erased; } }).clone, }; } const aligned = @alignCast(@alignOf(*TypedEntities(Archetype)), v.value_ptr.erased); return @ptrCast(*TypedEntities(Archetype), aligned); } /// Creates a copy using the same allocator pub inline fn clone(self: Self) !Self { return self.cloneWithAllocator(self.allocator); } /// Creates a copy using a specified allocator pub fn cloneWithAllocator(self: Self, new_allocator: Allocator) !Self { var comptime_entities: ComptimeEntities = undefined; inline for (archetypes) |Archetype| { const field = @field(self.comptime_entities, @typeName(Archetype)); @field(comptime_entities, @typeName(Archetype)) = try field.cloneWithAllocator(new_allocator); } var runtime_entities = try self.runtime_entities.cloneWithAllocator(new_allocator); var iter = runtime_entities.valueIterator(); while (iter.next()) |entities| { entities.erased = try entities.clone(new_allocator, entities.erased); } return Self{ .allocator = new_allocator, .comptime_entities = comptime_entities, .runtime_entities = runtime_entities, }; } pub fn deinit(self: *Self) void { inline for (archetypes) |Archetype| { @field(self.comptime_entities, @typeName(Archetype)).deinit(); } var runtime_iter = self.runtime_entities.valueIterator(); while (runtime_iter.next()) |runtime_entities| { runtime_entities.deinit(self.allocator, runtime_entities.erased); } self.runtime_entities.deinit(); } }; } test "example" { // A location component. const Location = struct { x: f32 = 0, y: f32 = 0, z: f32 = 0, }; // A name component. const Name = []const u8; // A player archetype. const Player = struct { name: Name, location: Location = .{}, }; const allocator = testing.allocator; // Entities for e.g. a world. Stores multiple archetypes! var entities = Entities(.{ // Predeclare your archetypes up front here and you get Archetype lookups at comptime / for free! Player, }).init(allocator); defer entities.deinit(); // Get the player entities var players = try entities.get(Player); // A monster archetype const Monster = struct { name: Name, }; // Get the monster entities - note that we didn't declare this archetype up front in Entities.init! // This archetype lookup will be done at runtime via a type name hashmap var monsters = try entities.get(Monster); // Let's add some entities! const carrot = try monsters.add(.{.name = "carrot"}); const tomato = try monsters.add(.{.name = "tomato"}); const potato = try monsters.add(.{.name = "potato"}); // Remove some of our entities try monsters.remove(carrot); try monsters.remove(tomato); // Change an entity's components monsters.set(potato, .{.name = "totally real potato"}); // Don't want to set all the components of an entity? i.e. just want to set one field? This can // be more efficient: monsters.update(potato, .{.name = "secretly tomato"}); // Get all components of an entity try testing.expectEqual(Monster{.name = "secretly tomato"}, monsters.get(potato)); // Iterate entities. _ = try players.add(.{.name = "jane"}); _ = try players.add(.{.name = "bob"}); var iter = players.iterator(); try testing.expectEqualStrings("jane", iter.next().?.name); try testing.expectEqualStrings("bob", iter.next().?.name); // We can clone sets of entities, if needed. var players2 = try players.clone(); defer players2.deinit(); // Or maybe clone ALL entities! var entities2 = try entities.clone(); defer entities2.deinit(); }
ecs/src/main.zig
const std = @import("std.zig"); const debug = std.debug; const assert = debug.assert; const testing = std.testing; const math = std.math; const mem = std.mem; const meta = std.meta; const trait = meta.trait; const autoHash = std.hash.autoHash; const Wyhash = std.hash.Wyhash; const Allocator = mem.Allocator; const builtin = @import("builtin"); const hash_map = @This(); pub fn AutoArrayHashMap(comptime K: type, comptime V: type) type { return ArrayHashMap(K, V, getAutoHashFn(K), getAutoEqlFn(K), autoEqlIsCheap(K)); } pub fn AutoArrayHashMapUnmanaged(comptime K: type, comptime V: type) type { return ArrayHashMapUnmanaged(K, V, getAutoHashFn(K), getAutoEqlFn(K), autoEqlIsCheap(K)); } /// Builtin hashmap for strings as keys. pub fn StringArrayHashMap(comptime V: type) type { return ArrayHashMap([]const u8, V, hashString, eqlString, true); } pub fn StringArrayHashMapUnmanaged(comptime V: type) type { return ArrayHashMapUnmanaged([]const u8, V, hashString, eqlString, true); } pub fn eqlString(a: []const u8, b: []const u8) bool { return mem.eql(u8, a, b); } pub fn hashString(s: []const u8) u32 { return @truncate(u32, std.hash.Wyhash.hash(0, s)); } /// Insertion order is preserved. /// Deletions perform a "swap removal" on the entries list. /// Modifying the hash map while iterating is allowed, however one must understand /// the (well defined) behavior when mixing insertions and deletions with iteration. /// For a hash map that can be initialized directly that does not store an Allocator /// field, see `ArrayHashMapUnmanaged`. /// When `store_hash` is `false`, this data structure is biased towards cheap `eql` /// functions. It does not store each item's hash in the table. Setting `store_hash` /// to `true` incurs slightly more memory cost by storing each key's hash in the table /// but only has to call `eql` for hash collisions. /// If typical operations (except iteration over entries) need to be faster, prefer /// the alternative `std.HashMap`. pub fn ArrayHashMap( comptime K: type, comptime V: type, comptime hash: fn (key: K) u32, comptime eql: fn (a: K, b: K) bool, comptime store_hash: bool, ) type { return struct { unmanaged: Unmanaged, allocator: *Allocator, pub const Unmanaged = ArrayHashMapUnmanaged(K, V, hash, eql, store_hash); pub const Entry = Unmanaged.Entry; pub const Hash = Unmanaged.Hash; pub const GetOrPutResult = Unmanaged.GetOrPutResult; /// Deprecated. Iterate using `items`. pub const Iterator = struct { hm: *const Self, /// Iterator through the entry array. index: usize, pub fn next(it: *Iterator) ?*Entry { if (it.index >= it.hm.unmanaged.entries.items.len) return null; const result = &it.hm.unmanaged.entries.items[it.index]; it.index += 1; return result; } /// Reset the iterator to the initial index pub fn reset(it: *Iterator) void { it.index = 0; } }; const Self = @This(); const Index = Unmanaged.Index; pub fn init(allocator: *Allocator) Self { return .{ .unmanaged = .{}, .allocator = allocator, }; } pub fn deinit(self: *Self) void { self.unmanaged.deinit(self.allocator); self.* = undefined; } pub fn clearRetainingCapacity(self: *Self) void { return self.unmanaged.clearRetainingCapacity(); } pub fn clearAndFree(self: *Self) void { return self.unmanaged.clearAndFree(self.allocator); } /// Deprecated. Use `items().len`. pub fn count(self: Self) usize { return self.items().len; } /// Deprecated. Iterate using `items`. pub fn iterator(self: *const Self) Iterator { return Iterator{ .hm = self, .index = 0, }; } /// If key exists this function cannot fail. /// If there is an existing item with `key`, then the result /// `Entry` pointer points to it, and found_existing is true. /// Otherwise, puts a new item with undefined value, and /// the `Entry` pointer points to it. Caller should then initialize /// the value (but not the key). pub fn getOrPut(self: *Self, key: K) !GetOrPutResult { return self.unmanaged.getOrPut(self.allocator, key); } /// If there is an existing item with `key`, then the result /// `Entry` pointer points to it, and found_existing is true. /// Otherwise, puts a new item with undefined value, and /// the `Entry` pointer points to it. Caller should then initialize /// the value (but not the key). /// If a new entry needs to be stored, this function asserts there /// is enough capacity to store it. pub fn getOrPutAssumeCapacity(self: *Self, key: K) GetOrPutResult { return self.unmanaged.getOrPutAssumeCapacity(key); } pub fn getOrPutValue(self: *Self, key: K, value: V) !*Entry { return self.unmanaged.getOrPutValue(self.allocator, key, value); } /// Increases capacity, guaranteeing that insertions up until the /// `expected_count` will not cause an allocation, and therefore cannot fail. pub fn ensureCapacity(self: *Self, new_capacity: usize) !void { return self.unmanaged.ensureCapacity(self.allocator, new_capacity); } /// Returns the number of total elements which may be present before it is /// no longer guaranteed that no allocations will be performed. pub fn capacity(self: *Self) usize { return self.unmanaged.capacity(); } /// Clobbers any existing data. To detect if a put would clobber /// existing data, see `getOrPut`. pub fn put(self: *Self, key: K, value: V) !void { return self.unmanaged.put(self.allocator, key, value); } /// Inserts a key-value pair into the hash map, asserting that no previous /// entry with the same key is already present pub fn putNoClobber(self: *Self, key: K, value: V) !void { return self.unmanaged.putNoClobber(self.allocator, key, value); } /// Asserts there is enough capacity to store the new key-value pair. /// Clobbers any existing data. To detect if a put would clobber /// existing data, see `getOrPutAssumeCapacity`. pub fn putAssumeCapacity(self: *Self, key: K, value: V) void { return self.unmanaged.putAssumeCapacity(key, value); } /// Asserts there is enough capacity to store the new key-value pair. /// Asserts that it does not clobber any existing data. /// To detect if a put would clobber existing data, see `getOrPutAssumeCapacity`. pub fn putAssumeCapacityNoClobber(self: *Self, key: K, value: V) void { return self.unmanaged.putAssumeCapacityNoClobber(key, value); } /// Inserts a new `Entry` into the hash map, returning the previous one, if any. pub fn fetchPut(self: *Self, key: K, value: V) !?Entry { return self.unmanaged.fetchPut(self.allocator, key, value); } /// Inserts a new `Entry` into the hash map, returning the previous one, if any. /// If insertion happuns, asserts there is enough capacity without allocating. pub fn fetchPutAssumeCapacity(self: *Self, key: K, value: V) ?Entry { return self.unmanaged.fetchPutAssumeCapacity(key, value); } pub fn getEntry(self: Self, key: K) ?*Entry { return self.unmanaged.getEntry(key); } pub fn getIndex(self: Self, key: K) ?usize { return self.unmanaged.getIndex(key); } pub fn get(self: Self, key: K) ?V { return self.unmanaged.get(key); } pub fn contains(self: Self, key: K) bool { return self.unmanaged.contains(key); } /// If there is an `Entry` with a matching key, it is deleted from /// the hash map, and then returned from this function. pub fn remove(self: *Self, key: K) ?Entry { return self.unmanaged.remove(key); } /// Asserts there is an `Entry` with matching key, deletes it from the hash map, /// and discards it. pub fn removeAssertDiscard(self: *Self, key: K) void { return self.unmanaged.removeAssertDiscard(key); } pub fn items(self: Self) []Entry { return self.unmanaged.items(); } pub fn clone(self: Self) !Self { var other = try self.unmanaged.clone(self.allocator); return other.promote(self.allocator); } }; } /// General purpose hash table. /// Insertion order is preserved. /// Deletions perform a "swap removal" on the entries list. /// Modifying the hash map while iterating is allowed, however one must understand /// the (well defined) behavior when mixing insertions and deletions with iteration. /// This type does not store an Allocator field - the Allocator must be passed in /// with each function call that requires it. See `ArrayHashMap` for a type that stores /// an Allocator field for convenience. /// Can be initialized directly using the default field values. /// This type is designed to have low overhead for small numbers of entries. When /// `store_hash` is `false` and the number of entries in the map is less than 9, /// the overhead cost of using `ArrayHashMapUnmanaged` rather than `std.ArrayList` is /// only a single pointer-sized integer. /// When `store_hash` is `false`, this data structure is biased towards cheap `eql` /// functions. It does not store each item's hash in the table. Setting `store_hash` /// to `true` incurs slightly more memory cost by storing each key's hash in the table /// but guarantees only one call to `eql` per insertion/deletion. pub fn ArrayHashMapUnmanaged( comptime K: type, comptime V: type, comptime hash: fn (key: K) u32, comptime eql: fn (a: K, b: K) bool, comptime store_hash: bool, ) type { return struct { /// It is permitted to access this field directly. entries: std.ArrayListUnmanaged(Entry) = .{}, /// When entries length is less than `linear_scan_max`, this remains `null`. /// Once entries length grows big enough, this field is allocated. There is /// an IndexHeader followed by an array of Index(I) structs, where I is defined /// by how many total indexes there are. index_header: ?*IndexHeader = null, /// Modifying the key is illegal behavior. /// Modifying the value is allowed. /// Entry pointers become invalid whenever this ArrayHashMap is modified, /// unless `ensureCapacity` was previously used. pub const Entry = struct { /// This field is `void` if `store_hash` is `false`. hash: Hash, key: K, value: V, }; pub const Hash = if (store_hash) u32 else void; pub const GetOrPutResult = struct { entry: *Entry, found_existing: bool, }; pub const Managed = ArrayHashMap(K, V, hash, eql, store_hash); const Self = @This(); const linear_scan_max = 8; pub fn promote(self: Self, allocator: *Allocator) Managed { return .{ .unmanaged = self, .allocator = allocator, }; } pub fn deinit(self: *Self, allocator: *Allocator) void { self.entries.deinit(allocator); if (self.index_header) |header| { header.free(allocator); } self.* = undefined; } pub fn clearRetainingCapacity(self: *Self) void { self.entries.items.len = 0; if (self.index_header) |header| { header.max_distance_from_start_index = 0; switch (header.capacityIndexType()) { .u8 => mem.set(Index(u8), header.indexes(u8), Index(u8).empty), .u16 => mem.set(Index(u16), header.indexes(u16), Index(u16).empty), .u32 => mem.set(Index(u32), header.indexes(u32), Index(u32).empty), .usize => mem.set(Index(usize), header.indexes(usize), Index(usize).empty), } } } pub fn clearAndFree(self: *Self, allocator: *Allocator) void { self.entries.shrink(allocator, 0); if (self.index_header) |header| { header.free(allocator); self.index_header = null; } } /// If key exists this function cannot fail. /// If there is an existing item with `key`, then the result /// `Entry` pointer points to it, and found_existing is true. /// Otherwise, puts a new item with undefined value, and /// the `Entry` pointer points to it. Caller should then initialize /// the value (but not the key). pub fn getOrPut(self: *Self, allocator: *Allocator, key: K) !GetOrPutResult { self.ensureCapacity(allocator, self.entries.items.len + 1) catch |err| { // "If key exists this function cannot fail." return GetOrPutResult{ .entry = self.getEntry(key) orelse return err, .found_existing = true, }; }; return self.getOrPutAssumeCapacity(key); } /// If there is an existing item with `key`, then the result /// `Entry` pointer points to it, and found_existing is true. /// Otherwise, puts a new item with undefined value, and /// the `Entry` pointer points to it. Caller should then initialize /// the value (but not the key). /// If a new entry needs to be stored, this function asserts there /// is enough capacity to store it. pub fn getOrPutAssumeCapacity(self: *Self, key: K) GetOrPutResult { const header = self.index_header orelse { // Linear scan. const h = if (store_hash) hash(key) else {}; for (self.entries.items) |*item| { if (item.hash == h and eql(key, item.key)) { return GetOrPutResult{ .entry = item, .found_existing = true, }; } } const new_entry = self.entries.addOneAssumeCapacity(); new_entry.* = .{ .hash = if (store_hash) h else {}, .key = key, .value = undefined, }; return GetOrPutResult{ .entry = new_entry, .found_existing = false, }; }; switch (header.capacityIndexType()) { .u8 => return self.getOrPutInternal(key, header, u8), .u16 => return self.getOrPutInternal(key, header, u16), .u32 => return self.getOrPutInternal(key, header, u32), .usize => return self.getOrPutInternal(key, header, usize), } } pub fn getOrPutValue(self: *Self, allocator: *Allocator, key: K, value: V) !*Entry { const res = try self.getOrPut(allocator, key); if (!res.found_existing) res.entry.value = value; return res.entry; } /// Increases capacity, guaranteeing that insertions up until the /// `expected_count` will not cause an allocation, and therefore cannot fail. pub fn ensureCapacity(self: *Self, allocator: *Allocator, new_capacity: usize) !void { try self.entries.ensureCapacity(allocator, new_capacity); if (new_capacity <= linear_scan_max) return; // Ensure that the indexes will be at most 60% full if // `new_capacity` items are put into it. const needed_len = new_capacity * 5 / 3; if (self.index_header) |header| { if (needed_len > header.indexes_len) { // An overflow here would mean the amount of memory required would not // be representable in the address space. const new_indexes_len = math.ceilPowerOfTwo(usize, needed_len) catch unreachable; const new_header = try IndexHeader.alloc(allocator, new_indexes_len); self.insertAllEntriesIntoNewHeader(new_header); header.free(allocator); self.index_header = new_header; } } else { // An overflow here would mean the amount of memory required would not // be representable in the address space. const new_indexes_len = math.ceilPowerOfTwo(usize, needed_len) catch unreachable; const header = try IndexHeader.alloc(allocator, new_indexes_len); self.insertAllEntriesIntoNewHeader(header); self.index_header = header; } } /// Returns the number of total elements which may be present before it is /// no longer guaranteed that no allocations will be performed. pub fn capacity(self: Self) usize { const entry_cap = self.entries.capacity; const header = self.index_header orelse return math.min(linear_scan_max, entry_cap); const indexes_cap = (header.indexes_len + 1) * 3 / 4; return math.min(entry_cap, indexes_cap); } /// Clobbers any existing data. To detect if a put would clobber /// existing data, see `getOrPut`. pub fn put(self: *Self, allocator: *Allocator, key: K, value: V) !void { const result = try self.getOrPut(allocator, key); result.entry.value = value; } /// Inserts a key-value pair into the hash map, asserting that no previous /// entry with the same key is already present pub fn putNoClobber(self: *Self, allocator: *Allocator, key: K, value: V) !void { const result = try self.getOrPut(allocator, key); assert(!result.found_existing); result.entry.value = value; } /// Asserts there is enough capacity to store the new key-value pair. /// Clobbers any existing data. To detect if a put would clobber /// existing data, see `getOrPutAssumeCapacity`. pub fn putAssumeCapacity(self: *Self, key: K, value: V) void { const result = self.getOrPutAssumeCapacity(key); result.entry.value = value; } /// Asserts there is enough capacity to store the new key-value pair. /// Asserts that it does not clobber any existing data. /// To detect if a put would clobber existing data, see `getOrPutAssumeCapacity`. pub fn putAssumeCapacityNoClobber(self: *Self, key: K, value: V) void { const result = self.getOrPutAssumeCapacity(key); assert(!result.found_existing); result.entry.value = value; } /// Inserts a new `Entry` into the hash map, returning the previous one, if any. pub fn fetchPut(self: *Self, allocator: *Allocator, key: K, value: V) !?Entry { const gop = try self.getOrPut(allocator, key); var result: ?Entry = null; if (gop.found_existing) { result = gop.entry.*; } gop.entry.value = value; return result; } /// Inserts a new `Entry` into the hash map, returning the previous one, if any. /// If insertion happens, asserts there is enough capacity without allocating. pub fn fetchPutAssumeCapacity(self: *Self, key: K, value: V) ?Entry { const gop = self.getOrPutAssumeCapacity(key); var result: ?Entry = null; if (gop.found_existing) { result = gop.entry.*; } gop.entry.value = value; return result; } pub fn getEntry(self: Self, key: K) ?*Entry { const index = self.getIndex(key) orelse return null; return &self.entries.items[index]; } pub fn getIndex(self: Self, key: K) ?usize { const header = self.index_header orelse { // Linear scan. const h = if (store_hash) hash(key) else {}; for (self.entries.items) |*item, i| { if (item.hash == h and eql(key, item.key)) { return i; } } return null; }; switch (header.capacityIndexType()) { .u8 => return self.getInternal(key, header, u8), .u16 => return self.getInternal(key, header, u16), .u32 => return self.getInternal(key, header, u32), .usize => return self.getInternal(key, header, usize), } } pub fn get(self: Self, key: K) ?V { return if (self.getEntry(key)) |entry| entry.value else null; } pub fn contains(self: Self, key: K) bool { return self.getEntry(key) != null; } /// If there is an `Entry` with a matching key, it is deleted from /// the hash map, and then returned from this function. pub fn remove(self: *Self, key: K) ?Entry { const header = self.index_header orelse { // Linear scan. const h = if (store_hash) hash(key) else {}; for (self.entries.items) |item, i| { if (item.hash == h and eql(key, item.key)) { return self.entries.swapRemove(i); } } return null; }; switch (header.capacityIndexType()) { .u8 => return self.removeInternal(key, header, u8), .u16 => return self.removeInternal(key, header, u16), .u32 => return self.removeInternal(key, header, u32), .usize => return self.removeInternal(key, header, usize), } } /// Asserts there is an `Entry` with matching key, deletes it from the hash map, /// and discards it. pub fn removeAssertDiscard(self: *Self, key: K) void { assert(self.remove(key) != null); } pub fn items(self: Self) []Entry { return self.entries.items; } pub fn clone(self: Self, allocator: *Allocator) !Self { var other: Self = .{}; try other.entries.appendSlice(allocator, self.entries.items); if (self.index_header) |header| { const new_header = try IndexHeader.alloc(allocator, header.indexes_len); other.insertAllEntriesIntoNewHeader(new_header); other.index_header = new_header; } return other; } fn removeInternal(self: *Self, key: K, header: *IndexHeader, comptime I: type) ?Entry { const indexes = header.indexes(I); const h = hash(key); const start_index = header.constrainIndex(h); var roll_over: usize = 0; while (roll_over <= header.max_distance_from_start_index) : (roll_over += 1) { const index_index = header.constrainIndex(start_index + roll_over); var index = &indexes[index_index]; if (index.isEmpty()) return null; const entry = &self.entries.items[index.entry_index]; const hash_match = if (store_hash) h == entry.hash else true; if (!hash_match or !eql(key, entry.key)) continue; const removed_entry = self.entries.swapRemove(index.entry_index); if (self.entries.items.len > 0 and self.entries.items.len != index.entry_index) { // Because of the swap remove, now we need to update the index that was // pointing to the last entry and is now pointing to this removed item slot. self.updateEntryIndex(header, self.entries.items.len, index.entry_index, I, indexes); } // Now we have to shift over the following indexes. roll_over += 1; while (roll_over < header.indexes_len) : (roll_over += 1) { const next_index_index = header.constrainIndex(start_index + roll_over); const next_index = &indexes[next_index_index]; if (next_index.isEmpty() or next_index.distance_from_start_index == 0) { index.setEmpty(); return removed_entry; } index.* = next_index.*; index.distance_from_start_index -= 1; index = next_index; } unreachable; } return null; } fn updateEntryIndex( self: *Self, header: *IndexHeader, old_entry_index: usize, new_entry_index: usize, comptime I: type, indexes: []Index(I), ) void { const h = if (store_hash) self.entries.items[new_entry_index].hash else hash(self.entries.items[new_entry_index].key); const start_index = header.constrainIndex(h); var roll_over: usize = 0; while (roll_over <= header.max_distance_from_start_index) : (roll_over += 1) { const index_index = header.constrainIndex(start_index + roll_over); const index = &indexes[index_index]; if (index.entry_index == old_entry_index) { index.entry_index = @intCast(I, new_entry_index); return; } } unreachable; } /// Must ensureCapacity before calling this. fn getOrPutInternal(self: *Self, key: K, header: *IndexHeader, comptime I: type) GetOrPutResult { const indexes = header.indexes(I); const h = hash(key); const start_index = header.constrainIndex(h); var roll_over: usize = 0; var distance_from_start_index: usize = 0; while (roll_over <= header.indexes_len) : ({ roll_over += 1; distance_from_start_index += 1; }) { const index_index = header.constrainIndex(start_index + roll_over); const index = indexes[index_index]; if (index.isEmpty()) { indexes[index_index] = .{ .distance_from_start_index = @intCast(I, distance_from_start_index), .entry_index = @intCast(I, self.entries.items.len), }; header.maybeBumpMax(distance_from_start_index); const new_entry = self.entries.addOneAssumeCapacity(); new_entry.* = .{ .hash = if (store_hash) h else {}, .key = key, .value = undefined, }; return .{ .found_existing = false, .entry = new_entry, }; } // This pointer survives the following append because we call // entries.ensureCapacity before getOrPutInternal. const entry = &self.entries.items[index.entry_index]; const hash_match = if (store_hash) h == entry.hash else true; if (hash_match and eql(key, entry.key)) { return .{ .found_existing = true, .entry = entry, }; } if (index.distance_from_start_index < distance_from_start_index) { // In this case, we did not find the item. We will put a new entry. // However, we will use this index for the new entry, and move // the previous index down the line, to keep the max_distance_from_start_index // as small as possible. indexes[index_index] = .{ .distance_from_start_index = @intCast(I, distance_from_start_index), .entry_index = @intCast(I, self.entries.items.len), }; header.maybeBumpMax(distance_from_start_index); const new_entry = self.entries.addOneAssumeCapacity(); new_entry.* = .{ .hash = if (store_hash) h else {}, .key = key, .value = undefined, }; distance_from_start_index = index.distance_from_start_index; var prev_entry_index = index.entry_index; // Find somewhere to put the index we replaced by shifting // following indexes backwards. roll_over += 1; distance_from_start_index += 1; while (roll_over < header.indexes_len) : ({ roll_over += 1; distance_from_start_index += 1; }) { const next_index_index = header.constrainIndex(start_index + roll_over); const next_index = indexes[next_index_index]; if (next_index.isEmpty()) { header.maybeBumpMax(distance_from_start_index); indexes[next_index_index] = .{ .entry_index = prev_entry_index, .distance_from_start_index = @intCast(I, distance_from_start_index), }; return .{ .found_existing = false, .entry = new_entry, }; } if (next_index.distance_from_start_index < distance_from_start_index) { header.maybeBumpMax(distance_from_start_index); indexes[next_index_index] = .{ .entry_index = prev_entry_index, .distance_from_start_index = @intCast(I, distance_from_start_index), }; distance_from_start_index = next_index.distance_from_start_index; prev_entry_index = next_index.entry_index; } } unreachable; } } unreachable; } fn getInternal(self: Self, key: K, header: *IndexHeader, comptime I: type) ?usize { const indexes = header.indexes(I); const h = hash(key); const start_index = header.constrainIndex(h); var roll_over: usize = 0; while (roll_over <= header.max_distance_from_start_index) : (roll_over += 1) { const index_index = header.constrainIndex(start_index + roll_over); const index = indexes[index_index]; if (index.isEmpty()) return null; const entry = &self.entries.items[index.entry_index]; const hash_match = if (store_hash) h == entry.hash else true; if (hash_match and eql(key, entry.key)) return index.entry_index; } return null; } fn insertAllEntriesIntoNewHeader(self: *Self, header: *IndexHeader) void { switch (header.capacityIndexType()) { .u8 => return self.insertAllEntriesIntoNewHeaderGeneric(header, u8), .u16 => return self.insertAllEntriesIntoNewHeaderGeneric(header, u16), .u32 => return self.insertAllEntriesIntoNewHeaderGeneric(header, u32), .usize => return self.insertAllEntriesIntoNewHeaderGeneric(header, usize), } } fn insertAllEntriesIntoNewHeaderGeneric(self: *Self, header: *IndexHeader, comptime I: type) void { const indexes = header.indexes(I); entry_loop: for (self.entries.items) |entry, i| { const h = if (store_hash) entry.hash else hash(entry.key); const start_index = header.constrainIndex(h); var entry_index = i; var roll_over: usize = 0; var distance_from_start_index: usize = 0; while (roll_over < header.indexes_len) : ({ roll_over += 1; distance_from_start_index += 1; }) { const index_index = header.constrainIndex(start_index + roll_over); const next_index = indexes[index_index]; if (next_index.isEmpty()) { header.maybeBumpMax(distance_from_start_index); indexes[index_index] = .{ .distance_from_start_index = @intCast(I, distance_from_start_index), .entry_index = @intCast(I, entry_index), }; continue :entry_loop; } if (next_index.distance_from_start_index < distance_from_start_index) { header.maybeBumpMax(distance_from_start_index); indexes[index_index] = .{ .distance_from_start_index = @intCast(I, distance_from_start_index), .entry_index = @intCast(I, entry_index), }; distance_from_start_index = next_index.distance_from_start_index; entry_index = next_index.entry_index; } } unreachable; } } }; } const CapacityIndexType = enum { u8, u16, u32, usize }; fn capacityIndexType(indexes_len: usize) CapacityIndexType { if (indexes_len < math.maxInt(u8)) return .u8; if (indexes_len < math.maxInt(u16)) return .u16; if (indexes_len < math.maxInt(u32)) return .u32; return .usize; } fn capacityIndexSize(indexes_len: usize) usize { switch (capacityIndexType(indexes_len)) { .u8 => return @sizeOf(Index(u8)), .u16 => return @sizeOf(Index(u16)), .u32 => return @sizeOf(Index(u32)), .usize => return @sizeOf(Index(usize)), } } fn Index(comptime I: type) type { return extern struct { entry_index: I, distance_from_start_index: I, const Self = @This(); const empty = Self{ .entry_index = math.maxInt(I), .distance_from_start_index = undefined, }; fn isEmpty(idx: Self) bool { return idx.entry_index == math.maxInt(I); } fn setEmpty(idx: *Self) void { idx.entry_index = math.maxInt(I); } }; } /// This struct is trailed by an array of `Index(I)`, where `I` /// and the array length are determined by `indexes_len`. const IndexHeader = struct { max_distance_from_start_index: usize, indexes_len: usize, fn constrainIndex(header: IndexHeader, i: usize) usize { // This is an optimization for modulo of power of two integers; // it requires `indexes_len` to always be a power of two. return i & (header.indexes_len - 1); } fn indexes(header: *IndexHeader, comptime I: type) []Index(I) { const start = @ptrCast([*]Index(I), @ptrCast([*]u8, header) + @sizeOf(IndexHeader)); return start[0..header.indexes_len]; } fn capacityIndexType(header: IndexHeader) CapacityIndexType { return hash_map.capacityIndexType(header.indexes_len); } fn maybeBumpMax(header: *IndexHeader, distance_from_start_index: usize) void { if (distance_from_start_index > header.max_distance_from_start_index) { header.max_distance_from_start_index = distance_from_start_index; } } fn alloc(allocator: *Allocator, len: usize) !*IndexHeader { const index_size = hash_map.capacityIndexSize(len); const nbytes = @sizeOf(IndexHeader) + index_size * len; const bytes = try allocator.allocAdvanced(u8, @alignOf(IndexHeader), nbytes, .exact); @memset(bytes.ptr + @sizeOf(IndexHeader), 0xff, bytes.len - @sizeOf(IndexHeader)); const result = @ptrCast(*IndexHeader, bytes.ptr); result.* = .{ .max_distance_from_start_index = 0, .indexes_len = len, }; return result; } fn free(header: *IndexHeader, allocator: *Allocator) void { const index_size = hash_map.capacityIndexSize(header.indexes_len); const ptr = @ptrCast([*]u8, header); const slice = ptr[0 .. @sizeOf(IndexHeader) + header.indexes_len * index_size]; allocator.free(slice); } }; test "basic hash map usage" { var map = AutoArrayHashMap(i32, i32).init(std.testing.allocator); defer map.deinit(); testing.expect((try map.fetchPut(1, 11)) == null); testing.expect((try map.fetchPut(2, 22)) == null); testing.expect((try map.fetchPut(3, 33)) == null); testing.expect((try map.fetchPut(4, 44)) == null); try map.putNoClobber(5, 55); testing.expect((try map.fetchPut(5, 66)).?.value == 55); testing.expect((try map.fetchPut(5, 55)).?.value == 66); const gop1 = try map.getOrPut(5); testing.expect(gop1.found_existing == true); testing.expect(gop1.entry.value == 55); gop1.entry.value = 77; testing.expect(map.getEntry(5).?.value == 77); const gop2 = try map.getOrPut(99); testing.expect(gop2.found_existing == false); gop2.entry.value = 42; testing.expect(map.getEntry(99).?.value == 42); const gop3 = try map.getOrPutValue(5, 5); testing.expect(gop3.value == 77); const gop4 = try map.getOrPutValue(100, 41); testing.expect(gop4.value == 41); testing.expect(map.contains(2)); testing.expect(map.getEntry(2).?.value == 22); testing.expect(map.get(2).? == 22); const rmv1 = map.remove(2); testing.expect(rmv1.?.key == 2); testing.expect(rmv1.?.value == 22); testing.expect(map.remove(2) == null); testing.expect(map.getEntry(2) == null); testing.expect(map.get(2) == null); map.removeAssertDiscard(3); } test "iterator hash map" { // https://github.com/ziglang/zig/issues/5127 if (std.Target.current.cpu.arch == .mips) return error.SkipZigTest; var reset_map = AutoArrayHashMap(i32, i32).init(std.testing.allocator); defer reset_map.deinit(); // test ensureCapacity with a 0 parameter try reset_map.ensureCapacity(0); try reset_map.putNoClobber(0, 11); try reset_map.putNoClobber(1, 22); try reset_map.putNoClobber(2, 33); var keys = [_]i32{ 0, 2, 1, }; var values = [_]i32{ 11, 33, 22, }; var buffer = [_]i32{ 0, 0, 0, }; var it = reset_map.iterator(); const first_entry = it.next().?; it.reset(); var count: usize = 0; while (it.next()) |entry| : (count += 1) { buffer[@intCast(usize, entry.key)] = entry.value; } testing.expect(count == 3); testing.expect(it.next() == null); for (buffer) |v, i| { testing.expect(buffer[@intCast(usize, keys[i])] == values[i]); } it.reset(); count = 0; while (it.next()) |entry| { buffer[@intCast(usize, entry.key)] = entry.value; count += 1; if (count >= 2) break; } for (buffer[0..2]) |v, i| { testing.expect(buffer[@intCast(usize, keys[i])] == values[i]); } it.reset(); var entry = it.next().?; testing.expect(entry.key == first_entry.key); testing.expect(entry.value == first_entry.value); } test "ensure capacity" { var map = AutoArrayHashMap(i32, i32).init(std.testing.allocator); defer map.deinit(); try map.ensureCapacity(20); const initial_capacity = map.capacity(); testing.expect(initial_capacity >= 20); var i: i32 = 0; while (i < 20) : (i += 1) { testing.expect(map.fetchPutAssumeCapacity(i, i + 10) == null); } // shouldn't resize from putAssumeCapacity testing.expect(initial_capacity == map.capacity()); } test "clone" { var original = AutoArrayHashMap(i32, i32).init(std.testing.allocator); defer original.deinit(); // put more than `linear_scan_max` so we can test that the index header is properly cloned var i: u8 = 0; while (i < 10) : (i += 1) { try original.putNoClobber(i, i * 10); } var copy = try original.clone(); defer copy.deinit(); i = 0; while (i < 10) : (i += 1) { testing.expect(copy.get(i).? == i * 10); } } pub fn getHashPtrAddrFn(comptime K: type) (fn (K) u32) { return struct { fn hash(key: K) u32 { return getAutoHashFn(usize)(@ptrToInt(key)); } }.hash; } pub fn getTrivialEqlFn(comptime K: type) (fn (K, K) bool) { return struct { fn eql(a: K, b: K) bool { return a == b; } }.eql; } pub fn getAutoHashFn(comptime K: type) (fn (K) u32) { return struct { fn hash(key: K) u32 { if (comptime trait.hasUniqueRepresentation(K)) { return @truncate(u32, Wyhash.hash(0, std.mem.asBytes(&key))); } else { var hasher = Wyhash.init(0); autoHash(&hasher, key); return @truncate(u32, hasher.final()); } } }.hash; } pub fn getAutoEqlFn(comptime K: type) (fn (K, K) bool) { return struct { fn eql(a: K, b: K) bool { return meta.eql(a, b); } }.eql; } pub fn autoEqlIsCheap(comptime K: type) bool { return switch (@typeInfo(K)) { .Bool, .Int, .Float, .Pointer, .ComptimeFloat, .ComptimeInt, .Enum, .Fn, .ErrorSet, .AnyFrame, .EnumLiteral, => true, else => false, }; } pub fn getAutoHashStratFn(comptime K: type, comptime strategy: std.hash.Strategy) (fn (K) u32) { return struct { fn hash(key: K) u32 { var hasher = Wyhash.init(0); std.hash.autoHashStrat(&hasher, key, strategy); return @truncate(u32, hasher.final()); } }.hash; }
lib/std/array_hash_map.zig
const std = @import("std"); const mem = std.mem; const OtherLetter = @This(); allocator: *mem.Allocator, array: []bool, lo: u21 = 170, hi: u21 = 201546, pub fn init(allocator: *mem.Allocator) !OtherLetter { var instance = OtherLetter{ .allocator = allocator, .array = try allocator.alloc(bool, 201377), }; mem.set(bool, instance.array, false); var index: u21 = 0; instance.array[0] = true; instance.array[16] = true; instance.array[273] = true; index = 278; while (index <= 281) : (index += 1) { instance.array[index] = true; } instance.array[490] = true; index = 1318; while (index <= 1344) : (index += 1) { instance.array[index] = true; } index = 1349; while (index <= 1352) : (index += 1) { instance.array[index] = true; } index = 1398; while (index <= 1429) : (index += 1) { instance.array[index] = true; } index = 1431; while (index <= 1440) : (index += 1) { instance.array[index] = true; } index = 1476; while (index <= 1477) : (index += 1) { instance.array[index] = true; } index = 1479; while (index <= 1577) : (index += 1) { instance.array[index] = true; } instance.array[1579] = true; index = 1604; while (index <= 1605) : (index += 1) { instance.array[index] = true; } index = 1616; while (index <= 1618) : (index += 1) { instance.array[index] = true; } instance.array[1621] = true; instance.array[1638] = true; index = 1640; while (index <= 1669) : (index += 1) { instance.array[index] = true; } index = 1699; while (index <= 1787) : (index += 1) { instance.array[index] = true; } instance.array[1799] = true; index = 1824; while (index <= 1856) : (index += 1) { instance.array[index] = true; } index = 1878; while (index <= 1899) : (index += 1) { instance.array[index] = true; } index = 1942; while (index <= 1966) : (index += 1) { instance.array[index] = true; } index = 1974; while (index <= 1984) : (index += 1) { instance.array[index] = true; } index = 2038; while (index <= 2058) : (index += 1) { instance.array[index] = true; } index = 2060; while (index <= 2077) : (index += 1) { instance.array[index] = true; } index = 2138; while (index <= 2191) : (index += 1) { instance.array[index] = true; } instance.array[2195] = true; instance.array[2214] = true; index = 2222; while (index <= 2231) : (index += 1) { instance.array[index] = true; } index = 2248; while (index <= 2262) : (index += 1) { instance.array[index] = true; } index = 2267; while (index <= 2274) : (index += 1) { instance.array[index] = true; } index = 2277; while (index <= 2278) : (index += 1) { instance.array[index] = true; } index = 2281; while (index <= 2302) : (index += 1) { instance.array[index] = true; } index = 2304; while (index <= 2310) : (index += 1) { instance.array[index] = true; } instance.array[2312] = true; index = 2316; while (index <= 2319) : (index += 1) { instance.array[index] = true; } instance.array[2323] = true; instance.array[2340] = true; index = 2354; while (index <= 2355) : (index += 1) { instance.array[index] = true; } index = 2357; while (index <= 2359) : (index += 1) { instance.array[index] = true; } index = 2374; while (index <= 2375) : (index += 1) { instance.array[index] = true; } instance.array[2386] = true; index = 2395; while (index <= 2400) : (index += 1) { instance.array[index] = true; } index = 2405; while (index <= 2406) : (index += 1) { instance.array[index] = true; } index = 2409; while (index <= 2430) : (index += 1) { instance.array[index] = true; } index = 2432; while (index <= 2438) : (index += 1) { instance.array[index] = true; } index = 2440; while (index <= 2441) : (index += 1) { instance.array[index] = true; } index = 2443; while (index <= 2444) : (index += 1) { instance.array[index] = true; } index = 2446; while (index <= 2447) : (index += 1) { instance.array[index] = true; } index = 2479; while (index <= 2482) : (index += 1) { instance.array[index] = true; } instance.array[2484] = true; index = 2504; while (index <= 2506) : (index += 1) { instance.array[index] = true; } index = 2523; while (index <= 2531) : (index += 1) { instance.array[index] = true; } index = 2533; while (index <= 2535) : (index += 1) { instance.array[index] = true; } index = 2537; while (index <= 2558) : (index += 1) { instance.array[index] = true; } index = 2560; while (index <= 2566) : (index += 1) { instance.array[index] = true; } index = 2568; while (index <= 2569) : (index += 1) { instance.array[index] = true; } index = 2571; while (index <= 2575) : (index += 1) { instance.array[index] = true; } instance.array[2579] = true; instance.array[2598] = true; index = 2614; while (index <= 2615) : (index += 1) { instance.array[index] = true; } instance.array[2639] = true; index = 2651; while (index <= 2658) : (index += 1) { instance.array[index] = true; } index = 2661; while (index <= 2662) : (index += 1) { instance.array[index] = true; } index = 2665; while (index <= 2686) : (index += 1) { instance.array[index] = true; } index = 2688; while (index <= 2694) : (index += 1) { instance.array[index] = true; } index = 2696; while (index <= 2697) : (index += 1) { instance.array[index] = true; } index = 2699; while (index <= 2703) : (index += 1) { instance.array[index] = true; } instance.array[2707] = true; index = 2738; while (index <= 2739) : (index += 1) { instance.array[index] = true; } index = 2741; while (index <= 2743) : (index += 1) { instance.array[index] = true; } instance.array[2759] = true; instance.array[2777] = true; index = 2779; while (index <= 2784) : (index += 1) { instance.array[index] = true; } index = 2788; while (index <= 2790) : (index += 1) { instance.array[index] = true; } index = 2792; while (index <= 2795) : (index += 1) { instance.array[index] = true; } index = 2799; while (index <= 2800) : (index += 1) { instance.array[index] = true; } instance.array[2802] = true; index = 2804; while (index <= 2805) : (index += 1) { instance.array[index] = true; } index = 2809; while (index <= 2810) : (index += 1) { instance.array[index] = true; } index = 2814; while (index <= 2816) : (index += 1) { instance.array[index] = true; } index = 2820; while (index <= 2831) : (index += 1) { instance.array[index] = true; } instance.array[2854] = true; index = 2907; while (index <= 2914) : (index += 1) { instance.array[index] = true; } index = 2916; while (index <= 2918) : (index += 1) { instance.array[index] = true; } index = 2920; while (index <= 2942) : (index += 1) { instance.array[index] = true; } index = 2944; while (index <= 2959) : (index += 1) { instance.array[index] = true; } instance.array[2963] = true; index = 2990; while (index <= 2992) : (index += 1) { instance.array[index] = true; } index = 2998; while (index <= 2999) : (index += 1) { instance.array[index] = true; } instance.array[3030] = true; index = 3035; while (index <= 3042) : (index += 1) { instance.array[index] = true; } index = 3044; while (index <= 3046) : (index += 1) { instance.array[index] = true; } index = 3048; while (index <= 3070) : (index += 1) { instance.array[index] = true; } index = 3072; while (index <= 3081) : (index += 1) { instance.array[index] = true; } index = 3083; while (index <= 3087) : (index += 1) { instance.array[index] = true; } instance.array[3091] = true; instance.array[3124] = true; index = 3126; while (index <= 3127) : (index += 1) { instance.array[index] = true; } index = 3143; while (index <= 3144) : (index += 1) { instance.array[index] = true; } index = 3162; while (index <= 3170) : (index += 1) { instance.array[index] = true; } index = 3172; while (index <= 3174) : (index += 1) { instance.array[index] = true; } index = 3176; while (index <= 3216) : (index += 1) { instance.array[index] = true; } instance.array[3219] = true; instance.array[3236] = true; index = 3242; while (index <= 3244) : (index += 1) { instance.array[index] = true; } index = 3253; while (index <= 3255) : (index += 1) { instance.array[index] = true; } index = 3280; while (index <= 3285) : (index += 1) { instance.array[index] = true; } index = 3291; while (index <= 3308) : (index += 1) { instance.array[index] = true; } index = 3312; while (index <= 3335) : (index += 1) { instance.array[index] = true; } index = 3337; while (index <= 3345) : (index += 1) { instance.array[index] = true; } instance.array[3347] = true; index = 3350; while (index <= 3356) : (index += 1) { instance.array[index] = true; } index = 3415; while (index <= 3462) : (index += 1) { instance.array[index] = true; } index = 3464; while (index <= 3465) : (index += 1) { instance.array[index] = true; } index = 3478; while (index <= 3483) : (index += 1) { instance.array[index] = true; } index = 3543; while (index <= 3544) : (index += 1) { instance.array[index] = true; } instance.array[3546] = true; index = 3548; while (index <= 3552) : (index += 1) { instance.array[index] = true; } index = 3554; while (index <= 3577) : (index += 1) { instance.array[index] = true; } instance.array[3579] = true; index = 3581; while (index <= 3590) : (index += 1) { instance.array[index] = true; } index = 3592; while (index <= 3593) : (index += 1) { instance.array[index] = true; } instance.array[3603] = true; index = 3606; while (index <= 3610) : (index += 1) { instance.array[index] = true; } index = 3634; while (index <= 3637) : (index += 1) { instance.array[index] = true; } instance.array[3670] = true; index = 3734; while (index <= 3741) : (index += 1) { instance.array[index] = true; } index = 3743; while (index <= 3778) : (index += 1) { instance.array[index] = true; } index = 3806; while (index <= 3810) : (index += 1) { instance.array[index] = true; } index = 3926; while (index <= 3968) : (index += 1) { instance.array[index] = true; } instance.array[3989] = true; index = 4006; while (index <= 4011) : (index += 1) { instance.array[index] = true; } index = 4016; while (index <= 4019) : (index += 1) { instance.array[index] = true; } instance.array[4023] = true; index = 4027; while (index <= 4028) : (index += 1) { instance.array[index] = true; } index = 4036; while (index <= 4038) : (index += 1) { instance.array[index] = true; } index = 4043; while (index <= 4055) : (index += 1) { instance.array[index] = true; } instance.array[4068] = true; index = 4182; while (index <= 4510) : (index += 1) { instance.array[index] = true; } index = 4512; while (index <= 4515) : (index += 1) { instance.array[index] = true; } index = 4518; while (index <= 4524) : (index += 1) { instance.array[index] = true; } instance.array[4526] = true; index = 4528; while (index <= 4531) : (index += 1) { instance.array[index] = true; } index = 4534; while (index <= 4574) : (index += 1) { instance.array[index] = true; } index = 4576; while (index <= 4579) : (index += 1) { instance.array[index] = true; } index = 4582; while (index <= 4614) : (index += 1) { instance.array[index] = true; } index = 4616; while (index <= 4619) : (index += 1) { instance.array[index] = true; } index = 4622; while (index <= 4628) : (index += 1) { instance.array[index] = true; } instance.array[4630] = true; index = 4632; while (index <= 4635) : (index += 1) { instance.array[index] = true; } index = 4638; while (index <= 4652) : (index += 1) { instance.array[index] = true; } index = 4654; while (index <= 4710) : (index += 1) { instance.array[index] = true; } index = 4712; while (index <= 4715) : (index += 1) { instance.array[index] = true; } index = 4718; while (index <= 4784) : (index += 1) { instance.array[index] = true; } index = 4822; while (index <= 4837) : (index += 1) { instance.array[index] = true; } index = 4951; while (index <= 5570) : (index += 1) { instance.array[index] = true; } index = 5573; while (index <= 5589) : (index += 1) { instance.array[index] = true; } index = 5591; while (index <= 5616) : (index += 1) { instance.array[index] = true; } index = 5622; while (index <= 5696) : (index += 1) { instance.array[index] = true; } index = 5703; while (index <= 5710) : (index += 1) { instance.array[index] = true; } index = 5718; while (index <= 5730) : (index += 1) { instance.array[index] = true; } index = 5732; while (index <= 5735) : (index += 1) { instance.array[index] = true; } index = 5750; while (index <= 5767) : (index += 1) { instance.array[index] = true; } index = 5782; while (index <= 5799) : (index += 1) { instance.array[index] = true; } index = 5814; while (index <= 5826) : (index += 1) { instance.array[index] = true; } index = 5828; while (index <= 5830) : (index += 1) { instance.array[index] = true; } index = 5846; while (index <= 5897) : (index += 1) { instance.array[index] = true; } instance.array[5938] = true; index = 6006; while (index <= 6040) : (index += 1) { instance.array[index] = true; } index = 6042; while (index <= 6094) : (index += 1) { instance.array[index] = true; } index = 6102; while (index <= 6106) : (index += 1) { instance.array[index] = true; } index = 6109; while (index <= 6142) : (index += 1) { instance.array[index] = true; } instance.array[6144] = true; index = 6150; while (index <= 6219) : (index += 1) { instance.array[index] = true; } index = 6230; while (index <= 6260) : (index += 1) { instance.array[index] = true; } index = 6310; while (index <= 6339) : (index += 1) { instance.array[index] = true; } index = 6342; while (index <= 6346) : (index += 1) { instance.array[index] = true; } index = 6358; while (index <= 6401) : (index += 1) { instance.array[index] = true; } index = 6406; while (index <= 6431) : (index += 1) { instance.array[index] = true; } index = 6486; while (index <= 6508) : (index += 1) { instance.array[index] = true; } index = 6518; while (index <= 6570) : (index += 1) { instance.array[index] = true; } index = 6747; while (index <= 6793) : (index += 1) { instance.array[index] = true; } index = 6811; while (index <= 6817) : (index += 1) { instance.array[index] = true; } index = 6873; while (index <= 6902) : (index += 1) { instance.array[index] = true; } index = 6916; while (index <= 6917) : (index += 1) { instance.array[index] = true; } index = 6928; while (index <= 6971) : (index += 1) { instance.array[index] = true; } index = 6998; while (index <= 7033) : (index += 1) { instance.array[index] = true; } index = 7075; while (index <= 7077) : (index += 1) { instance.array[index] = true; } index = 7088; while (index <= 7117) : (index += 1) { instance.array[index] = true; } index = 7231; while (index <= 7234) : (index += 1) { instance.array[index] = true; } index = 7236; while (index <= 7241) : (index += 1) { instance.array[index] = true; } index = 7243; while (index <= 7244) : (index += 1) { instance.array[index] = true; } instance.array[7248] = true; index = 8331; while (index <= 8334) : (index += 1) { instance.array[index] = true; } index = 11398; while (index <= 11453) : (index += 1) { instance.array[index] = true; } index = 11478; while (index <= 11500) : (index += 1) { instance.array[index] = true; } index = 11510; while (index <= 11516) : (index += 1) { instance.array[index] = true; } index = 11518; while (index <= 11524) : (index += 1) { instance.array[index] = true; } index = 11526; while (index <= 11532) : (index += 1) { instance.array[index] = true; } index = 11534; while (index <= 11540) : (index += 1) { instance.array[index] = true; } index = 11542; while (index <= 11548) : (index += 1) { instance.array[index] = true; } index = 11550; while (index <= 11556) : (index += 1) { instance.array[index] = true; } index = 11558; while (index <= 11564) : (index += 1) { instance.array[index] = true; } index = 11566; while (index <= 11572) : (index += 1) { instance.array[index] = true; } instance.array[12124] = true; instance.array[12178] = true; index = 12183; while (index <= 12268) : (index += 1) { instance.array[index] = true; } instance.array[12277] = true; index = 12279; while (index <= 12368) : (index += 1) { instance.array[index] = true; } instance.array[12373] = true; index = 12379; while (index <= 12421) : (index += 1) { instance.array[index] = true; } index = 12423; while (index <= 12516) : (index += 1) { instance.array[index] = true; } index = 12534; while (index <= 12565) : (index += 1) { instance.array[index] = true; } index = 12614; while (index <= 12629) : (index += 1) { instance.array[index] = true; } index = 13142; while (index <= 19733) : (index += 1) { instance.array[index] = true; } index = 19798; while (index <= 40786) : (index += 1) { instance.array[index] = true; } index = 40790; while (index <= 40810) : (index += 1) { instance.array[index] = true; } index = 40812; while (index <= 41954) : (index += 1) { instance.array[index] = true; } index = 42022; while (index <= 42061) : (index += 1) { instance.array[index] = true; } index = 42070; while (index <= 42337) : (index += 1) { instance.array[index] = true; } index = 42342; while (index <= 42357) : (index += 1) { instance.array[index] = true; } index = 42368; while (index <= 42369) : (index += 1) { instance.array[index] = true; } instance.array[42436] = true; index = 42486; while (index <= 42555) : (index += 1) { instance.array[index] = true; } instance.array[42725] = true; instance.array[42829] = true; index = 42833; while (index <= 42839) : (index += 1) { instance.array[index] = true; } index = 42841; while (index <= 42843) : (index += 1) { instance.array[index] = true; } index = 42845; while (index <= 42848) : (index += 1) { instance.array[index] = true; } index = 42850; while (index <= 42872) : (index += 1) { instance.array[index] = true; } index = 42902; while (index <= 42953) : (index += 1) { instance.array[index] = true; } index = 42968; while (index <= 43017) : (index += 1) { instance.array[index] = true; } index = 43080; while (index <= 43085) : (index += 1) { instance.array[index] = true; } instance.array[43089] = true; index = 43091; while (index <= 43092) : (index += 1) { instance.array[index] = true; } index = 43104; while (index <= 43131) : (index += 1) { instance.array[index] = true; } index = 43142; while (index <= 43164) : (index += 1) { instance.array[index] = true; } index = 43190; while (index <= 43218) : (index += 1) { instance.array[index] = true; } index = 43226; while (index <= 43272) : (index += 1) { instance.array[index] = true; } index = 43318; while (index <= 43322) : (index += 1) { instance.array[index] = true; } index = 43325; while (index <= 43333) : (index += 1) { instance.array[index] = true; } index = 43344; while (index <= 43348) : (index += 1) { instance.array[index] = true; } index = 43350; while (index <= 43390) : (index += 1) { instance.array[index] = true; } index = 43414; while (index <= 43416) : (index += 1) { instance.array[index] = true; } index = 43418; while (index <= 43425) : (index += 1) { instance.array[index] = true; } index = 43446; while (index <= 43461) : (index += 1) { instance.array[index] = true; } index = 43463; while (index <= 43468) : (index += 1) { instance.array[index] = true; } instance.array[43472] = true; index = 43476; while (index <= 43525) : (index += 1) { instance.array[index] = true; } instance.array[43527] = true; index = 43531; while (index <= 43532) : (index += 1) { instance.array[index] = true; } index = 43535; while (index <= 43539) : (index += 1) { instance.array[index] = true; } instance.array[43542] = true; instance.array[43544] = true; index = 43569; while (index <= 43570) : (index += 1) { instance.array[index] = true; } index = 43574; while (index <= 43584) : (index += 1) { instance.array[index] = true; } instance.array[43592] = true; index = 43607; while (index <= 43612) : (index += 1) { instance.array[index] = true; } index = 43615; while (index <= 43620) : (index += 1) { instance.array[index] = true; } index = 43623; while (index <= 43628) : (index += 1) { instance.array[index] = true; } index = 43638; while (index <= 43644) : (index += 1) { instance.array[index] = true; } index = 43646; while (index <= 43652) : (index += 1) { instance.array[index] = true; } index = 43798; while (index <= 43832) : (index += 1) { instance.array[index] = true; } index = 43862; while (index <= 55033) : (index += 1) { instance.array[index] = true; } index = 55046; while (index <= 55068) : (index += 1) { instance.array[index] = true; } index = 55073; while (index <= 55121) : (index += 1) { instance.array[index] = true; } index = 63574; while (index <= 63939) : (index += 1) { instance.array[index] = true; } index = 63942; while (index <= 64047) : (index += 1) { instance.array[index] = true; } instance.array[64115] = true; index = 64117; while (index <= 64126) : (index += 1) { instance.array[index] = true; } index = 64128; while (index <= 64140) : (index += 1) { instance.array[index] = true; } index = 64142; while (index <= 64146) : (index += 1) { instance.array[index] = true; } instance.array[64148] = true; index = 64150; while (index <= 64151) : (index += 1) { instance.array[index] = true; } index = 64153; while (index <= 64154) : (index += 1) { instance.array[index] = true; } index = 64156; while (index <= 64263) : (index += 1) { instance.array[index] = true; } index = 64297; while (index <= 64659) : (index += 1) { instance.array[index] = true; } index = 64678; while (index <= 64741) : (index += 1) { instance.array[index] = true; } index = 64744; while (index <= 64797) : (index += 1) { instance.array[index] = true; } index = 64838; while (index <= 64849) : (index += 1) { instance.array[index] = true; } index = 64966; while (index <= 64970) : (index += 1) { instance.array[index] = true; } index = 64972; while (index <= 65106) : (index += 1) { instance.array[index] = true; } index = 65212; while (index <= 65221) : (index += 1) { instance.array[index] = true; } index = 65223; while (index <= 65267) : (index += 1) { instance.array[index] = true; } index = 65270; while (index <= 65300) : (index += 1) { instance.array[index] = true; } index = 65304; while (index <= 65309) : (index += 1) { instance.array[index] = true; } index = 65312; while (index <= 65317) : (index += 1) { instance.array[index] = true; } index = 65320; while (index <= 65325) : (index += 1) { instance.array[index] = true; } index = 65328; while (index <= 65330) : (index += 1) { instance.array[index] = true; } index = 65366; while (index <= 65377) : (index += 1) { instance.array[index] = true; } index = 65379; while (index <= 65404) : (index += 1) { instance.array[index] = true; } index = 65406; while (index <= 65424) : (index += 1) { instance.array[index] = true; } index = 65426; while (index <= 65427) : (index += 1) { instance.array[index] = true; } index = 65429; while (index <= 65443) : (index += 1) { instance.array[index] = true; } index = 65446; while (index <= 65459) : (index += 1) { instance.array[index] = true; } index = 65494; while (index <= 65616) : (index += 1) { instance.array[index] = true; } index = 66006; while (index <= 66034) : (index += 1) { instance.array[index] = true; } index = 66038; while (index <= 66086) : (index += 1) { instance.array[index] = true; } index = 66134; while (index <= 66165) : (index += 1) { instance.array[index] = true; } index = 66179; while (index <= 66198) : (index += 1) { instance.array[index] = true; } index = 66200; while (index <= 66207) : (index += 1) { instance.array[index] = true; } index = 66214; while (index <= 66251) : (index += 1) { instance.array[index] = true; } index = 66262; while (index <= 66291) : (index += 1) { instance.array[index] = true; } index = 66294; while (index <= 66329) : (index += 1) { instance.array[index] = true; } index = 66334; while (index <= 66341) : (index += 1) { instance.array[index] = true; } index = 66470; while (index <= 66547) : (index += 1) { instance.array[index] = true; } index = 66646; while (index <= 66685) : (index += 1) { instance.array[index] = true; } index = 66694; while (index <= 66745) : (index += 1) { instance.array[index] = true; } index = 66902; while (index <= 67212) : (index += 1) { instance.array[index] = true; } index = 67222; while (index <= 67243) : (index += 1) { instance.array[index] = true; } index = 67254; while (index <= 67261) : (index += 1) { instance.array[index] = true; } index = 67414; while (index <= 67419) : (index += 1) { instance.array[index] = true; } instance.array[67422] = true; index = 67424; while (index <= 67467) : (index += 1) { instance.array[index] = true; } index = 67469; while (index <= 67470) : (index += 1) { instance.array[index] = true; } instance.array[67474] = true; index = 67477; while (index <= 67499) : (index += 1) { instance.array[index] = true; } index = 67510; while (index <= 67532) : (index += 1) { instance.array[index] = true; } index = 67542; while (index <= 67572) : (index += 1) { instance.array[index] = true; } index = 67638; while (index <= 67656) : (index += 1) { instance.array[index] = true; } index = 67658; while (index <= 67659) : (index += 1) { instance.array[index] = true; } index = 67670; while (index <= 67691) : (index += 1) { instance.array[index] = true; } index = 67702; while (index <= 67727) : (index += 1) { instance.array[index] = true; } index = 67798; while (index <= 67853) : (index += 1) { instance.array[index] = true; } index = 67860; while (index <= 67861) : (index += 1) { instance.array[index] = true; } instance.array[67926] = true; index = 67942; while (index <= 67945) : (index += 1) { instance.array[index] = true; } index = 67947; while (index <= 67949) : (index += 1) { instance.array[index] = true; } index = 67951; while (index <= 67979) : (index += 1) { instance.array[index] = true; } index = 68022; while (index <= 68050) : (index += 1) { instance.array[index] = true; } index = 68054; while (index <= 68082) : (index += 1) { instance.array[index] = true; } index = 68118; while (index <= 68125) : (index += 1) { instance.array[index] = true; } index = 68127; while (index <= 68154) : (index += 1) { instance.array[index] = true; } index = 68182; while (index <= 68235) : (index += 1) { instance.array[index] = true; } index = 68246; while (index <= 68267) : (index += 1) { instance.array[index] = true; } index = 68278; while (index <= 68296) : (index += 1) { instance.array[index] = true; } index = 68310; while (index <= 68327) : (index += 1) { instance.array[index] = true; } index = 68438; while (index <= 68510) : (index += 1) { instance.array[index] = true; } index = 68694; while (index <= 68729) : (index += 1) { instance.array[index] = true; } index = 69078; while (index <= 69119) : (index += 1) { instance.array[index] = true; } index = 69126; while (index <= 69127) : (index += 1) { instance.array[index] = true; } index = 69206; while (index <= 69234) : (index += 1) { instance.array[index] = true; } instance.array[69245] = true; index = 69254; while (index <= 69275) : (index += 1) { instance.array[index] = true; } index = 69382; while (index <= 69402) : (index += 1) { instance.array[index] = true; } index = 69430; while (index <= 69452) : (index += 1) { instance.array[index] = true; } index = 69465; while (index <= 69517) : (index += 1) { instance.array[index] = true; } index = 69593; while (index <= 69637) : (index += 1) { instance.array[index] = true; } index = 69670; while (index <= 69694) : (index += 1) { instance.array[index] = true; } index = 69721; while (index <= 69756) : (index += 1) { instance.array[index] = true; } instance.array[69786] = true; instance.array[69789] = true; index = 69798; while (index <= 69832) : (index += 1) { instance.array[index] = true; } instance.array[69836] = true; index = 69849; while (index <= 69896) : (index += 1) { instance.array[index] = true; } index = 69911; while (index <= 69914) : (index += 1) { instance.array[index] = true; } instance.array[69936] = true; instance.array[69938] = true; index = 69974; while (index <= 69991) : (index += 1) { instance.array[index] = true; } index = 69993; while (index <= 70017) : (index += 1) { instance.array[index] = true; } index = 70102; while (index <= 70108) : (index += 1) { instance.array[index] = true; } instance.array[70110] = true; index = 70112; while (index <= 70115) : (index += 1) { instance.array[index] = true; } index = 70117; while (index <= 70131) : (index += 1) { instance.array[index] = true; } index = 70133; while (index <= 70142) : (index += 1) { instance.array[index] = true; } index = 70150; while (index <= 70196) : (index += 1) { instance.array[index] = true; } index = 70235; while (index <= 70242) : (index += 1) { instance.array[index] = true; } index = 70245; while (index <= 70246) : (index += 1) { instance.array[index] = true; } index = 70249; while (index <= 70270) : (index += 1) { instance.array[index] = true; } index = 70272; while (index <= 70278) : (index += 1) { instance.array[index] = true; } index = 70280; while (index <= 70281) : (index += 1) { instance.array[index] = true; } index = 70283; while (index <= 70287) : (index += 1) { instance.array[index] = true; } instance.array[70291] = true; instance.array[70310] = true; index = 70323; while (index <= 70327) : (index += 1) { instance.array[index] = true; } index = 70486; while (index <= 70538) : (index += 1) { instance.array[index] = true; } index = 70557; while (index <= 70560) : (index += 1) { instance.array[index] = true; } index = 70581; while (index <= 70583) : (index += 1) { instance.array[index] = true; } index = 70614; while (index <= 70661) : (index += 1) { instance.array[index] = true; } index = 70682; while (index <= 70683) : (index += 1) { instance.array[index] = true; } instance.array[70685] = true; index = 70870; while (index <= 70916) : (index += 1) { instance.array[index] = true; } index = 70958; while (index <= 70961) : (index += 1) { instance.array[index] = true; } index = 70998; while (index <= 71045) : (index += 1) { instance.array[index] = true; } instance.array[71066] = true; index = 71126; while (index <= 71168) : (index += 1) { instance.array[index] = true; } instance.array[71182] = true; index = 71254; while (index <= 71280) : (index += 1) { instance.array[index] = true; } index = 71510; while (index <= 71553) : (index += 1) { instance.array[index] = true; } index = 71765; while (index <= 71772) : (index += 1) { instance.array[index] = true; } instance.array[71775] = true; index = 71778; while (index <= 71785) : (index += 1) { instance.array[index] = true; } index = 71787; while (index <= 71788) : (index += 1) { instance.array[index] = true; } index = 71790; while (index <= 71813) : (index += 1) { instance.array[index] = true; } instance.array[71829] = true; instance.array[71831] = true; index = 71926; while (index <= 71933) : (index += 1) { instance.array[index] = true; } index = 71936; while (index <= 71974) : (index += 1) { instance.array[index] = true; } instance.array[71991] = true; instance.array[71993] = true; instance.array[72022] = true; index = 72033; while (index <= 72072) : (index += 1) { instance.array[index] = true; } instance.array[72080] = true; instance.array[72102] = true; index = 72114; while (index <= 72159) : (index += 1) { instance.array[index] = true; } instance.array[72179] = true; index = 72214; while (index <= 72270) : (index += 1) { instance.array[index] = true; } index = 72534; while (index <= 72542) : (index += 1) { instance.array[index] = true; } index = 72544; while (index <= 72580) : (index += 1) { instance.array[index] = true; } instance.array[72598] = true; index = 72648; while (index <= 72677) : (index += 1) { instance.array[index] = true; } index = 72790; while (index <= 72796) : (index += 1) { instance.array[index] = true; } index = 72798; while (index <= 72799) : (index += 1) { instance.array[index] = true; } index = 72801; while (index <= 72838) : (index += 1) { instance.array[index] = true; } instance.array[72860] = true; index = 72886; while (index <= 72891) : (index += 1) { instance.array[index] = true; } index = 72893; while (index <= 72894) : (index += 1) { instance.array[index] = true; } index = 72896; while (index <= 72927) : (index += 1) { instance.array[index] = true; } instance.array[72942] = true; index = 73270; while (index <= 73288) : (index += 1) { instance.array[index] = true; } instance.array[73478] = true; index = 73558; while (index <= 74479) : (index += 1) { instance.array[index] = true; } index = 74710; while (index <= 74905) : (index += 1) { instance.array[index] = true; } index = 77654; while (index <= 78724) : (index += 1) { instance.array[index] = true; } index = 82774; while (index <= 83356) : (index += 1) { instance.array[index] = true; } index = 91990; while (index <= 92558) : (index += 1) { instance.array[index] = true; } index = 92566; while (index <= 92596) : (index += 1) { instance.array[index] = true; } index = 92710; while (index <= 92739) : (index += 1) { instance.array[index] = true; } index = 92758; while (index <= 92805) : (index += 1) { instance.array[index] = true; } index = 92857; while (index <= 92877) : (index += 1) { instance.array[index] = true; } index = 92883; while (index <= 92901) : (index += 1) { instance.array[index] = true; } index = 93782; while (index <= 93856) : (index += 1) { instance.array[index] = true; } instance.array[93862] = true; index = 94038; while (index <= 100173) : (index += 1) { instance.array[index] = true; } index = 100182; while (index <= 101419) : (index += 1) { instance.array[index] = true; } index = 101462; while (index <= 101470) : (index += 1) { instance.array[index] = true; } index = 110422; while (index <= 110708) : (index += 1) { instance.array[index] = true; } index = 110758; while (index <= 110760) : (index += 1) { instance.array[index] = true; } index = 110778; while (index <= 110781) : (index += 1) { instance.array[index] = true; } index = 110790; while (index <= 111185) : (index += 1) { instance.array[index] = true; } index = 113494; while (index <= 113600) : (index += 1) { instance.array[index] = true; } index = 113606; while (index <= 113618) : (index += 1) { instance.array[index] = true; } index = 113622; while (index <= 113630) : (index += 1) { instance.array[index] = true; } index = 113638; while (index <= 113647) : (index += 1) { instance.array[index] = true; } index = 122966; while (index <= 123010) : (index += 1) { instance.array[index] = true; } instance.array[123044] = true; index = 123414; while (index <= 123457) : (index += 1) { instance.array[index] = true; } index = 124758; while (index <= 124954) : (index += 1) { instance.array[index] = true; } index = 126294; while (index <= 126297) : (index += 1) { instance.array[index] = true; } index = 126299; while (index <= 126325) : (index += 1) { instance.array[index] = true; } index = 126327; while (index <= 126328) : (index += 1) { instance.array[index] = true; } instance.array[126330] = true; instance.array[126333] = true; index = 126335; while (index <= 126344) : (index += 1) { instance.array[index] = true; } index = 126346; while (index <= 126349) : (index += 1) { instance.array[index] = true; } instance.array[126351] = true; instance.array[126353] = true; instance.array[126360] = true; instance.array[126365] = true; instance.array[126367] = true; instance.array[126369] = true; index = 126371; while (index <= 126373) : (index += 1) { instance.array[index] = true; } index = 126375; while (index <= 126376) : (index += 1) { instance.array[index] = true; } instance.array[126378] = true; instance.array[126381] = true; instance.array[126383] = true; instance.array[126385] = true; instance.array[126387] = true; instance.array[126389] = true; index = 126391; while (index <= 126392) : (index += 1) { instance.array[index] = true; } instance.array[126394] = true; index = 126397; while (index <= 126400) : (index += 1) { instance.array[index] = true; } index = 126402; while (index <= 126408) : (index += 1) { instance.array[index] = true; } index = 126410; while (index <= 126413) : (index += 1) { instance.array[index] = true; } index = 126415; while (index <= 126418) : (index += 1) { instance.array[index] = true; } instance.array[126420] = true; index = 126422; while (index <= 126431) : (index += 1) { instance.array[index] = true; } index = 126433; while (index <= 126449) : (index += 1) { instance.array[index] = true; } index = 126455; while (index <= 126457) : (index += 1) { instance.array[index] = true; } index = 126459; while (index <= 126463) : (index += 1) { instance.array[index] = true; } index = 126465; while (index <= 126481) : (index += 1) { instance.array[index] = true; } index = 130902; while (index <= 173619) : (index += 1) { instance.array[index] = true; } index = 173654; while (index <= 177802) : (index += 1) { instance.array[index] = true; } index = 177814; while (index <= 178035) : (index += 1) { instance.array[index] = true; } index = 178038; while (index <= 183799) : (index += 1) { instance.array[index] = true; } index = 183814; while (index <= 191286) : (index += 1) { instance.array[index] = true; } index = 194390; while (index <= 194931) : (index += 1) { instance.array[index] = true; } index = 196438; while (index <= 201376) : (index += 1) { instance.array[index] = true; } // Placeholder: 0. Struct name, 1. Code point kind return instance; } pub fn deinit(self: *OtherLetter) void { self.allocator.free(self.array); } // isOtherLetter checks if cp is of the kind Other_Letter. pub fn isOtherLetter(self: OtherLetter, cp: u21) bool { if (cp < self.lo or cp > self.hi) return false; const index = cp - self.lo; return if (index >= self.array.len) false else self.array[index]; }
src/components/autogen/DerivedGeneralCategory/OtherLetter.zig
const Package = @This(); const std = @import("std"); const fs = std.fs; const mem = std.mem; const Allocator = mem.Allocator; const assert = std.debug.assert; const Compilation = @import("Compilation.zig"); const Module = @import("Module.zig"); pub const Table = std.StringHashMapUnmanaged(*Package); root_src_directory: Compilation.Directory, /// Relative to `root_src_directory`. May contain path separators. root_src_path: []const u8, table: Table = .{}, parent: ?*Package = null, /// Whether to free `root_src_directory` on `destroy`. root_src_directory_owned: bool = false, /// Allocate a Package. No references to the slices passed are kept. pub fn create( gpa: *Allocator, /// Null indicates the current working directory root_src_dir_path: ?[]const u8, /// Relative to root_src_dir_path root_src_path: []const u8, ) !*Package { const ptr = try gpa.create(Package); errdefer gpa.destroy(ptr); const owned_dir_path = if (root_src_dir_path) |p| try gpa.dupe(u8, p) else null; errdefer if (owned_dir_path) |p| gpa.free(p); const owned_src_path = try gpa.dupe(u8, root_src_path); errdefer gpa.free(owned_src_path); ptr.* = .{ .root_src_directory = .{ .path = owned_dir_path, .handle = if (owned_dir_path) |p| try fs.cwd().openDir(p, .{}) else fs.cwd(), }, .root_src_path = owned_src_path, .root_src_directory_owned = true, }; return ptr; } pub fn createWithDir( gpa: *Allocator, directory: Compilation.Directory, /// Relative to `directory`. If null, means `directory` is the root src dir /// and is owned externally. root_src_dir_path: ?[]const u8, /// Relative to root_src_dir_path root_src_path: []const u8, ) !*Package { const ptr = try gpa.create(Package); errdefer gpa.destroy(ptr); const owned_src_path = try gpa.dupe(u8, root_src_path); errdefer gpa.free(owned_src_path); if (root_src_dir_path) |p| { const owned_dir_path = try directory.join(gpa, &[1][]const u8{p}); errdefer gpa.free(owned_dir_path); ptr.* = .{ .root_src_directory = .{ .path = owned_dir_path, .handle = try directory.handle.openDir(p, .{}), }, .root_src_directory_owned = true, .root_src_path = owned_src_path, }; } else { ptr.* = .{ .root_src_directory = directory, .root_src_directory_owned = false, .root_src_path = owned_src_path, }; } return ptr; } /// Free all memory associated with this package. It does not destroy any packages /// inside its table; the caller is responsible for calling destroy() on them. pub fn destroy(pkg: *Package, gpa: *Allocator) void { gpa.free(pkg.root_src_path); if (pkg.root_src_directory_owned) { // If root_src_directory.path is null then the handle is the cwd() // which shouldn't be closed. if (pkg.root_src_directory.path) |p| { gpa.free(p); pkg.root_src_directory.handle.close(); } } pkg.deinitTable(gpa); gpa.destroy(pkg); } /// Only frees memory associated with the table. pub fn deinitTable(pkg: *Package, gpa: *Allocator) void { var it = pkg.table.keyIterator(); while (it.next()) |key| { gpa.free(key.*); } pkg.table.deinit(gpa); } pub fn add(pkg: *Package, gpa: *Allocator, name: []const u8, package: *Package) !void { try pkg.table.ensureUnusedCapacity(gpa, 1); const name_dupe = try gpa.dupe(u8, name); pkg.table.putAssumeCapacityNoClobber(name_dupe, package); } pub fn addAndAdopt(parent: *Package, gpa: *Allocator, name: []const u8, child: *Package) !void { assert(child.parent == null); // make up your mind, who is the parent?? child.parent = parent; return parent.add(gpa, name, child); }
src/Package.zig