From 0b38e0d898649cff46b98dc6f230efd79e28a793 Mon Sep 17 00:00:00 2001 From: Dave Mason Date: Tue, 12 Dec 2023 12:44:14 -0500 Subject: [PATCH 01/10] var->const and internal trait.zig to compile on latest zig 0.12.0-dev.1808+69195d0cd --- android/build/auto-detect.zig | 2 +- build.zig | 2 +- src/backends/android/backend.zig | 8 ++-- src/backends/gtk/backend.zig | 6 +-- src/backends/macos/backend.zig | 5 ++- src/backends/macos/objc.zig | 7 +-- src/backends/win32/backend.zig | 6 +-- src/components/Alignment.zig | 2 +- src/containers.zig | 2 +- src/data.zig | 23 +++++----- src/dev_tools.zig | 4 +- src/fuzz.zig | 2 +- src/internal.zig | 11 ++--- src/list.zig | 4 +- src/listener.zig | 2 +- src/trait.zig | 36 +++++++++++++++ src/window.zig | 2 +- vendor/zigimg/src/Image.zig | 2 +- vendor/zigimg/src/color.zig | 2 +- vendor/zigimg/src/formats/bmp.zig | 2 +- vendor/zigimg/src/formats/jpeg.zig | 2 +- vendor/zigimg/src/formats/netpbm.zig | 14 +++--- vendor/zigimg/src/formats/pcx.zig | 4 +- vendor/zigimg/src/formats/png.zig | 4 +- .../zigimg/src/formats/png/InfoProcessor.zig | 44 +++++++++---------- vendor/zigimg/src/formats/png/reader.zig | 12 ++--- vendor/zigimg/src/formats/qoi.zig | 2 +- vendor/zigimg/src/octree_quantizer.zig | 2 +- vendor/zigimg/tests/formats/bmp_test.zig | 2 +- vendor/zigimg/tests/formats/png_test.zig | 14 +++--- vendor/zigimg/tests/formats/qoi_test.zig | 4 +- vendor/zigimg/tests/image_test.zig | 4 +- vendor/zigimg/tests/octree_quantizer_test.zig | 10 ++--- 33 files changed, 144 insertions(+), 104 deletions(-) create mode 100644 src/trait.zig diff --git a/android/build/auto-detect.zig b/android/build/auto-detect.zig index 30dd9c9f..4772992b 100644 --- a/android/build/auto-detect.zig +++ b/android/build/auto-detect.zig @@ -155,7 +155,7 @@ pub fn findUserConfig(b: *Builder, versions: Sdk.ToolchainVersions) !UserConfig }; // Get the android studio registry entry - var android_studio_key: HKEY = for ([_]HKEY{ HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE }) |root_key| { + const android_studio_key: HKEY = for ([_]HKEY{ HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE }) |root_key| { var software: HKEY = null; if (reg.RegOpenKeyA(root_key, "software", &software) == ERROR_SUCCESS) { defer _ = reg.RegCloseKey(software); diff --git a/build.zig b/build.zig index 88a60cd0..0f769a94 100644 --- a/build.zig +++ b/build.zig @@ -7,7 +7,7 @@ pub fn build(b: *std.Build) !void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); - var examplesDir = try std.fs.cwd().openIterableDir("examples", .{}); + var examplesDir = try std.fs.cwd().openDir("examples", .{}); defer examplesDir.close(); const broken = switch (target.getOsTag()) { diff --git a/src/backends/android/backend.zig b/src/backends/android/backend.zig index 690a6714..cf00c917 100644 --- a/src/backends/android/backend.zig +++ b/src/backends/android/backend.zig @@ -129,7 +129,7 @@ pub fn Events(comptime T: type) type { pub fn setupEvents(widget: PeerType) BackendError!void { const jni = theApp.getJni(); - var data = try lib.internal.lasting_allocator.create(EventUserData); + const data = try lib.internal.lasting_allocator.create(EventUserData); data.* = EventUserData{ .peer = widget }; // ensure that it uses default values // Wrap the memory address in a Long object @@ -751,7 +751,7 @@ pub const backendExport = struct { self.pipe = try std.os.pipe(); android.ALooper_acquire(self.uiThreadLooper); - var native_activity = android.NativeActivity.init(self.activity); + const native_activity = android.NativeActivity.init(self.activity); self.uiJni = native_activity.jni; const jni = native_activity.jni; @@ -836,7 +836,7 @@ pub const backendExport = struct { } pub fn getJni(self: *AndroidApp) *android.JNI { - var native_activity = android.NativeActivity.get(self.activity); + const native_activity = android.NativeActivity.get(self.activity); return native_activity.jni; } @@ -869,7 +869,7 @@ pub const backendExport = struct { } fn mainLoop(self: *AndroidApp) !void { - var native_activity = android.NativeActivity.init(self.activity); + const native_activity = android.NativeActivity.init(self.activity); self.mainJni = native_activity.jni; try self.runOnUiThread(setAppContentView, .{self}); diff --git a/src/backends/gtk/backend.zig b/src/backends/gtk/backend.zig index da11022b..852cad04 100644 --- a/src/backends/gtk/backend.zig +++ b/src/backends/gtk/backend.zig @@ -281,7 +281,7 @@ pub fn Events(comptime T: type) type { _ = c.g_signal_connect_data(event_controller_legacy, "event", @as(c.GCallback, @ptrCast(>kButtonPress)), null, null, c.G_CONNECT_AFTER); c.gtk_widget_add_controller(widget, event_controller_legacy); - var data = try lib.internal.lasting_allocator.create(EventUserData); + const data = try lib.internal.lasting_allocator.create(EventUserData); data.* = EventUserData{ .peer = widget }; // ensure that it uses default values c.g_object_set_data(@as(*c.GObject, @ptrCast(widget)), "eventUserData", data); _ = c.g_object_ref(@as(*c.GObject, @ptrCast(widget))); @@ -1242,7 +1242,7 @@ pub const NavigationSidebar = struct { pub fn create() BackendError!NavigationSidebar { const listBox = c.gtk_list_box_new(); - var context: *c.GtkStyleContext = c.gtk_widget_get_style_context(listBox); + const context: *c.GtkStyleContext = c.gtk_widget_get_style_context(listBox); c.gtk_style_context_add_class(context, "navigation-sidebar"); // A custom component is used to bypass GTK's minimum size mechanism @@ -1268,7 +1268,7 @@ pub const NavigationSidebar = struct { const label_gtk = c.gtk_label_new(label); c.gtk_box_append(@ptrCast(box), label_gtk); - var context: *c.GtkStyleContext = c.gtk_widget_get_style_context(box); + const context: *c.GtkStyleContext = c.gtk_widget_get_style_context(box); c.gtk_style_context_add_class(context, "activatable"); c.gtk_style_context_add_class(context, "row"); } diff --git a/src/backends/macos/backend.zig b/src/backends/macos/backend.zig index 6d616edd..53cf4b1d 100644 --- a/src/backends/macos/backend.zig +++ b/src/backends/macos/backend.zig @@ -3,6 +3,7 @@ const shared = @import("../shared.zig"); const lib = @import("../../main.zig"); const objc = @import("objc.zig"); const AppKit = @import("AppKit.zig"); +const trait = @import("../../trait.zig"); const EventFunctions = shared.EventFunctions(@This()); const EventType = shared.BackendEventType; @@ -12,7 +13,7 @@ const MouseButton = shared.MouseButton; // pub const PeerType = *opaque {}; pub const PeerType = objc.id; -var activeWindows = std.atomic.Atomic(usize).init(0); +var activeWindows = std.atomic.Value(usize).init(0); var hasInit: bool = false; pub fn init() BackendError!void { @@ -54,7 +55,7 @@ pub fn Events(comptime T: type) type { pub fn setUserData(self: *T, data: anytype) void { comptime { - if (!std.meta.trait.isSingleItemPtr(@TypeOf(data))) { + if (!trait.isSingleItemPtr(@TypeOf(data))) { @compileError(std.fmt.comptimePrint("Expected single item pointer, got {s}", .{@typeName(@TypeOf(data))})); } } diff --git a/src/backends/macos/objc.zig b/src/backends/macos/objc.zig index 1865bcea..63a8d659 100644 --- a/src/backends/macos/objc.zig +++ b/src/backends/macos/objc.zig @@ -1,6 +1,7 @@ // Courtesy of https://github.com/hazeycode/zig-objcrt const std = @import("std"); const c = @import("c.zig"); +const trait = @import("../../trait.zig"); /// Sends a message to an id or Class and returns the return value of the called method pub fn msgSend(comptime ReturnType: type, target: anytype, selector: SEL, args: anytype) ReturnType { @@ -9,7 +10,7 @@ pub fn msgSend(comptime ReturnType: type, target: anytype, selector: SEL, args: const args_meta = @typeInfo(@TypeOf(args)).Struct.fields; - if (comptime !std.meta.trait.isContainer(ReturnType)) { + if (comptime !trait.isContainer(ReturnType)) { const FnType = blk: { { // TODO(hazeycode): replace this hack with the more generalised code above once it doens't crash the compiler @@ -25,7 +26,7 @@ pub fn msgSend(comptime ReturnType: type, target: anytype, selector: SEL, args: } }; // NOTE: func is a var because making it const causes a compile error which I believe is a compiler bug - var func = @as(FnType, @ptrCast(&c.objc_msgSend)); + const func = @as(FnType, @ptrCast(&c.objc_msgSend)); return @call(.auto, func, .{ target, selector } ++ args); } else { const FnType = blk: { @@ -40,7 +41,7 @@ pub fn msgSend(comptime ReturnType: type, target: anytype, selector: SEL, args: } }; // NOTE: func is a var because making it const causes a compile error which I believe is a compiler bug - var func = @as(FnType, @ptrCast(&c.objc_msgSend_stret)); + const func = @as(FnType, @ptrCast(&c.objc_msgSend_stret)); var stret: ReturnType = undefined; _ = @call(.auto, func, .{ &stret, target, selector } ++ args); return stret; diff --git a/src/backends/win32/backend.zig b/src/backends/win32/backend.zig index 76388dd5..9d162fc5 100644 --- a/src/backends/win32/backend.zig +++ b/src/backends/win32/backend.zig @@ -516,7 +516,7 @@ pub fn Events(comptime T: type) type { _ = win32.GetClientRect(hwnd, &rc); var render_target: ?*win32.ID2D1HwndRenderTarget = null; - var hresult = d2dFactory.ID2D1Factory_CreateHwndRenderTarget( + const hresult = d2dFactory.ID2D1Factory_CreateHwndRenderTarget( &win32.D2D1_RENDER_TARGET_PROPERTIES{ .type = win32.D2D1_RENDER_TARGET_TYPE_DEFAULT, .pixelFormat = .{ @@ -576,7 +576,7 @@ pub fn Events(comptime T: type) type { } pub fn setupEvents(peer: HWND) !void { - var data = try lib.internal.lasting_allocator.create(EventUserData); + const data = try lib.internal.lasting_allocator.create(EventUserData); data.* = EventUserData{}; // ensure that it uses default values _ = win32Backend.setWindowLongPtr(peer, win32.GWL_USERDATA, @intFromPtr(data)); } @@ -1287,7 +1287,7 @@ pub const TabContainer = struct { if (self.shownPeer) |previousPeer| { _ = win32.ShowWindow(previousPeer, win32.SW_HIDE); } - var peer = self.peerList.items[index]; + const peer = self.peerList.items[index]; _ = win32.SetParent(peer, self.peer); _ = win32.ShowWindow(peer, win32.SW_SHOWDEFAULT); _ = win32.UpdateWindow(peer); diff --git a/src/components/Alignment.zig b/src/components/Alignment.zig index ee6dfa6c..8df9f00d 100644 --- a/src/components/Alignment.zig +++ b/src/components/Alignment.zig @@ -12,7 +12,7 @@ pub const Alignment = struct { widget_data: Alignment.WidgetData = .{}, child: Widget, - relayouting: std.atomic.Atomic(bool) = std.atomic.Atomic(bool).init(false), + relayouting: std.atomic.Value(bool) = std.atomic.Value(bool).init(false), x: Atom(f32) = Atom(f32).of(0.5), y: Atom(f32) = Atom(f32).of(0.5), diff --git a/src/containers.zig b/src/containers.zig index 002ccc37..e193419a 100644 --- a/src/containers.zig +++ b/src/containers.zig @@ -238,7 +238,7 @@ pub const Container = struct { widget_data: Container.WidgetData = .{}, childrens: std.ArrayList(Widget), expand: bool, - relayouting: std.atomic.Atomic(bool) = std.atomic.Atomic(bool).init(false), + relayouting: std.atomic.Value(bool) = std.atomic.Value(bool).init(false), layout: Layout, layoutConfig: [16]u8, diff --git a/src/data.zig b/src/data.zig index d3e2945a..206242f5 100644 --- a/src/data.zig +++ b/src/data.zig @@ -2,6 +2,7 @@ const std = @import("std"); const Container_Impl = @import("containers.zig").Container_Impl; const internal = @import("internal.zig"); const lasting_allocator = internal.lasting_allocator; +const trait = @import("trait.zig"); /// Linear interpolation between floats a and b with factor t. fn lerpFloat(a: anytype, b: @TypeOf(a), t: f64) @TypeOf(a) { @@ -13,9 +14,9 @@ fn lerpFloat(a: anytype, b: @TypeOf(a), t: f64) @TypeOf(a) { pub fn lerp(a: anytype, b: @TypeOf(a), t: f64) @TypeOf(a) { const T = @TypeOf(a); - if (comptime std.meta.trait.isNumber(T)) { + if (comptime trait.isNumber(T)) { const a_casted = blk: { - if (comptime std.meta.trait.isIntegral(T)) { + if (comptime trait.isIntegral(T)) { break :blk @as(f64, @floatFromInt(a)); } else { break :blk a; @@ -23,7 +24,7 @@ pub fn lerp(a: anytype, b: @TypeOf(a), t: f64) @TypeOf(a) { }; const b_casted = blk: { - if (comptime std.meta.trait.isIntegral(T)) { + if (comptime trait.isIntegral(T)) { break :blk @as(f64, @floatFromInt(b)); } else { break :blk b; @@ -31,12 +32,12 @@ pub fn lerp(a: anytype, b: @TypeOf(a), t: f64) @TypeOf(a) { }; const result = lerpFloat(a_casted, b_casted, t); - if (comptime std.meta.trait.isIntegral(T)) { + if (comptime trait.isIntegral(T)) { return @intFromFloat(@round(result)); } else { return result; } - } else if (comptime std.meta.trait.isContainer(T) and @hasDecl(T, "lerp")) { + } else if (comptime trait.isContainer(T) and @hasDecl(T, "lerp")) { return T.lerp(a, b, t); } else if (comptime std.meta.trait.is(.Optional)(T)) { if (a != null and b != null) { @@ -94,7 +95,7 @@ pub fn Animation(comptime T: type) type { } pub fn isAtom(comptime T: type) bool { - if (!comptime std.meta.trait.is(.Struct)(T)) + if (!comptime trait.is(.Struct)(T)) return false; return @hasDecl(T, "ValueType") and T == Atom(T.ValueType); } @@ -107,9 +108,9 @@ pub var _animatedAtomsLength = Atom(usize).of(0); pub var _animatedAtomsMutex = std.Thread.Mutex{}; fn isAnimableType(comptime T: type) bool { - if (std.meta.trait.isNumber(T) or (std.meta.trait.isContainer(T) and @hasDecl(T, "lerp"))) { + if (trait.isNumber(T) or (trait.isContainer(T) and @hasDecl(T, "lerp"))) { return true; - } else if (std.meta.trait.is(.Optional)(T)) { + } else if (trait.is(.Optional)(T)) { return isAnimableType(std.meta.Child(T)); } return false; @@ -136,7 +137,7 @@ pub fn Atom(comptime T: type) type { /// When A is set, it sets the lock to true and sets B. Since B is set, it will set A too. /// A notices that bindLock is already set to true, and thus returns. /// TODO: make the bind lock more general and just use it for any change, and explicit how this favors completeness instead of consistency (in case an onChange triggers set method manually) - bindLock: std.atomic.Atomic(bool) = std.atomic.Atomic(bool).init(false), + bindLock: std.atomic.Value(bool) = std.atomic.Value(bool).init(false), /// If dependOn has been called, this is a pointer to the callback function depend_on_callback: ?*const anyopaque = null, @@ -427,7 +428,7 @@ pub fn Atom(comptime T: type) type { // If the old value was false, it returns null, which is what we want. // Otherwise, it returns the old value, but since the only value other than false is true, // we're not interested in the result. - if (self.bindLock.compareAndSwap(false, true, .SeqCst, .SeqCst) == null) { + if (self.bindLock.cmpxchgStrong(false, true, .SeqCst, .SeqCst) == null) { defer self.bindLock.store(false, .SeqCst); { @@ -608,7 +609,7 @@ pub fn FormattedAtom(allocator: std.mem.Allocator, comptime fmt: []const u8, chi tuple[i] = child.get(); } - var str = std.fmt.allocPrint(ptr.wrapper.allocator.?, fmt, tuple) catch unreachable; + const str = std.fmt.allocPrint(ptr.wrapper.allocator.?, fmt, tuple) catch unreachable; ptr.wrapper.allocator.?.free(ptr.wrapper.get()); ptr.wrapper.set(str); } diff --git a/src/dev_tools.zig b/src/dev_tools.zig index d2f38249..3808fe92 100644 --- a/src/dev_tools.zig +++ b/src/dev_tools.zig @@ -77,7 +77,7 @@ fn readStructField(comptime T: type, reader: anytype) !T { return try reader.readIntBig(T); } else if (T == []const u8) { const length = try std.leb.readULEB128(u32, reader); - var bytes = try internal.lasting_allocator.alloc(u8, length); + const bytes = try internal.lasting_allocator.alloc(u8, length); try reader.readNoEof(bytes); return bytes; } @@ -141,7 +141,7 @@ fn connectionRunner(connection: std.net.StreamServer.Connection) !void { inline for (std.meta.fields(Request)) |request_field| { const RequestType = request_field.type; if (request_id == @field(RequestId, request_field.name)) { - var request = try readStruct(RequestType, reader); + const request = try readStruct(RequestType, reader); switch (request_id) { RequestId.get_windows_num => { try writeResponse(writer, .{ diff --git a/src/fuzz.zig b/src/fuzz.zig index 45722521..83066e70 100644 --- a/src/fuzz.zig +++ b/src/fuzz.zig @@ -197,7 +197,7 @@ const ColorContainer = struct { test "simple struct init" { var all = forAll(@import("color.zig").Color); while (all.next()) |color| { - var container = ColorContainer{ .color = color }; + const container = ColorContainer{ .color = color }; try std.testing.expectEqual(color, container.color); } } diff --git a/src/internal.zig b/src/internal.zig index 81dffb37..5954d900 100644 --- a/src/internal.zig +++ b/src/internal.zig @@ -11,6 +11,7 @@ const Atom = dataStructures.Atom; const Container = @import("containers.zig").Container; const Layout = @import("containers.zig").Layout; const MouseButton = @import("backends/shared.zig").MouseButton; +const trait = @import("trait.zig"); const link_libc = @import("builtin").link_libc; @@ -311,7 +312,7 @@ fn iterateFields(comptime config_fields: *[]const std.builtin.Type.StructField, .is_comptime = false, .alignment = @alignOf(FieldType.ValueType), }}; - } else if (comptime std.meta.trait.is(.Struct)(FieldType)) { + } else if (comptime trait.is(.Struct)(FieldType)) { iterateFields(config_fields, FieldType); } } @@ -348,7 +349,7 @@ fn iterateApplyFields(comptime T: type, target: anytype, config: GenerateConfigS /// If T is a pointer, return the type it points to, otherwise return T. /// Example: DereferencedType(*Button_Impl) = Button_Impl pub fn DereferencedType(comptime T: type) type { - return if (comptime std.meta.trait.isSingleItemPtr(T)) + return if (comptime trait.isSingleItemPtr(T)) std.meta.Child(T) else T; @@ -366,8 +367,8 @@ pub fn genericWidgetFrom(component: anytype) anyerror!Widget { // Unless it is already a pointer, we clone the component so that // it can be referenced by the Widget we're gonna create. - var cp = if (comptime std.meta.trait.isSingleItemPtr(ComponentType)) component else blk: { - var copy = try lasting_allocator.create(ComponentType); + var cp = if (comptime trait.isSingleItemPtr(ComponentType)) component else blk: { + const copy = try lasting_allocator.create(ComponentType); copy.* = component; break :blk copy; }; @@ -381,7 +382,7 @@ pub fn genericWidgetFrom(component: anytype) anyerror!Widget { .data = cp, .class = &Dereferenced.WidgetClass, .name = &cp.widget_data.atoms.name, - .allocator = if (comptime std.meta.trait.isSingleItemPtr(ComponentType)) null else lasting_allocator, + .allocator = if (comptime trait.isSingleItemPtr(ComponentType)) null else lasting_allocator, }; } diff --git a/src/list.zig b/src/list.zig index f74b0707..2aa5fa41 100644 --- a/src/list.zig +++ b/src/list.zig @@ -65,7 +65,7 @@ pub inline fn columnList(config: containers.GridConfig, model: anytype) anyerror } var row = try containers.column(config, .{}); const ModelType = @import("internal.zig").DereferencedType(@TypeOf(model)); // The type of the list model - var genericModel = GenericListModel{ + const genericModel = GenericListModel{ .size = &model.size, .userdata = model, .getComponent = struct { @@ -86,7 +86,7 @@ pub inline fn columnList(config: containers.GridConfig, model: anytype) anyerror } const widget = try @import("internal.zig").genericWidgetFrom(row); - var list = List.init(widget, genericModel); + const list = List.init(widget, genericModel); return list; } diff --git a/src/listener.zig b/src/listener.zig index 40754c2e..ce942440 100644 --- a/src/listener.zig +++ b/src/listener.zig @@ -55,7 +55,7 @@ pub const Listener = struct { }; pub fn init(config: Listener.Config) std.mem.Allocator.Error!*Listener { - var listener = try lasting_allocator.create(Listener); + const listener = try lasting_allocator.create(Listener); listener.* = .{ .listened = config.listened, .callback = config.callback, diff --git a/src/trait.zig b/src/trait.zig new file mode 100644 index 00000000..4ca852fd --- /dev/null +++ b/src/trait.zig @@ -0,0 +1,36 @@ +const std = @import("std"); + +pub usingnamespace if (@hasField(std.meta,"trait")) std.meta.trait else struct { + pub fn isNumber(comptime T: type) bool { + return switch (@typeInfo(T)) { + .Int, .Float, .ComptimeInt, .ComptimeFloat => true, + else => false, + }; + } + pub fn isContainer(comptime T: type) bool { + return switch (@typeInfo(T)) { + .Struct, .Union, .Enum, .Opaque => true, + else => false, + }; + } + pub fn is(comptime id: std.builtin.TypeId) fn (type) bool { + const Closure = struct { + pub fn trait(comptime T: type) bool { + return id == @typeInfo(T); + } + }; + return Closure.trait; + } + pub fn isSingleItemPtr(comptime T: type) bool { + if (comptime is(.Pointer)(T)) { + return @typeInfo(T).Pointer.size == .One; + } + return false; + } + pub fn isIntegral(comptime T: type) bool { + return switch (@typeInfo(T)) { + .Int, .ComptimeInt => true, + else => false, + }; + } +}; diff --git a/src/window.zig b/src/window.zig index 6b15b09f..6289e3af 100644 --- a/src/window.zig +++ b/src/window.zig @@ -61,7 +61,7 @@ pub const Window = struct { /// wrappedContainer can be an error union, a pointer to the container or the container itself. pub inline fn set(self: *Window, wrappedContainer: anytype) anyerror!void { - var container = + const container = if (comptime isErrorUnion(@TypeOf(wrappedContainer))) try wrappedContainer else diff --git a/vendor/zigimg/src/Image.zig b/vendor/zigimg/src/Image.zig index b4ba6a59..16242491 100644 --- a/vendor/zigimg/src/Image.zig +++ b/vendor/zigimg/src/Image.zig @@ -136,7 +136,7 @@ pub fn fromMemory(allocator: Allocator, buffer: []const u8) !Self { /// Create a pixel surface from scratch pub fn create(allocator: Allocator, width: usize, height: usize, pixel_format: PixelFormat) !Self { - var result = Self{ + const result = Self{ .allocator = allocator, .width = width, .height = height, diff --git a/vendor/zigimg/src/color.zig b/vendor/zigimg/src/color.zig index d48ed2d2..d4944f02 100644 --- a/vendor/zigimg/src/color.zig +++ b/vendor/zigimg/src/color.zig @@ -450,7 +450,7 @@ pub fn IndexedStorage(comptime T: type) type { const Self = @This(); pub fn init(allocator: Allocator, pixel_count: usize) !Self { - var res = Self{ + const res = Self{ .indices = try allocator.alloc(T, pixel_count), .palette = try allocator.alloc(Rgba32, PaletteSize), }; diff --git a/vendor/zigimg/src/formats/bmp.zig b/vendor/zigimg/src/formats/bmp.zig index 4da24866..7abe3aa4 100644 --- a/vendor/zigimg/src/formats/bmp.zig +++ b/vendor/zigimg/src/formats/bmp.zig @@ -234,7 +234,7 @@ pub const Bitmap = struct { // Read header size to figure out the header type, also TODO: Use PeekableStream when I understand how to use it const current_header_pos = try stream.getPos(); - var header_size = try reader.readIntLittle(u32); + const header_size = try reader.readIntLittle(u32); try stream.seekTo(current_header_pos); // Read info header diff --git a/vendor/zigimg/src/formats/jpeg.zig b/vendor/zigimg/src/formats/jpeg.zig index 4c81e7fe..f4677614 100644 --- a/vendor/zigimg/src/formats/jpeg.zig +++ b/vendor/zigimg/src/formats/jpeg.zig @@ -828,7 +828,7 @@ const Frame = struct { } fn renderToPixelsRgb(self: *Frame, pixels: []color.Rgb24) ImageReadError!void { - var width = self.frame_header.samples_per_row; + const width = self.frame_header.samples_per_row; var mcu_id: usize = 0; while (mcu_id < self.mcu_storage.len) : (mcu_id += 1) { const mcus_per_row = width / 8; diff --git a/vendor/zigimg/src/formats/netpbm.zig b/vendor/zigimg/src/formats/netpbm.zig index dda95966..67cc1444 100644 --- a/vendor/zigimg/src/formats/netpbm.zig +++ b/vendor/zigimg/src/formats/netpbm.zig @@ -87,7 +87,7 @@ fn isWhitespace(b: u8) bool { fn readNextByte(reader: Image.Stream.Reader) ImageReadError!u8 { while (true) { - var b = try reader.readByte(); + const b = try reader.readByte(); switch (b) { // Before the whitespace character that delimits the raster, any characters // from a "#" through the next carriage return or newline character, is a @@ -98,7 +98,7 @@ fn readNextByte(reader: Image.Stream.Reader) ImageReadError!u8 { '#' => { // eat up comment while (true) { - var c = try reader.readByte(); + const c = try reader.readByte(); switch (c) { '\r', '\n' => break, else => {}, @@ -115,7 +115,7 @@ fn readNextByte(reader: Image.Stream.Reader) ImageReadError!u8 { fn parseNumber(reader: Image.Stream.Reader, buffer: []u8) ImageReadError!usize { var input_length: usize = 0; while (true) { - var b = try readNextByte(reader); + const b = try readNextByte(reader); if (isWhitespace(b)) { if (input_length > 0) { return std.fmt.parseInt(usize, buffer[0..input_length], 10) catch return ImageReadError.InvalidData; @@ -150,7 +150,7 @@ fn loadAsciiBitmap(header: Header, data: []color.Grayscale1, reader: Image.Strea const data_end = header.width * header.height; while (data_index < data_end) { - var b = try reader.readByte(); + const b = try reader.readByte(); if (isWhitespace(b)) { continue; } @@ -222,9 +222,9 @@ fn loadAsciiRgbmap(header: Header, data: []color.Rgb24, reader: Image.Stream.Rea const data_end = header.width * header.height; while (data_index < data_end) : (data_index += 1) { - var r = try parseNumber(reader, read_buffer[0..]); - var g = try parseNumber(reader, read_buffer[0..]); - var b = try parseNumber(reader, read_buffer[0..]); + const r = try parseNumber(reader, read_buffer[0..]); + const g = try parseNumber(reader, read_buffer[0..]); + const b = try parseNumber(reader, read_buffer[0..]); data[data_index] = color.Rgb24{ .r = @as(u8, @truncate(255 * r / header.max_value)), diff --git a/vendor/zigimg/src/formats/pcx.zig b/vendor/zigimg/src/formats/pcx.zig index b1254657..86dcdf0c 100644 --- a/vendor/zigimg/src/formats/pcx.zig +++ b/vendor/zigimg/src/formats/pcx.zig @@ -56,7 +56,7 @@ const RLEDecoder = struct { fn readByte(self: *RLEDecoder) ImageReadError!u8 { if (self.current_run) |*run| { - var result = run.value; + const result = run.value; run.remaining -= 1; if (run.remaining == 0) { self.current_run = null; @@ -64,7 +64,7 @@ const RLEDecoder = struct { return result; } else { while (true) { - var byte = try self.reader.readByte(); + const byte = try self.reader.readByte(); if (byte == 0xC0) // skip over "zero length runs" continue; if ((byte & 0xC0) == 0xC0) { diff --git a/vendor/zigimg/src/formats/png.zig b/vendor/zigimg/src/formats/png.zig index a98f944f..987cf0d3 100644 --- a/vendor/zigimg/src/formats/png.zig +++ b/vendor/zigimg/src/formats/png.zig @@ -101,7 +101,7 @@ pub const PNG = struct { if (header.filter_method != .adaptive) return ImageWriteError.Unsupported; - var writer = write_stream.writer(); + const writer = write_stream.writer(); try writeSignature(writer); try writeHeader(writer, header); @@ -155,7 +155,7 @@ pub const PNG = struct { // Note: there may be more than 1 chunk // TODO: provide choice of how much it buffers (how much data per idat chunk) var chunks = chunk_writer.chunkWriter(writer, "IDAT"); - var chunk_wr = chunks.writer(); + const chunk_wr = chunks.writer(); var zlib: ZlibCompressor(@TypeOf(chunk_wr)) = undefined; try zlib.init(allocator, chunk_wr); diff --git a/vendor/zigimg/src/formats/png/InfoProcessor.zig b/vendor/zigimg/src/formats/png/InfoProcessor.zig index 1521d5bc..eb77384e 100644 --- a/vendor/zigimg/src/formats/png/InfoProcessor.zig +++ b/vendor/zigimg/src/formats/png/InfoProcessor.zig @@ -43,7 +43,7 @@ pub fn processor(self: *Self) ReaderProcessor { fn processChunk(self: *Self, data: *ChunkProcessData) Image.ReadError!PixelFormat { // This is critical chunk so it is already read and there is no need to read it here - var result_format = data.current_format; + const result_format = data.current_format; var reader = data.stream.reader(); var buffer: [1024]u8 = undefined; @@ -55,7 +55,7 @@ fn processChunk(self: *Self, data: *ChunkProcessData) Image.ReadError!PixelForma try data.stream.seekBy(data.chunk_length); self.writer.print("gAMA: Invalid Length {}\n", .{data.chunk_length}) catch return result_format; } else { - var gama = try reader.readIntBig(u32); + const gama = try reader.readIntBig(u32); self.writer.print("gAMA: {}\n", .{gama}) catch return result_format; } }, @@ -64,7 +64,7 @@ fn processChunk(self: *Self, data: *ChunkProcessData) Image.ReadError!PixelForma try data.stream.seekBy(data.chunk_length); self.writer.print("sBIT: Invalid length {}\n", .{data.chunk_length}) catch return result_format; } else { - var vals = buffer[0..data.chunk_length]; + const vals = buffer[0..data.chunk_length]; try reader.readNoEof(vals); self.writer.print("sBIT (significant bits): ", .{}) catch return result_format; switch (data.chunk_length) { @@ -77,12 +77,12 @@ fn processChunk(self: *Self, data: *ChunkProcessData) Image.ReadError!PixelForma } }, png.Chunks.tEXt.id => { - var to_read = if (data.chunk_length <= buffer.len) data.chunk_length else buffer.len; + const to_read = if (data.chunk_length <= buffer.len) data.chunk_length else buffer.len; var txt = buffer[0..to_read]; try reader.readNoEof(txt); if (data.chunk_length > buffer.len) try data.stream.seekBy(@as(i64, data.chunk_length) - buffer.len); self.writer.print("tEXt Length {s}:\n", .{std.fmt.fmtIntSizeBin(data.chunk_length)}) catch return result_format; - var strEnd = std.mem.indexOfScalar(u8, txt, 0).?; + const strEnd = std.mem.indexOfScalar(u8, txt, 0).?; self.writer.print(" Keyword: {s}\n", .{txt[0..strEnd]}) catch return result_format; txt = txt[strEnd + 1 ..]; self.writer.print(" Text: {s}\n", .{txt[0..]}) catch return result_format; @@ -92,7 +92,7 @@ fn processChunk(self: *Self, data: *ChunkProcessData) Image.ReadError!PixelForma var txt = buffer[0..to_read]; try reader.readNoEof(txt); self.writer.print("zTXt Length {s}:\n", .{std.fmt.fmtIntSizeBin(data.chunk_length)}) catch return result_format; - var strEnd = std.mem.indexOfScalar(u8, txt, 0).?; + const strEnd = std.mem.indexOfScalar(u8, txt, 0).?; self.writer.print(" Keyword: {s}\n", .{txt[0..strEnd]}) catch return result_format; if (txt[strEnd + 1] == 0) { self.writer.print(" Compression: Zlib Deflate\n", .{}) catch return result_format; @@ -111,7 +111,7 @@ fn processChunk(self: *Self, data: *ChunkProcessData) Image.ReadError!PixelForma } }, png.Chunks.iTXt.id => { - var to_read = if (data.chunk_length <= buffer.len) data.chunk_length else buffer.len; + const to_read = if (data.chunk_length <= buffer.len) data.chunk_length else buffer.len; var txt = buffer[0..to_read]; try reader.readNoEof(txt); if (data.chunk_length > buffer.len) try data.stream.seekBy(@as(i64, data.chunk_length) - buffer.len); @@ -159,8 +159,8 @@ fn processChunk(self: *Self, data: *ChunkProcessData) Image.ReadError!PixelForma self.writer.print("pHYs: Invalid Length {}\n", .{data.chunk_length}) catch return result_format; } else { self.writer.print("pHYs: ", .{}) catch return result_format; - var x = try reader.readIntBig(u32); - var y = try reader.readIntBig(u32); + const x = try reader.readIntBig(u32); + const y = try reader.readIntBig(u32); self.writer.print("{} x {}", .{ x, y }) catch return result_format; if ((try reader.readIntBig(u8)) == 1) { self.writer.print(" metres\n", .{}) catch return result_format; @@ -172,16 +172,16 @@ fn processChunk(self: *Self, data: *ChunkProcessData) Image.ReadError!PixelForma png.Chunks.tRNS.id => { self.writer.print("tRNS Length {s}: ", .{std.fmt.fmtIntSizeBin(data.chunk_length)}) catch return result_format; if (data.chunk_length == 2 and data.header.color_type != .indexed) { - var val = try reader.readIntBig(u16); + const val = try reader.readIntBig(u16); self.writer.print("{}\n", .{val}) catch return result_format; } else if (data.chunk_length == 6 and data.header.color_type != .indexed) { - var r = try reader.readIntBig(u16); - var g = try reader.readIntBig(u16); - var b = try reader.readIntBig(u16); + const r = try reader.readIntBig(u16); + const g = try reader.readIntBig(u16); + const b = try reader.readIntBig(u16); self.writer.print("RGB {}, {}, {}\n", .{ r, g, b }) catch return result_format; } else { const to_print = if (data.chunk_length > 20) 20 else data.chunk_length; - var vals = buffer[0..to_print]; + const vals = buffer[0..to_print]; try reader.readNoEof(vals); self.writer.print("{d}", .{vals}) catch return result_format; if (data.chunk_length > 20) { @@ -193,15 +193,15 @@ fn processChunk(self: *Self, data: *ChunkProcessData) Image.ReadError!PixelForma png.Chunks.bKGD.id => { self.writer.print("bKGD Length {s}: ", .{std.fmt.fmtIntSizeBin(data.chunk_length)}) catch return result_format; if (data.chunk_length == 1) { - var val = try reader.readIntBig(u8); + const val = try reader.readIntBig(u8); self.writer.print("Index {}\n", .{val}) catch return result_format; } else if (data.chunk_length == 2) { - var val = try reader.readIntBig(u16); + const val = try reader.readIntBig(u16); self.writer.print("{}\n", .{val}) catch return result_format; } else if (data.chunk_length == 6) { - var r = try reader.readIntBig(u16); - var g = try reader.readIntBig(u16); - var b = try reader.readIntBig(u16); + const r = try reader.readIntBig(u16); + const g = try reader.readIntBig(u16); + const b = try reader.readIntBig(u16); self.writer.print("RGB {}, {}, {}\n", .{ r, g, b }) catch return result_format; } else { self.writer.print("Invalid Length\n", .{}) catch return result_format; @@ -214,8 +214,8 @@ fn processChunk(self: *Self, data: *ChunkProcessData) Image.ReadError!PixelForma self.writer.print("tIME: Invalid Length {}: ", .{data.chunk_length}) catch return result_format; } else { self.writer.print("tIME: ", .{}) catch return result_format; - var year = try reader.readIntBig(u16); - var rest = buffer[0 .. data.chunk_length - 2]; + const year = try reader.readIntBig(u16); + const rest = buffer[0 .. data.chunk_length - 2]; try reader.readNoEof(rest); self.writer.print("{}-{}-{} {}:{}:{}\n", .{ year, rest[0], rest[1], rest[2], rest[3], rest[4] }) catch return result_format; } @@ -242,7 +242,7 @@ fn processChunk(self: *Self, data: *ChunkProcessData) Image.ReadError!PixelForma self.writer.print("sRGB: Invalid Length {}: ", .{data.chunk_length}) catch return result_format; } else { self.writer.print("sRGB: ", .{}) catch return result_format; - var srgb = try reader.readByte(); + const srgb = try reader.readByte(); switch (srgb) { 0 => self.writer.print("Perceptual\n", .{}) catch return result_format, 1 => self.writer.print("Relative colorimetric\n", .{}) catch return result_format, diff --git a/vendor/zigimg/src/formats/png/reader.zig b/vendor/zigimg/src/formats/png/reader.zig index 178b325a..ea85e20a 100644 --- a/vendor/zigimg/src/formats/png/reader.zig +++ b/vendor/zigimg/src/formats/png/reader.zig @@ -73,7 +73,7 @@ const IDatChunksReader = struct { fn fillBuffer(self: *Self, to_read: usize) Image.ReadError!usize { std.mem.copy(u8, self.buffer[0..self.data.len], self.data); - var new_start = self.data.len; + const new_start = self.data.len; var max = self.buffer.len; if (max - new_start > self.remaining_chunk_length) { max = new_start + self.remaining_chunk_length; @@ -246,7 +246,7 @@ pub fn loadWithHeader( return Image.ReadError.InvalidData; } palette = try options.temp_allocator.alloc(color.Rgb24, palette_entries); - var palette_bytes = mem.sliceAsBytes(palette); + const palette_bytes = mem.sliceAsBytes(palette); try reader.readNoEof(palette_bytes); const expected_crc = try reader.readIntBig(u32); @@ -282,7 +282,7 @@ fn readAllData( var result = try PixelStorage.init(allocator, dest_format, width * height); errdefer result.deinit(allocator); var idat_chunks_reader = IDatChunksReader.init(stream, options.processors, chunk_process_data); - var idat_reader: IDATReader = .{ .context = &idat_chunks_reader }; + const idat_reader: IDATReader = .{ .context = &idat_chunks_reader }; var decompress_stream = std.compress.zlib.decompressStream(options.temp_allocator, idat_reader) catch return Image.ReadError.InvalidData; if (palette.len > 0) { @@ -436,7 +436,7 @@ fn readAllData( // Just make sure zip stream gets to its end var buf: [8]u8 = undefined; - var shouldBeZero = decompress_stream.read(buf[0..]) catch return Image.ReadError.InvalidData; + const shouldBeZero = decompress_stream.read(buf[0..]) catch return Image.ReadError.InvalidData; std.debug.assert(shouldBeZero == 0); @@ -524,7 +524,7 @@ fn spreadRowData( } }, 16 => { - var current_row16 = mem.bytesAsSlice(u16, current_row); + const current_row16 = mem.bytesAsSlice(u16, current_row); var dest_row16 = mem.bytesAsSlice(u16, dest_row); const pixel_stride16 = pixel_stride / 2; source_index /= 2; @@ -811,7 +811,7 @@ pub const PlteProcessor = struct { if (!data.src_format.isIndex() or self.palette.len == 0) { return data.src_format; } - var pixel_stride: u8 = switch (data.dest_format) { + const pixel_stride: u8 = switch (data.dest_format) { .rgba32, .bgra32 => 4, .rgba64 => 8, else => return data.src_format, diff --git a/vendor/zigimg/src/formats/qoi.zig b/vendor/zigimg/src/formats/qoi.zig index ef5c1908..d9511647 100644 --- a/vendor/zigimg/src/formats/qoi.zig +++ b/vendor/zigimg/src/formats/qoi.zig @@ -210,7 +210,7 @@ pub const QOI = struct { const pixels_size: usize = @as(usize, self.header.width) * @as(usize, self.header.height); while (index < pixels_size) { - var byte = try reader.readByte(); + const byte = try reader.readByte(); var new_color = current_color; var count: usize = 1; diff --git a/vendor/zigimg/src/octree_quantizer.zig b/vendor/zigimg/src/octree_quantizer.zig index 5881d275..4f35bbb4 100644 --- a/vendor/zigimg/src/octree_quantizer.zig +++ b/vendor/zigimg/src/octree_quantizer.zig @@ -203,7 +203,7 @@ const OctTreeQuantizerNode = struct { inline fn getColorIndex(color: Rgba32, level: i32) usize { var index: usize = 0; - var mask = @as(u8, 0b10000000) >> @as(u3, @intCast(level)); + const mask = @as(u8, 0b10000000) >> @as(u3, @intCast(level)); if (color.r & mask != 0) { index |= 0b100; } diff --git a/vendor/zigimg/tests/formats/bmp_test.zig b/vendor/zigimg/tests/formats/bmp_test.zig index 89fb5cf5..9aee9d38 100644 --- a/vendor/zigimg/tests/formats/bmp_test.zig +++ b/vendor/zigimg/tests/formats/bmp_test.zig @@ -163,7 +163,7 @@ test "Read a valid version 5 RGBA bitmap from file" { test "Read a valid version 5 RGBA bitmap from memory" { var MemoryRGBABitmap: [200 * 1024]u8 = undefined; - var buffer: []const u8 = try helpers.testReadFile(helpers.fixtures_path ++ "bmp/windows_rgba_v5.bmp", MemoryRGBABitmap[0..]); + const buffer: []const u8 = try helpers.testReadFile(helpers.fixtures_path ++ "bmp/windows_rgba_v5.bmp", MemoryRGBABitmap[0..]); var stream_source = std.io.StreamSource{ .const_buffer = std.io.fixedBufferStream(buffer) }; var the_bitmap = bmp.Bitmap{}; diff --git a/vendor/zigimg/tests/formats/png_test.zig b/vendor/zigimg/tests/formats/png_test.zig index 497d3db4..55570ad7 100644 --- a/vendor/zigimg/tests/formats/png_test.zig +++ b/vendor/zigimg/tests/formats/png_test.zig @@ -31,7 +31,7 @@ test "loadHeader_valid" { const expectEqual = std.testing.expectEqual; var buffer = valid_header_data.*; var stream = Image.Stream{ .buffer = std.io.fixedBufferStream(&buffer) }; - var header = try png.loadHeader(&stream); + const header = try png.loadHeader(&stream); try expectEqual(@as(u32, 0xff), header.width); try expectEqual(@as(u32, 0x75), header.height); try expectEqual(@as(u8, 8), header.bit_depth); @@ -97,7 +97,7 @@ test "PNG loadHeader() should error on invalid data in header" { } fn testHeaderWithInvalidValue(buf: []u8, position: usize, val: u8) !void { - var origin = buf[position]; + const origin = buf[position]; buf[position] = val; var stream = Image.Stream{ .buffer = std.io.fixedBufferStream(buf) }; try expectError(Image.ReadError.InvalidData, png.loadHeader(&stream)); @@ -131,7 +131,7 @@ pub fn testWithDir(directory: []const u8, testMd5Sig: bool) !void { var default_options = png.DefaultOptions{}; var header = try png.loadHeader(&stream); if (entry.name[0] == 'x') { - var error_result = png.loadWithHeader(&stream, &header, std.testing.allocator, default_options.get()); + const error_result = png.loadWithHeader(&stream, &header, std.testing.allocator, default_options.get()); try std.testing.expectError(Image.ReadError.InvalidData, error_result); if (testMd5Sig) std.debug.print("OK\n", .{}); continue; @@ -142,7 +142,7 @@ pub fn testWithDir(directory: []const u8, testMd5Sig: bool) !void { if (!testMd5Sig) continue; - var result_bytes = result.asBytes(); + const result_bytes = result.asBytes(); var md5_val: [16]u8 = undefined; std.crypto.hash.Md5.hash(result_bytes, &md5_val, .{}); @@ -157,9 +157,9 @@ pub fn testWithDir(directory: []const u8, testMd5Sig: bool) !void { var treader = tdata.reader(); var expected_md5: [16]u8 = undefined; var read_buffer: [50]u8 = undefined; - var str_format = try treader.readUntilDelimiter(read_buffer[0..], '\n'); - var expected_pixel_format = std.meta.stringToEnum(PixelFormat, str_format).?; - var str_md5 = try treader.readUntilDelimiterOrEof(read_buffer[0..], '\n'); + const str_format = try treader.readUntilDelimiter(read_buffer[0..], '\n'); + const expected_pixel_format = std.meta.stringToEnum(PixelFormat, str_format).?; + const str_md5 = try treader.readUntilDelimiterOrEof(read_buffer[0..], '\n'); _ = try std.fmt.hexToBytes(expected_md5[0..], str_md5.?); try std.testing.expectEqual(expected_pixel_format, std.meta.activeTag(result)); try std.testing.expectEqualSlices(u8, expected_md5[0..], md5_val[0..]); // catch std.debug.print("MD5 Expected: {s} Got {s}\n", .{std.fmt.fmtSliceHexUpper(expected_md5[0..]), std.fmt.fmtSliceHexUpper(md5_val[0..])}); diff --git a/vendor/zigimg/tests/formats/qoi_test.zig b/vendor/zigimg/tests/formats/qoi_test.zig index 4c48bf2e..784e2ffb 100644 --- a/vendor/zigimg/tests/formats/qoi_test.zig +++ b/vendor/zigimg/tests/formats/qoi_test.zig @@ -43,7 +43,7 @@ test "Read zero.qoi file" { try testing.expect(pixels == .rgba32); var buffer: [1025 * 1024]u8 = undefined; - var zero_raw_pixels = try helpers.testReadFile(zero_raw_file, buffer[0..]); + const zero_raw_pixels = try helpers.testReadFile(zero_raw_file, buffer[0..]); try testing.expectEqualSlices(u8, zero_raw_pixels, std.mem.sliceAsBytes(pixels.rgba32)); } @@ -52,7 +52,7 @@ test "Write qoi file" { defer source_image.deinit(); var buffer: [1025 * 1024]u8 = undefined; - var zero_raw_pixels = try helpers.testReadFile(zero_raw_file, buffer[0..]); + const zero_raw_pixels = try helpers.testReadFile(zero_raw_file, buffer[0..]); std.mem.copy(u8, std.mem.sliceAsBytes(source_image.pixels.rgba32), std.mem.bytesAsSlice(u8, zero_raw_pixels)); var image_buffer: [100 * 1024]u8 = undefined; diff --git a/vendor/zigimg/tests/image_test.zig b/vendor/zigimg/tests/image_test.zig index 94bc7ad7..706f0f06 100644 --- a/vendor/zigimg/tests/image_test.zig +++ b/vendor/zigimg/tests/image_test.zig @@ -180,7 +180,7 @@ test "Should detect BMP properly" { test "Should detect Memory BMP properly" { var MemoryRGBABitmap: [200 * 1024]u8 = undefined; - var buffer = try helpers.testReadFile(helpers.fixtures_path ++ "bmp/windows_rgba_v5.bmp", MemoryRGBABitmap[0..]); + const buffer = try helpers.testReadFile(helpers.fixtures_path ++ "bmp/windows_rgba_v5.bmp", MemoryRGBABitmap[0..]); var test_image = try Image.fromMemory(helpers.zigimg_test_allocator, buffer); defer test_image.deinit(); @@ -290,7 +290,7 @@ test "Should detect JPEG properly" { } test "Should error on invalid file" { - var invalidFile = helpers.testImageFromFile("tests/helpers.zig"); + const invalidFile = helpers.testImageFromFile("tests/helpers.zig"); try helpers.expectError(invalidFile, ImageError.Unsupported); } diff --git a/vendor/zigimg/tests/octree_quantizer_test.zig b/vendor/zigimg/tests/octree_quantizer_test.zig index 6c558ab9..703c94f8 100644 --- a/vendor/zigimg/tests/octree_quantizer_test.zig +++ b/vendor/zigimg/tests/octree_quantizer_test.zig @@ -18,7 +18,7 @@ test "Build the oct tree with 3 colors" { try quantizer.addColor(green); try quantizer.addColor(blue); var paletteStorage: [256]color.Rgba32 = undefined; - var palette = try quantizer.makePalette(256, paletteStorage[0..]); + const palette = try quantizer.makePalette(256, paletteStorage[0..]); try helpers.expectEq(palette.len, 3); try helpers.expectEq(try quantizer.getPaletteIndex(red), 2); @@ -32,7 +32,7 @@ test "Build the oct tree with 3 colors" { test "Build a oct tree with 32-bit RGBA bitmap" { var MemoryRGBABitmap: [200 * 1024]u8 = undefined; - var buffer = try helpers.testReadFile(helpers.fixtures_path ++ "bmp/windows_rgba_v5.bmp", MemoryRGBABitmap[0..]); + const buffer = try helpers.testReadFile(helpers.fixtures_path ++ "bmp/windows_rgba_v5.bmp", MemoryRGBABitmap[0..]); var image = try Image.fromMemory(helpers.zigimg_test_allocator, buffer); defer image.deinit(); @@ -47,17 +47,17 @@ test "Build a oct tree with 32-bit RGBA bitmap" { } var paletteStorage: [256]color.Rgba32 = undefined; - var palette = try quantizer.makePalette(255, paletteStorage[0..]); + const palette = try quantizer.makePalette(255, paletteStorage[0..]); try helpers.expectEq(palette.len, 255); - var paletteIndex = try quantizer.getPaletteIndex(color.Rgba32.initRgba(110, 0, 0, 255)); + const paletteIndex = try quantizer.getPaletteIndex(color.Rgba32.initRgba(110, 0, 0, 255)); try helpers.expectEq(paletteIndex, 93); try helpers.expectEq(palette[93].r, 110); try helpers.expectEq(palette[93].g, 2); try helpers.expectEq(palette[93].b, 2); try helpers.expectEq(palette[93].a, 255); - var secondPaletteIndex = try quantizer.getPaletteIndex(color.Rgba32.initRgba(0, 0, 119, 255)); + const secondPaletteIndex = try quantizer.getPaletteIndex(color.Rgba32.initRgba(0, 0, 119, 255)); try helpers.expectEq(secondPaletteIndex, 53); try helpers.expectEq(palette[53].r, 0); try helpers.expectEq(palette[53].g, 0); From 09c265ea505c8167046ce9512fbe15125559c5d1 Mon Sep 17 00:00:00 2001 From: Dave Mason Date: Thu, 14 Dec 2023 08:39:58 -0500 Subject: [PATCH 02/10] minor --- src/backends/macos/objc.zig | 3 +-- src/trait.zig | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/backends/macos/objc.zig b/src/backends/macos/objc.zig index 63a8d659..5ad27043 100644 --- a/src/backends/macos/objc.zig +++ b/src/backends/macos/objc.zig @@ -9,8 +9,7 @@ pub fn msgSend(comptime ReturnType: type, target: anytype, selector: SEL, args: if ((target_type == id or target_type == Class) == false) @compileError("msgSend target should be of type id or Class"); const args_meta = @typeInfo(@TypeOf(args)).Struct.fields; - - if (comptime !trait.isContainer(ReturnType)) { + if (comptime !trait.isContainer(ReturnType) or @import("builtin").cpu.arch == .aarch64) { const FnType = blk: { { // TODO(hazeycode): replace this hack with the more generalised code above once it doens't crash the compiler diff --git a/src/trait.zig b/src/trait.zig index 4ca852fd..e7f03029 100644 --- a/src/trait.zig +++ b/src/trait.zig @@ -1,6 +1,6 @@ const std = @import("std"); -pub usingnamespace if (@hasField(std.meta,"trait")) std.meta.trait else struct { +pub usingnamespace if (@hasField(std.meta, "trait")) std.meta.trait else struct { pub fn isNumber(comptime T: type) bool { return switch (@typeInfo(T)) { .Int, .Float, .ComptimeInt, .ComptimeFloat => true, From e8cd25e00c9917e67a6580958f56c37efdaf9c6f Mon Sep 17 00:00:00 2001 From: Allison Durham Date: Tue, 19 Dec 2023 16:50:30 -0600 Subject: [PATCH 03/10] corrected atomic.Atomic to atomic.Value for zig latest master compatibility --- android/examples/invocationhandler/main.zig | 2 +- android/examples/textview/main.zig | 2 +- build.zig | 2 +- src/async.zig | 2 +- src/backends/android/backend.zig | 4 ++-- src/backends/gtk/backend.zig | 2 +- src/components/Navigation.zig | 2 +- src/components/TextArea.zig | 2 +- src/components/TextField.zig | 2 +- 9 files changed, 10 insertions(+), 10 deletions(-) diff --git a/android/examples/invocationhandler/main.zig b/android/examples/invocationhandler/main.zig index fd692b42..f776f736 100644 --- a/android/examples/invocationhandler/main.zig +++ b/android/examples/invocationhandler/main.zig @@ -64,7 +64,7 @@ pub const AndroidApp = struct { pipe: [2]std.os.fd_t = undefined, // This is used with futexes so that runOnUiThread waits until the callback is completed // before returning. - uiThreadCondition: std.atomic.Atomic(u32) = std.atomic.Atomic(u32).init(0), + uiThreadCondition: std.atomic.Value(u32) = std.atomic.Value(u32).init(0), uiThreadLooper: *android.ALooper = undefined, uiThreadId: std.Thread.Id = undefined, diff --git a/android/examples/textview/main.zig b/android/examples/textview/main.zig index f52aaaff..66027942 100644 --- a/android/examples/textview/main.zig +++ b/android/examples/textview/main.zig @@ -32,7 +32,7 @@ pub const AndroidApp = struct { pipe: [2]std.os.fd_t = undefined, // This is used with futexes so that runOnUiThread waits until the callback is completed // before returning. - uiThreadCondition: std.atomic.Atomic(u32) = std.atomic.Atomic(u32).init(0), + uiThreadCondition: std.atomic.Value(u32) = std.atomic.Value(u32).init(0), uiThreadLooper: *android.ALooper = undefined, uiThreadId: std.Thread.Id = undefined, diff --git a/build.zig b/build.zig index 0f769a94..49ac6477 100644 --- a/build.zig +++ b/build.zig @@ -7,7 +7,7 @@ pub fn build(b: *std.Build) !void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); - var examplesDir = try std.fs.cwd().openDir("examples", .{}); + var examplesDir = try std.fs.cwd().openDir("examples", .{ .iterate = true }); defer examplesDir.close(); const broken = switch (target.getOsTag()) { diff --git a/src/async.zig b/src/async.zig index 657cc028..d1c2e913 100644 --- a/src/async.zig +++ b/src/async.zig @@ -15,7 +15,7 @@ pub const ThreadPool = struct { thread: std.Thread, /// The last time a task was executed on this thread, in milliseconds. last_used: i64, - busy: std.atomic.Atomic(bool) = false, + busy: std.atomic.Value(bool) = false, }; pub fn init(allocator: std.mem.Allocator) ThreadPool { diff --git a/src/backends/android/backend.zig b/src/backends/android/backend.zig index cf00c917..708a1884 100644 --- a/src/backends/android/backend.zig +++ b/src/backends/android/backend.zig @@ -10,7 +10,7 @@ const MouseButton = shared.MouseButton; pub const PeerType = *anyopaque; // jobject but not optional -var activeWindows = std.atomic.Atomic(usize).init(0); +var activeWindows = std.atomic.Value(usize).init(0); var hasInit: bool = false; var theApp: *backendExport.AndroidApp = undefined; @@ -732,7 +732,7 @@ pub const backendExport = struct { pipe: [2]std.os.fd_t = undefined, // This is used with futexes so that runOnUiThread waits until the callback is completed // before returning. - uiThreadCondition: std.atomic.Atomic(u32) = std.atomic.Atomic(u32).init(0), + uiThreadCondition: std.atomic.Value(u32) = std.atomic.Value(u32).init(0), // TODO: add an interface in capy for handling stored state pub fn init(allocator: std.mem.Allocator, activity: *android.ANativeActivity, stored_state: ?[]const u8) !AndroidApp { diff --git a/src/backends/gtk/backend.zig b/src/backends/gtk/backend.zig index 852cad04..a1edfdfe 100644 --- a/src/backends/gtk/backend.zig +++ b/src/backends/gtk/backend.zig @@ -20,7 +20,7 @@ const GTK_VERSION = std.SemanticVersion.Range{ pub const Capabilities = .{ .useEventLoop = true }; -var activeWindows = std.atomic.Atomic(usize).init(0); +var activeWindows = std.atomic.Value(usize).init(0); var randomWindow: *c.GtkWidget = undefined; var hasInit: bool = false; diff --git a/src/components/Navigation.zig b/src/components/Navigation.zig index 6370858b..72ac38f1 100644 --- a/src/components/Navigation.zig +++ b/src/components/Navigation.zig @@ -11,7 +11,7 @@ pub const Navigation = struct { peer: ?backend.Container = null, widget_data: Navigation.WidgetData = .{}, - relayouting: std.atomic.Atomic(bool) = std.atomic.Atomic(bool).init(false), + relayouting: std.atomic.Value(bool) = std.atomic.Value(bool).init(false), routeName: Atom([]const u8), activeChild: *Widget, routes: std.StringHashMap(Widget), diff --git a/src/components/TextArea.zig b/src/components/TextArea.zig index 35512c89..7148f183 100644 --- a/src/components/TextArea.zig +++ b/src/components/TextArea.zig @@ -12,7 +12,7 @@ pub const TextArea = struct { peer: ?backend.TextArea = null, widget_data: TextArea.WidgetData = .{}, text: StringAtom = StringAtom.of(""), - _wrapperTextBlock: std.atomic.Atomic(bool) = std.atomic.Atomic(bool).init(false), + _wrapperTextBlock: std.atomic.Value(bool) = std.atomic.Value(bool).init(false), // TODO: replace with TextArea.setFont(.{ .family = "monospace" }) ? /// Whether to let the system choose a monospace font for us and use it in this TextArea.. diff --git a/src/components/TextField.zig b/src/components/TextField.zig index 705d5913..1040d4ae 100644 --- a/src/components/TextField.zig +++ b/src/components/TextField.zig @@ -14,7 +14,7 @@ pub const TextField = struct { widget_data: TextField.WidgetData = .{}, text: StringAtom = StringAtom.of(""), readOnly: Atom(bool) = Atom(bool).of(false), - _wrapperTextBlock: std.atomic.Atomic(bool) = std.atomic.Atomic(bool).init(false), + _wrapperTextBlock: std.atomic.Value(bool) = std.atomic.Value(bool).init(false), pub fn init(config: TextField.Config) TextField { var field = TextField.init_events(TextField{ From 88d80f4a924a9a7a181967b2ca6c2540fd5e5270 Mon Sep 17 00:00:00 2001 From: Allison Durham Date: Tue, 19 Dec 2023 16:53:47 -0600 Subject: [PATCH 04/10] update isSingleItemPtr to work with latest zig master --- src/backends/android/backend.zig | 3 ++- src/backends/gles/backend.zig | 3 ++- src/backends/gtk/backend.zig | 3 ++- src/backends/wasm/backend.zig | 4 +++- src/backends/win32/backend.zig | 3 ++- 5 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/backends/android/backend.zig b/src/backends/android/backend.zig index 708a1884..3de76d4b 100644 --- a/src/backends/android/backend.zig +++ b/src/backends/android/backend.zig @@ -2,6 +2,7 @@ const std = @import("std"); const shared = @import("../shared.zig"); const lib = @import("../../main.zig"); const android = @import("android"); +const trait = @import("../../trait.zig"); const EventFunctions = shared.EventFunctions(@This()); const EventType = shared.BackendEventType; @@ -154,7 +155,7 @@ pub fn Events(comptime T: type) type { pub inline fn setUserData(self: *T, data: anytype) void { comptime { - if (!std.meta.trait.isSingleItemPtr(@TypeOf(data))) { + if (!trait.isSingleItemPtr(@TypeOf(data))) { @compileError(std.fmt.comptimePrint("Expected single item pointer, got {s}", .{@typeName(@TypeOf(data))})); } } diff --git a/src/backends/gles/backend.zig b/src/backends/gles/backend.zig index b8a4a33b..8adabc03 100644 --- a/src/backends/gles/backend.zig +++ b/src/backends/gles/backend.zig @@ -1,6 +1,7 @@ const std = @import("std"); const shared = @import("../shared.zig"); const lib = @import("../../main.zig"); +const trait = @import("../../trait.zig"); const c = @cImport({ @cDefine("GLFW_INCLUDE_ES3", {}); @cInclude("GLFW/glfw3.h"); @@ -161,7 +162,7 @@ pub fn Events(comptime T: type) type { pub inline fn setUserData(self: *T, data: anytype) void { comptime { - if (!std.meta.trait.isSingleItemPtr(@TypeOf(data))) { + if (!trait.isSingleItemPtr(@TypeOf(data))) { @compileError(std.fmt.comptimePrint("Expected single item pointer, got {s}", .{@typeName(@TypeOf(data))})); } } diff --git a/src/backends/gtk/backend.zig b/src/backends/gtk/backend.zig index a1edfdfe..461d8468 100644 --- a/src/backends/gtk/backend.zig +++ b/src/backends/gtk/backend.zig @@ -1,6 +1,7 @@ const std = @import("std"); const shared = @import("../shared.zig"); const lib = @import("../../main.zig"); +const trait = @import("../../trait.zig"); pub const c = @cImport({ @cInclude("gtk/gtk.h"); }); @@ -441,7 +442,7 @@ pub fn Events(comptime T: type) type { pub inline fn setUserData(self: *T, data: anytype) void { comptime { - if (!std.meta.trait.isSingleItemPtr(@TypeOf(data))) { + if (!trait.isSingleItemPtr(@TypeOf(data))) { @compileError(std.fmt.comptimePrint("Expected single item pointer, got {s}", .{@typeName(@TypeOf(data))})); } } diff --git a/src/backends/wasm/backend.zig b/src/backends/wasm/backend.zig index db31a66a..70353e43 100644 --- a/src/backends/wasm/backend.zig +++ b/src/backends/wasm/backend.zig @@ -2,6 +2,8 @@ const std = @import("std"); const shared = @import("../shared.zig"); const lib = @import("../../main.zig"); const js = @import("js.zig"); +const trait = @import("../../trait.zig"); + const lasting_allocator = lib.internal.lasting_allocator; const EventType = shared.BackendEventType; @@ -106,7 +108,7 @@ pub fn Events(comptime T: type) type { pub inline fn setUserData(self: *T, data: anytype) void { comptime { - if (!std.meta.trait.isSingleItemPtr(@TypeOf(data))) { + if (!trait.isSingleItemPtr(@TypeOf(data))) { @compileError(std.fmt.comptimePrint("Expected single item pointer, got {s}", .{@typeName(@TypeOf(data))})); } } diff --git a/src/backends/win32/backend.zig b/src/backends/win32/backend.zig index 9d162fc5..d78fd7aa 100644 --- a/src/backends/win32/backend.zig +++ b/src/backends/win32/backend.zig @@ -1,6 +1,7 @@ const std = @import("std"); const lib = @import("../../main.zig"); const shared = @import("../shared.zig"); +const trait = @import("../../trait.zig"); const os = @import("builtin").target.os; const log = std.log.scoped(.win32); @@ -583,7 +584,7 @@ pub fn Events(comptime T: type) type { pub inline fn setUserData(self: *T, data: anytype) void { comptime { - if (!std.meta.trait.isSingleItemPtr(@TypeOf(data))) { + if (!trait.isSingleItemPtr(@TypeOf(data))) { @compileError(std.fmt.comptimePrint("Expected single item pointer, got {s}", .{@typeName(@TypeOf(data))})); } } From 3eda6daf1b0f7ab6eaf038dcfff5b92c540dda7f Mon Sep 17 00:00:00 2001 From: Allison Durham Date: Tue, 19 Dec 2023 16:59:18 -0600 Subject: [PATCH 05/10] update trait.is() for zig master compatibility --- src/data.zig | 2 +- src/internal.zig | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/data.zig b/src/data.zig index 206242f5..c5a49f07 100644 --- a/src/data.zig +++ b/src/data.zig @@ -39,7 +39,7 @@ pub fn lerp(a: anytype, b: @TypeOf(a), t: f64) @TypeOf(a) { } } else if (comptime trait.isContainer(T) and @hasDecl(T, "lerp")) { return T.lerp(a, b, t); - } else if (comptime std.meta.trait.is(.Optional)(T)) { + } else if (comptime trait.is(.Optional)(T)) { if (a != null and b != null) { return lerp(a.?, b.?, t); } else { diff --git a/src/internal.zig b/src/internal.zig index 5954d900..c486012a 100644 --- a/src/internal.zig +++ b/src/internal.zig @@ -340,7 +340,7 @@ fn iterateApplyFields(comptime T: type, target: anytype, config: GenerateConfigS @field(target, field.name).set( @field(config, name), ); - } else if (comptime std.meta.trait.is(.Struct)(FieldType)) { + } else if (comptime trait.is(.Struct)(FieldType)) { iterateApplyFields(T, &@field(target, field.name), config); } } From edfce3ad1185e57ab77307b21eff0936034f644c Mon Sep 17 00:00:00 2001 From: Allison Durham Date: Tue, 19 Dec 2023 16:59:47 -0600 Subject: [PATCH 06/10] isIntegral update for zig master compatibility --- src/dev_tools.zig | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/dev_tools.zig b/src/dev_tools.zig index 3808fe92..8c3db973 100644 --- a/src/dev_tools.zig +++ b/src/dev_tools.zig @@ -1,6 +1,7 @@ //! Capy Development Tools Server const std = @import("std"); const internal = @import("internal.zig"); +const trait = @import("trait.zig"); const DEV_TOOLS_PORT = 42671; const log = std.log.scoped(.dev_tools); @@ -73,7 +74,7 @@ pub fn init() !void { } fn readStructField(comptime T: type, reader: anytype) !T { - if (comptime std.meta.trait.isIntegral(T)) { + if (comptime trait.isIntegral(T)) { return try reader.readIntBig(T); } else if (T == []const u8) { const length = try std.leb.readULEB128(u32, reader); @@ -84,7 +85,7 @@ fn readStructField(comptime T: type, reader: anytype) !T { } fn writeStructField(comptime T: type, writer: anytype, value: T) !void { - if (comptime std.meta.trait.isIntegral(T)) { + if (comptime trait.isIntegral(T)) { try writer.writeIntBig(T, value); } else if (T == []const u8) { try std.leb.writeULEB128(writer, value.len); From 8bb81ee11f6a71c09fe8474550c866ca6767707a Mon Sep 17 00:00:00 2001 From: Allison Durham Date: Tue, 19 Dec 2023 17:02:19 -0600 Subject: [PATCH 07/10] updated isNumber for zig master support --- src/fuzz.zig | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/fuzz.zig b/src/fuzz.zig index 83066e70..7a9ed229 100644 --- a/src/fuzz.zig +++ b/src/fuzz.zig @@ -1,5 +1,6 @@ //! Randomly test data and lower it down const std = @import("std"); +const trait = @import("trait.zig"); pub fn forAll(comptime T: type) Iterator(T) { return Iterator(T).init(); @@ -115,7 +116,7 @@ pub fn testFunction(comptime T: type, duration: i64, func: fn (T) anyerror!void) pub fn hypothetize(self: *Self, callback: fn (T) anyerror!void) !Hypothesis { var elements = std.ArrayList(Hypothesis.HypothesisElement).init(std.testing.allocator); - if (comptime std.meta.trait.isNumber(T)) { + if (comptime trait.isNumber(T)) { std.sort.sort(T, self.items, {}, comptime std.sort.asc(T)); const smallest = self.items[0]; const biggest = self.items[self.items.len - 1]; From 549028ead308b008e2263ba244178ecbd42370d3 Mon Sep 17 00:00:00 2001 From: Dave Mason Date: Tue, 19 Dec 2023 21:52:16 -0500 Subject: [PATCH 08/10] Added std.meta.trait functions mentioned by AdjectiveAllison --- src/trait.zig | 74 ++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 73 insertions(+), 1 deletion(-) diff --git a/src/trait.zig b/src/trait.zig index e7f03029..1e511cc6 100644 --- a/src/trait.zig +++ b/src/trait.zig @@ -1,6 +1,7 @@ const std = @import("std"); pub usingnamespace if (@hasField(std.meta, "trait")) std.meta.trait else struct { + const TraitFn = fn (type) bool; pub fn isNumber(comptime T: type) bool { return switch (@typeInfo(T)) { .Int, .Float, .ComptimeInt, .ComptimeFloat => true, @@ -13,7 +14,7 @@ pub usingnamespace if (@hasField(std.meta, "trait")) std.meta.trait else struct else => false, }; } - pub fn is(comptime id: std.builtin.TypeId) fn (type) bool { + pub fn is(comptime id: std.builtin.TypeId) TraitFn { const Closure = struct { pub fn trait(comptime T: type) bool { return id == @typeInfo(T); @@ -21,6 +22,15 @@ pub usingnamespace if (@hasField(std.meta, "trait")) std.meta.trait else struct }; return Closure.trait; } + pub fn isPtrTo(comptime id: std.builtin.TypeId) TraitFn { + const Closure = struct { + pub fn trait(comptime T: type) bool { + if (!comptime isSingleItemPtr(T)) return false; + return id == @typeInfo(std.meta.Child(T)); + } + }; + return Closure.trait; + } pub fn isSingleItemPtr(comptime T: type) bool { if (comptime is(.Pointer)(T)) { return @typeInfo(T).Pointer.size == .One; @@ -33,4 +43,66 @@ pub usingnamespace if (@hasField(std.meta, "trait")) std.meta.trait else struct else => false, }; } + pub fn isZigString(comptime T: type) bool { + return comptime blk: { + // Only pointer types can be strings, no optionals + const info = @typeInfo(T); + if (info != .Pointer) break :blk false; + + const ptr = &info.Pointer; + // Check for CV qualifiers that would prevent coerction to []const u8 + if (ptr.is_volatile or ptr.is_allowzero) break :blk false; + + // If it's already a slice, simple check. + if (ptr.size == .Slice) { + break :blk ptr.child == u8; + } + + // Otherwise check if it's an array type that coerces to slice. + if (ptr.size == .One) { + const child = @typeInfo(ptr.child); + if (child == .Array) { + const arr = &child.Array; + break :blk arr.child == u8; + } + } + + break :blk false; + }; + } + pub fn hasUniqueRepresentation(comptime T: type) bool { + switch (@typeInfo(T)) { + else => return false, // TODO can we know if it's true for some of these types ? + + .AnyFrame, + .Enum, + .ErrorSet, + .Fn, + => return true, + + .Bool => return false, + + .Int => |info| return @sizeOf(T) * 8 == info.bits, + + .Pointer => |info| return info.size != .Slice, + + .Array => |info| return comptime hasUniqueRepresentation(info.child), + + .Struct => |info| { + var sum_size = @as(usize, 0); + + inline for (info.fields) |field| { + const FieldType = field.type; + if (comptime !hasUniqueRepresentation(FieldType)) return false; + sum_size += @sizeOf(FieldType); + } + + return @sizeOf(T) == sum_size; + }, + + .Vector => |info| return comptime hasUniqueRepresentation(info.child) and + @sizeOf(T) == @sizeOf(info.child) * info.len, + } + } + }; From fdb5da6be1eeb1ee05428d66f6a10918bd89b202 Mon Sep 17 00:00:00 2001 From: Dave Mason Date: Tue, 19 Dec 2023 22:42:49 -0500 Subject: [PATCH 09/10] Try to make sure it compiles wil 0.11 as well Gets an error that I don't understand --- build.zig | 2 +- src/backends/macos/backend.zig | 3 ++- src/containers.zig | 3 ++- src/data.zig | 6 ++++-- src/trait.zig | 1 + 5 files changed, 10 insertions(+), 5 deletions(-) diff --git a/build.zig b/build.zig index 49ac6477..e039551d 100644 --- a/build.zig +++ b/build.zig @@ -7,7 +7,7 @@ pub fn build(b: *std.Build) !void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); - var examplesDir = try std.fs.cwd().openDir("examples", .{ .iterate = true }); + var examplesDir = try if (@hasField(std.fs.Dir.OpenDirOptions,"iterate")) std.fs.cwd().openDir("examples",.{ .iterate = true }) else std.fs.cwd().openIterableDir("examples",.{}); // support zig 0.11 as well as current master defer examplesDir.close(); const broken = switch (target.getOsTag()) { diff --git a/src/backends/macos/backend.zig b/src/backends/macos/backend.zig index 53cf4b1d..ad6a9e05 100644 --- a/src/backends/macos/backend.zig +++ b/src/backends/macos/backend.zig @@ -13,7 +13,8 @@ const MouseButton = shared.MouseButton; // pub const PeerType = *opaque {}; pub const PeerType = objc.id; -var activeWindows = std.atomic.Value(usize).init(0); +const atomicValue = if (@hasField(std.atomic,"Value")) std.atomic.Value else std.atomic.Atomic; // support zig 0.11 as well as current master +var activeWindows = atomicValue(usize).init(0); var hasInit: bool = false; pub fn init() BackendError!void { diff --git a/src/containers.zig b/src/containers.zig index e193419a..d74b6bce 100644 --- a/src/containers.zig +++ b/src/containers.zig @@ -238,13 +238,14 @@ pub const Container = struct { widget_data: Container.WidgetData = .{}, childrens: std.ArrayList(Widget), expand: bool, - relayouting: std.atomic.Value(bool) = std.atomic.Value(bool).init(false), + relayouting: atomicValue(bool) = atomicValue(bool).init(false), layout: Layout, layoutConfig: [16]u8, /// The widget associated to this Container widget: ?*Widget = null, + const atomicValue = if (@hasField(std.atomic,"Value")) std.atomic.Value else std.atomic.Atomic; // support zig 0.11 as well as current master pub fn init(childrens: std.ArrayList(Widget), config: GridConfig, layout: Layout, layoutConfig: anytype) !Container { const LayoutConfig = @TypeOf(layoutConfig); comptime std.debug.assert(@sizeOf(LayoutConfig) <= 16); diff --git a/src/data.zig b/src/data.zig index c5a49f07..249e4780 100644 --- a/src/data.zig +++ b/src/data.zig @@ -137,7 +137,7 @@ pub fn Atom(comptime T: type) type { /// When A is set, it sets the lock to true and sets B. Since B is set, it will set A too. /// A notices that bindLock is already set to true, and thus returns. /// TODO: make the bind lock more general and just use it for any change, and explicit how this favors completeness instead of consistency (in case an onChange triggers set method manually) - bindLock: std.atomic.Value(bool) = std.atomic.Value(bool).init(false), + bindLock: atomicValue(bool) = atomicValue(bool).init(false), /// If dependOn has been called, this is a pointer to the callback function depend_on_callback: ?*const anyopaque = null, @@ -148,6 +148,7 @@ pub fn Atom(comptime T: type) type { const Self = @This(); const isAnimable = isAnimableType(T); + const atomicValue = if (@hasField(std.atomic,"Value")) std.atomic.Value else std.atomic.Atomic; // support zig 0.11 as well as current master pub const ValueType = T; pub const ChangeListener = struct { @@ -428,7 +429,8 @@ pub fn Atom(comptime T: type) type { // If the old value was false, it returns null, which is what we want. // Otherwise, it returns the old value, but since the only value other than false is true, // we're not interested in the result. - if (self.bindLock.cmpxchgStrong(false, true, .SeqCst, .SeqCst) == null) { + if ((if (@hasField(atomicValue(bool),"cmpxchgStrong")) self.bindLock.cmpxchgStrong(false, true, .SeqCst, .SeqCst) else self.bindLock.cmpxchg(true,false, true, .SeqCst, .SeqCst) // support zig 0.11 as well as current master + ) == null) { defer self.bindLock.store(false, .SeqCst); { diff --git a/src/trait.zig b/src/trait.zig index 1e511cc6..cb95e868 100644 --- a/src/trait.zig +++ b/src/trait.zig @@ -1,5 +1,6 @@ const std = @import("std"); +// support zig 0.11 as well as current master pub usingnamespace if (@hasField(std.meta, "trait")) std.meta.trait else struct { const TraitFn = fn (type) bool; pub fn isNumber(comptime T: type) bool { From 83aa9fb664c3e9e4f0a0e5ece735a21b5658d213 Mon Sep 17 00:00:00 2001 From: Dave Mason Date: Tue, 19 Dec 2023 22:48:44 -0500 Subject: [PATCH 10/10] minor fix --- src/backends/macos/backend.zig | 2 +- src/containers.zig | 2 +- src/data.zig | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/backends/macos/backend.zig b/src/backends/macos/backend.zig index ad6a9e05..36a03669 100644 --- a/src/backends/macos/backend.zig +++ b/src/backends/macos/backend.zig @@ -13,7 +13,7 @@ const MouseButton = shared.MouseButton; // pub const PeerType = *opaque {}; pub const PeerType = objc.id; -const atomicValue = if (@hasField(std.atomic,"Value")) std.atomic.Value else std.atomic.Atomic; // support zig 0.11 as well as current master +const atomicValue = if (@hasDecl(std.atomic,"Value")) std.atomic.Value else std.atomic.Atomic; // support zig 0.11 as well as current master var activeWindows = atomicValue(usize).init(0); var hasInit: bool = false; diff --git a/src/containers.zig b/src/containers.zig index d74b6bce..40468571 100644 --- a/src/containers.zig +++ b/src/containers.zig @@ -245,7 +245,7 @@ pub const Container = struct { /// The widget associated to this Container widget: ?*Widget = null, - const atomicValue = if (@hasField(std.atomic,"Value")) std.atomic.Value else std.atomic.Atomic; // support zig 0.11 as well as current master + const atomicValue = if (@hasDecl(std.atomic,"Value")) std.atomic.Value else std.atomic.Atomic; // support zig 0.11 as well as current master pub fn init(childrens: std.ArrayList(Widget), config: GridConfig, layout: Layout, layoutConfig: anytype) !Container { const LayoutConfig = @TypeOf(layoutConfig); comptime std.debug.assert(@sizeOf(LayoutConfig) <= 16); diff --git a/src/data.zig b/src/data.zig index 249e4780..119c8c53 100644 --- a/src/data.zig +++ b/src/data.zig @@ -148,7 +148,7 @@ pub fn Atom(comptime T: type) type { const Self = @This(); const isAnimable = isAnimableType(T); - const atomicValue = if (@hasField(std.atomic,"Value")) std.atomic.Value else std.atomic.Atomic; // support zig 0.11 as well as current master + const atomicValue = if (@hasDecl(std.atomic,"Value")) std.atomic.Value else std.atomic.Atomic; // support zig 0.11 as well as current master pub const ValueType = T; pub const ChangeListener = struct { @@ -429,7 +429,7 @@ pub fn Atom(comptime T: type) type { // If the old value was false, it returns null, which is what we want. // Otherwise, it returns the old value, but since the only value other than false is true, // we're not interested in the result. - if ((if (@hasField(atomicValue(bool),"cmpxchgStrong")) self.bindLock.cmpxchgStrong(false, true, .SeqCst, .SeqCst) else self.bindLock.cmpxchg(true,false, true, .SeqCst, .SeqCst) // support zig 0.11 as well as current master + if ((if (@hasDecl(atomicValue(bool),"cmpxchgStrong")) self.bindLock.cmpxchgStrong(false, true, .SeqCst, .SeqCst) else self.bindLock.cmpxchg(true,false, true, .SeqCst, .SeqCst) // support zig 0.11 as well as current master ) == null) { defer self.bindLock.store(false, .SeqCst);