Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions lib/std/Io.zig
Original file line numberDiff line numberDiff line change
Expand Up@@ -990,15 +990,15 @@ pub fn Future(Result: type) type {
/// Idempotent. Not threadsafe.
pub fn cancel(f: *@This(), io: Io) Result {
const any_future = f.any_future orelse return f.result;
io.vtable.cancel(io.userdata, any_future, @ptrCast((&f.result)[0..1]), .of(Result));
io.vtable.cancel(io.userdata, any_future, @ptrCast(&f.result), .of(Result));
f.any_future = null;
return f.result;
}

/// Idempotent. Not threadsafe.
pub fn await(f: *@This(), io: Io) Result {
const any_future = f.any_future orelse return f.result;
io.vtable.await(io.userdata, any_future, @ptrCast((&f.result)[0..1]), .of(Result));
io.vtable.await(io.userdata, any_future, @ptrCast(&f.result), .of(Result));
f.any_future = null;
return f.result;
}
Expand DownExpand Up@@ -1034,7 +1034,7 @@ pub const Group = struct {
@call(.auto, function, args_casted.*);
}
};
io.vtable.groupAsync(io.userdata, g, @ptrCast((&args)[0..1]), .of(Args), TypeErased.start);
io.vtable.groupAsync(io.userdata, g, @ptrCast(&args), .of(Args), TypeErased.start);
}

/// Blocks until all tasks of the group finish. During this time,
Expand DownExpand Up@@ -1111,7 +1111,7 @@ pub fn Select(comptime U: type) type {
}
};
_ = @atomicRmw(usize, &s.outstanding, .Add, 1, .monotonic);
s.io.vtable.groupAsync(s.io.userdata, &s.group, @ptrCast((&args)[0..1]), .of(Args), TypeErased.start);
s.io.vtable.groupAsync(s.io.userdata, &s.group, @ptrCast(&args), .of(Args), TypeErased.start);
}

/// Blocks until another task of the select finishes.
Expand DownExpand Up@@ -1539,9 +1539,9 @@ pub fn async(
var future: Future(Result) = undefined;
future.any_future = io.vtable.async(
io.userdata,
@ptrCast((&future.result)[0..1]),
@ptrCast(&future.result),
.of(Result),
@ptrCast((&args)[0..1]),
@ptrCast(&args),
.of(Args),
TypeErased.start,
);
Expand DownExpand Up@@ -1580,7 +1580,7 @@ pub fn concurrent(
io.userdata,
@sizeOf(Result),
.of(Result),
@ptrCast((&args)[0..1]),
@ptrCast(&args),
.of(Args),
TypeErased.start,
);
Expand Down
52 changes: 31 additions & 21 deletions lib/std/Io/Threaded.zig
Original file line numberDiff line numberDiff line change
Expand Up@@ -388,7 +388,8 @@ const AsyncClosure = struct {
reset_event: ResetEvent,
select_condition: ?*ResetEvent,
context_alignment: std.mem.Alignment,
result_offset: usize,
result_alignment: std.mem.Alignment,
result_offset_before_padding: usize,

const done_reset_event: *ResetEvent = @ptrFromInt(@alignOf(ResetEvent));

Expand DownExpand Up@@ -420,12 +421,12 @@ const AsyncClosure = struct {

fn resultPointer(ac: *AsyncClosure) [*]u8 {
const base: [*]u8 = @ptrCast(ac);
return base + ac.result_offset;
return @ptrFromInt(ac.result_alignment.forward(@intFromPtr(base + ac.result_offset_before_padding)));
}

fn contextPointer(ac: *AsyncClosure) [*]u8 {
const base: [*]u8 = @ptrCast(ac);
return base + ac.context_alignment.forward(@sizeOf(AsyncClosure));
return @ptrFromInt(ac.context_alignment.forward(@intFromPtr(base + @sizeOf(AsyncClosure))));
}

fn waitAndFree(ac: *AsyncClosure, gpa: Allocator, result: []u8) void {
Expand All@@ -436,7 +437,9 @@ const AsyncClosure = struct {

fn free(ac: *AsyncClosure, gpa: Allocator, result_len: usize) void {
const base: [*]align(@alignOf(AsyncClosure)) u8 = @ptrCast(ac);
gpa.free(base[0 .. ac.result_offset + result_len]);
const result_offset_with_padding = ac.result_alignment.forward(ac.result_offset_before_padding);
const allocated_size = result_offset_with_padding + result_len;
gpa.free(base[0..allocated_size]);
}
};

Expand All@@ -460,13 +463,16 @@ fn async(
};
};
const gpa = t.allocator;
const context_offset = context_alignment.forward(@sizeOf(AsyncClosure));
const result_offset = result_alignment.forward(context_offset + context.len);
const n = result_offset + result.len;
const ac: *AsyncClosure = @ptrCast(@alignCast(gpa.alignedAlloc(u8, .of(AsyncClosure), n) catch {
const context_offset_before_padding = @alignOf(AsyncClosure) + @sizeOf(AsyncClosure);
const context_offset_with_padding = context_alignment.forward(context_offset_before_padding);
const result_offset_before_padding = context_offset_with_padding + context.len;
const result_offset_with_padding = result_alignment.forward(result_offset_before_padding);
const allocated_size = result_offset_with_padding + result.len;
const ac_bytes = gpa.alignedAlloc(u8, .of(AsyncClosure), allocated_size) catch {
start(context.ptr, result.ptr);
return null;
}));
};
const ac: *AsyncClosure = @ptrCast(@alignCast(ac_bytes));

ac.* = .{
.closure = .{
Expand All@@ -476,7 +482,8 @@ fn async(
},
.func = start,
.context_alignment = context_alignment,
.result_offset = result_offset,
.result_alignment = result_alignment,
.result_offset_before_padding = result_offset_before_padding,
.reset_event = .unset,
.select_condition = null,
};
Expand DownExpand Up@@ -531,10 +538,12 @@ fn concurrent(
const t: *Threaded = @ptrCast(@alignCast(userdata));
const cpu_count = t.cpu_count catch 1;
const gpa = t.allocator;
const context_offset = context_alignment.forward(@sizeOf(AsyncClosure));
const result_offset = result_alignment.forward(context_offset + context.len);
const n = result_offset + result_len;
const ac_bytes = gpa.alignedAlloc(u8, .of(AsyncClosure), n) catch
const context_offset_before_padding = @alignOf(AsyncClosure) + @sizeOf(AsyncClosure);
const context_offset_with_padding = context_alignment.forward(context_offset_before_padding);
const result_offset_before_padding = context_offset_with_padding + context.len;
const result_offset_with_padding = result_alignment.forward(result_offset_before_padding);
const allocated_size = result_offset_with_padding + result_len;
const ac_bytes = gpa.alignedAlloc(u8, .of(AsyncClosure), allocated_size) catch
return error.ConcurrencyUnavailable;
const ac: *AsyncClosure = @ptrCast(@alignCast(ac_bytes));

Expand All@@ -546,7 +555,8 @@ fn concurrent(
},
.func = start,
.context_alignment = context_alignment,
.result_offset = result_offset,
.result_alignment = result_alignment,
.result_offset_before_padding = result_offset_before_padding,
.reset_event = .unset,
.select_condition = null,
};
Expand DownExpand Up@@ -580,6 +590,8 @@ fn concurrent(
return @ptrCast(ac);
}

/// Trailing data:
/// 1. context
const GroupClosure = struct {
closure: Closure,
t: *Threaded,
Expand DownExpand Up@@ -621,17 +633,15 @@ const GroupClosure = struct {
gpa.free(base[0..contextEnd(gc.context_alignment, gc.context_len)]);
}

fn contextOffset(context_alignment: std.mem.Alignment) usize {
return context_alignment.forward(@sizeOf(GroupClosure));
}

fn contextEnd(context_alignment: std.mem.Alignment, context_len: usize) usize {
return contextOffset(context_alignment) + context_len;
const context_offset_before_padding = @alignOf(GroupClosure) + @sizeOf(GroupClosure);
const context_offset_with_padding = context_alignment.forward(context_offset_before_padding);
return context_offset_with_padding + context_len;
}

fn contextPointer(gc: *GroupClosure) [*]u8 {
const base: [*]u8 = @ptrCast(gc);
return base + contextOffset(gc.context_alignment);
return @ptrFromInt(gc.context_alignment.forward(@intFromPtr(base + @sizeOf(GroupClosure))));
}

const sync_is_waiting: usize = 1 << 0;
Expand Down
66 changes: 66 additions & 0 deletions lib/std/Io/Threaded/test.zig
Original file line numberDiff line numberDiff line change
Expand Up@@ -56,3 +56,69 @@ test "concurrent vs concurrent prevents deadlock via oversubscription" {
getter.await(io);
putter.await(io);
}

fn paramWithExtraAlignment(param: Align64) void {
assert(param.data == 3);
}

fn returnValueWithExtraAlignment() Align64 {
return .{ .data = 5 };
}

const Align64 = struct {
data: u8 align(64),
};

test "async closure where result or context has extra alignment" {
// A fixed buffer allocator is used instead of `std.testing.allocator` to
// not get memory that has better alignment than requested.
var buffer: [1024]u8 align(64) = undefined;
var fba: std.heap.FixedBufferAllocator = .init(buffer[1..]);

var threaded: std.Io.Threaded = .init(fba.allocator());
defer threaded.deinit();
const io = threaded.io();

{
var future = io.async(paramWithExtraAlignment, .{.{ .data = 3 }});
future.await(io);
}

{
var future = io.async(returnValueWithExtraAlignment, .{});
const result = future.await(io);
try std.testing.expectEqual(5, result.data);
}
}

test "group closure where context has extra alignment" {
// A fixed buffer allocator is used instead of `std.testing.allocator` to
// not get memory that has better alignment than requested.
var buffer: [1024]u8 align(64) = undefined;
var fba: std.heap.FixedBufferAllocator = .init(buffer[1..]);

var threaded: std.Io.Threaded = .init(fba.allocator());
defer threaded.deinit();
const io = threaded.io();

var group: std.Io.Group = .init;
defer group.cancel(io);

group.async(io, paramWithExtraAlignment, .{.{ .data = 3 }});
}

fn returnArray() [32]u8 {
return @splat(5);
}

test "async on function with array parameter or return type" {
var threaded: std.Io.Threaded = .init(std.testing.allocator);
defer threaded.deinit();
const io = threaded.io();

var future = io.async(returnArray, .{});
const result = future.await(io);
for (result) |actual| {
try std.testing.expectEqual(5, actual);
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions lib/std/Io.zig
Original file line numberDiff line numberDiff line change
Expand Up@@ -990,15 +990,15 @@ pub fn Future(Result: type) type {
/// Idempotent. Not threadsafe.
pub fn cancel(f: *@This(), io: Io) Result {
const any_future = f.any_future orelse return f.result;
io.vtable.cancel(io.userdata, any_future, @ptrCast((&f.result)[0..1]), .of(Result));
io.vtable.cancel(io.userdata, any_future, @ptrCast(&f.result), .of(Result));
f.any_future = null;
return f.result;
}

/// Idempotent. Not threadsafe.
pub fn await(f: *@This(), io: Io) Result {
const any_future = f.any_future orelse return f.result;
io.vtable.await(io.userdata, any_future, @ptrCast((&f.result)[0..1]), .of(Result));
io.vtable.await(io.userdata, any_future, @ptrCast(&f.result), .of(Result));
f.any_future = null;
return f.result;
}
Expand DownExpand Up@@ -1034,7 +1034,7 @@ pub const Group = struct {
@call(.auto, function, args_casted.*);
}
};
io.vtable.groupAsync(io.userdata, g, @ptrCast((&args)[0..1]), .of(Args), TypeErased.start);
io.vtable.groupAsync(io.userdata, g, @ptrCast(&args), .of(Args), TypeErased.start);
}

/// Blocks until all tasks of the group finish. During this time,
Expand DownExpand Up@@ -1111,7 +1111,7 @@ pub fn Select(comptime U: type) type {
}
};
_ = @atomicRmw(usize, &s.outstanding, .Add, 1, .monotonic);
s.io.vtable.groupAsync(s.io.userdata, &s.group, @ptrCast((&args)[0..1]), .of(Args), TypeErased.start);
s.io.vtable.groupAsync(s.io.userdata, &s.group, @ptrCast(&args), .of(Args), TypeErased.start);
}

/// Blocks until another task of the select finishes.
Expand DownExpand Up@@ -1539,9 +1539,9 @@ pub fn async(
var future: Future(Result) = undefined;
future.any_future = io.vtable.async(
io.userdata,
@ptrCast((&future.result)[0..1]),
@ptrCast(&future.result),
.of(Result),
@ptrCast((&args)[0..1]),
@ptrCast(&args),
.of(Args),
TypeErased.start,
);
Expand DownExpand Up@@ -1580,7 +1580,7 @@ pub fn concurrent(
io.userdata,
@sizeOf(Result),
.of(Result),
@ptrCast((&args)[0..1]),
@ptrCast(&args),
.of(Args),
TypeErased.start,
);
Expand Down
52 changes: 31 additions & 21 deletions lib/std/Io/Threaded.zig
Original file line numberDiff line numberDiff line change
Expand Up@@ -388,7 +388,8 @@ const AsyncClosure = struct {
reset_event: ResetEvent,
select_condition: ?*ResetEvent,
context_alignment: std.mem.Alignment,
result_offset: usize,
result_alignment: std.mem.Alignment,
result_offset_before_padding: usize,

const done_reset_event: *ResetEvent = @ptrFromInt(@alignOf(ResetEvent));

Expand DownExpand Up@@ -420,12 +421,12 @@ const AsyncClosure = struct {

fn resultPointer(ac: *AsyncClosure) [*]u8 {
const base: [*]u8 = @ptrCast(ac);
return base + ac.result_offset;
return @ptrFromInt(ac.result_alignment.forward(@intFromPtr(base + ac.result_offset_before_padding)));
}

fn contextPointer(ac: *AsyncClosure) [*]u8 {
const base: [*]u8 = @ptrCast(ac);
return base + ac.context_alignment.forward(@sizeOf(AsyncClosure));
return @ptrFromInt(ac.context_alignment.forward(@intFromPtr(base + @sizeOf(AsyncClosure))));
}

fn waitAndFree(ac: *AsyncClosure, gpa: Allocator, result: []u8) void {
Expand All@@ -436,7 +437,9 @@ const AsyncClosure = struct {

fn free(ac: *AsyncClosure, gpa: Allocator, result_len: usize) void {
const base: [*]align(@alignOf(AsyncClosure)) u8 = @ptrCast(ac);
gpa.free(base[0 .. ac.result_offset + result_len]);
const result_offset_with_padding = ac.result_alignment.forward(ac.result_offset_before_padding);
const allocated_size = result_offset_with_padding + result_len;
gpa.free(base[0..allocated_size]);
}
};

Expand All@@ -460,13 +463,16 @@ fn async(
};
};
const gpa = t.allocator;
const context_offset = context_alignment.forward(@sizeOf(AsyncClosure));
const result_offset = result_alignment.forward(context_offset + context.len);
const n = result_offset + result.len;
const ac: *AsyncClosure = @ptrCast(@alignCast(gpa.alignedAlloc(u8, .of(AsyncClosure), n) catch {
const context_offset_before_padding = @alignOf(AsyncClosure) + @sizeOf(AsyncClosure);
const context_offset_with_padding = context_alignment.forward(context_offset_before_padding);
const result_offset_before_padding = context_offset_with_padding + context.len;
const result_offset_with_padding = result_alignment.forward(result_offset_before_padding);
const allocated_size = result_offset_with_padding + result.len;
const ac_bytes = gpa.alignedAlloc(u8, .of(AsyncClosure), allocated_size) catch {
start(context.ptr, result.ptr);
return null;
}));
};
const ac: *AsyncClosure = @ptrCast(@alignCast(ac_bytes));

ac.* = .{
.closure = .{
Expand All@@ -476,7 +482,8 @@ fn async(
},
.func = start,
.context_alignment = context_alignment,
.result_offset = result_offset,
.result_alignment = result_alignment,
.result_offset_before_padding = result_offset_before_padding,
.reset_event = .unset,
.select_condition = null,
};
Expand DownExpand Up@@ -531,10 +538,12 @@ fn concurrent(
const t: *Threaded = @ptrCast(@alignCast(userdata));
const cpu_count = t.cpu_count catch 1;
const gpa = t.allocator;
const context_offset = context_alignment.forward(@sizeOf(AsyncClosure));
const result_offset = result_alignment.forward(context_offset + context.len);
const n = result_offset + result_len;
const ac_bytes = gpa.alignedAlloc(u8, .of(AsyncClosure), n) catch
const context_offset_before_padding = @alignOf(AsyncClosure) + @sizeOf(AsyncClosure);
const context_offset_with_padding = context_alignment.forward(context_offset_before_padding);
const result_offset_before_padding = context_offset_with_padding + context.len;
const result_offset_with_padding = result_alignment.forward(result_offset_before_padding);
const allocated_size = result_offset_with_padding + result_len;
const ac_bytes = gpa.alignedAlloc(u8, .of(AsyncClosure), allocated_size) catch
return error.ConcurrencyUnavailable;
const ac: *AsyncClosure = @ptrCast(@alignCast(ac_bytes));

Expand All@@ -546,7 +555,8 @@ fn concurrent(
},
.func = start,
.context_alignment = context_alignment,
.result_offset = result_offset,
.result_alignment = result_alignment,
.result_offset_before_padding = result_offset_before_padding,
.reset_event = .unset,
.select_condition = null,
};
Expand DownExpand Up@@ -580,6 +590,8 @@ fn concurrent(
return @ptrCast(ac);
}

/// Trailing data:
/// 1. context
const GroupClosure = struct {
closure: Closure,
t: *Threaded,
Expand DownExpand Up@@ -621,17 +633,15 @@ const GroupClosure = struct {
gpa.free(base[0..contextEnd(gc.context_alignment, gc.context_len)]);
}

fn contextOffset(context_alignment: std.mem.Alignment) usize {
return context_alignment.forward(@sizeOf(GroupClosure));
}

fn contextEnd(context_alignment: std.mem.Alignment, context_len: usize) usize {
return contextOffset(context_alignment) + context_len;
const context_offset_before_padding = @alignOf(GroupClosure) + @sizeOf(GroupClosure);
const context_offset_with_padding = context_alignment.forward(context_offset_before_padding);
return context_offset_with_padding + context_len;
}

fn contextPointer(gc: *GroupClosure) [*]u8 {
const base: [*]u8 = @ptrCast(gc);
return base + contextOffset(gc.context_alignment);
return @ptrFromInt(gc.context_alignment.forward(@intFromPtr(base + @sizeOf(GroupClosure))));
}

const sync_is_waiting: usize = 1 << 0;
Expand Down
66 changes: 66 additions & 0 deletions lib/std/Io/Threaded/test.zig
Original file line numberDiff line numberDiff line change
Expand Up@@ -56,3 +56,69 @@ test "concurrent vs concurrent prevents deadlock via oversubscription" {
getter.await(io);
putter.await(io);
}

fn paramWithExtraAlignment(param: Align64) void {
assert(param.data == 3);
}

fn returnValueWithExtraAlignment() Align64 {
return .{ .data = 5 };
}

const Align64 = struct {
data: u8 align(64),
};

test "async closure where result or context has extra alignment" {
// A fixed buffer allocator is used instead of `std.testing.allocator` to
// not get memory that has better alignment than requested.
var buffer: [1024]u8 align(64) = undefined;
var fba: std.heap.FixedBufferAllocator = .init(buffer[1..]);

var threaded: std.Io.Threaded = .init(fba.allocator());
defer threaded.deinit();
const io = threaded.io();

{
var future = io.async(paramWithExtraAlignment, .{.{ .data = 3 }});
future.await(io);
}

{
var future = io.async(returnValueWithExtraAlignment, .{});
const result = future.await(io);
try std.testing.expectEqual(5, result.data);
}
}

test "group closure where context has extra alignment" {
// A fixed buffer allocator is used instead of `std.testing.allocator` to
// not get memory that has better alignment than requested.
var buffer: [1024]u8 align(64) = undefined;
var fba: std.heap.FixedBufferAllocator = .init(buffer[1..]);

var threaded: std.Io.Threaded = .init(fba.allocator());
defer threaded.deinit();
const io = threaded.io();

var group: std.Io.Group = .init;
defer group.cancel(io);

group.async(io, paramWithExtraAlignment, .{.{ .data = 3 }});
}

fn returnArray() [32]u8 {
return @splat(5);
}

test "async on function with array parameter or return type" {
var threaded: std.Io.Threaded = .init(std.testing.allocator);
defer threaded.deinit();
const io = threaded.io();

var future = io.async(returnArray, .{});
const result = future.await(io);
for (result) |actual| {
try std.testing.expectEqual(5, actual);
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions lib/std/Io.zig
Original file line numberDiff line numberDiff line change
Expand Up@@ -990,15 +990,15 @@ pub fn Future(Result: type) type {
/// Idempotent. Not threadsafe.
pub fn cancel(f: *@This(), io: Io) Result {
const any_future = f.any_future orelse return f.result;
io.vtable.cancel(io.userdata, any_future, @ptrCast((&f.result)[0..1]), .of(Result));
io.vtable.cancel(io.userdata, any_future, @ptrCast(&f.result), .of(Result));
f.any_future = null;
return f.result;
}

/// Idempotent. Not threadsafe.
pub fn await(f: *@This(), io: Io) Result {
const any_future = f.any_future orelse return f.result;
io.vtable.await(io.userdata, any_future, @ptrCast((&f.result)[0..1]), .of(Result));
io.vtable.await(io.userdata, any_future, @ptrCast(&f.result), .of(Result));
f.any_future = null;
return f.result;
}
Expand DownExpand Up@@ -1034,7 +1034,7 @@ pub const Group = struct {
@call(.auto, function, args_casted.*);
}
};
io.vtable.groupAsync(io.userdata, g, @ptrCast((&args)[0..1]), .of(Args), TypeErased.start);
io.vtable.groupAsync(io.userdata, g, @ptrCast(&args), .of(Args), TypeErased.start);
}

/// Blocks until all tasks of the group finish. During this time,
Expand DownExpand Up@@ -1111,7 +1111,7 @@ pub fn Select(comptime U: type) type {
}
};
_ = @atomicRmw(usize, &s.outstanding, .Add, 1, .monotonic);
s.io.vtable.groupAsync(s.io.userdata, &s.group, @ptrCast((&args)[0..1]), .of(Args), TypeErased.start);
s.io.vtable.groupAsync(s.io.userdata, &s.group, @ptrCast(&args), .of(Args), TypeErased.start);
}

/// Blocks until another task of the select finishes.
Expand DownExpand Up@@ -1539,9 +1539,9 @@ pub fn async(
var future: Future(Result) = undefined;
future.any_future = io.vtable.async(
io.userdata,
@ptrCast((&future.result)[0..1]),
@ptrCast(&future.result),
.of(Result),
@ptrCast((&args)[0..1]),
@ptrCast(&args),
.of(Args),
TypeErased.start,
);
Expand DownExpand Up@@ -1580,7 +1580,7 @@ pub fn concurrent(
io.userdata,
@sizeOf(Result),
.of(Result),
@ptrCast((&args)[0..1]),
@ptrCast(&args),
.of(Args),
TypeErased.start,
);
Expand Down
52 changes: 31 additions & 21 deletions lib/std/Io/Threaded.zig
Original file line numberDiff line numberDiff line change
Expand Up@@ -388,7 +388,8 @@ const AsyncClosure = struct {
reset_event: ResetEvent,
select_condition: ?*ResetEvent,
context_alignment: std.mem.Alignment,
result_offset: usize,
result_alignment: std.mem.Alignment,
result_offset_before_padding: usize,

const done_reset_event: *ResetEvent = @ptrFromInt(@alignOf(ResetEvent));

Expand DownExpand Up@@ -420,12 +421,12 @@ const AsyncClosure = struct {

fn resultPointer(ac: *AsyncClosure) [*]u8 {
const base: [*]u8 = @ptrCast(ac);
return base + ac.result_offset;
return @ptrFromInt(ac.result_alignment.forward(@intFromPtr(base + ac.result_offset_before_padding)));
}

fn contextPointer(ac: *AsyncClosure) [*]u8 {
const base: [*]u8 = @ptrCast(ac);
return base + ac.context_alignment.forward(@sizeOf(AsyncClosure));
return @ptrFromInt(ac.context_alignment.forward(@intFromPtr(base + @sizeOf(AsyncClosure))));
}

fn waitAndFree(ac: *AsyncClosure, gpa: Allocator, result: []u8) void {
Expand All@@ -436,7 +437,9 @@ const AsyncClosure = struct {

fn free(ac: *AsyncClosure, gpa: Allocator, result_len: usize) void {
const base: [*]align(@alignOf(AsyncClosure)) u8 = @ptrCast(ac);
gpa.free(base[0 .. ac.result_offset + result_len]);
const result_offset_with_padding = ac.result_alignment.forward(ac.result_offset_before_padding);
const allocated_size = result_offset_with_padding + result_len;
gpa.free(base[0..allocated_size]);
}
};

Expand All@@ -460,13 +463,16 @@ fn async(
};
};
const gpa = t.allocator;
const context_offset = context_alignment.forward(@sizeOf(AsyncClosure));
const result_offset = result_alignment.forward(context_offset + context.len);
const n = result_offset + result.len;
const ac: *AsyncClosure = @ptrCast(@alignCast(gpa.alignedAlloc(u8, .of(AsyncClosure), n) catch {
const context_offset_before_padding = @alignOf(AsyncClosure) + @sizeOf(AsyncClosure);
const context_offset_with_padding = context_alignment.forward(context_offset_before_padding);
const result_offset_before_padding = context_offset_with_padding + context.len;
const result_offset_with_padding = result_alignment.forward(result_offset_before_padding);
const allocated_size = result_offset_with_padding + result.len;
const ac_bytes = gpa.alignedAlloc(u8, .of(AsyncClosure), allocated_size) catch {
start(context.ptr, result.ptr);
return null;
}));
};
const ac: *AsyncClosure = @ptrCast(@alignCast(ac_bytes));

ac.* = .{
.closure = .{
Expand All@@ -476,7 +482,8 @@ fn async(
},
.func = start,
.context_alignment = context_alignment,
.result_offset = result_offset,
.result_alignment = result_alignment,
.result_offset_before_padding = result_offset_before_padding,
.reset_event = .unset,
.select_condition = null,
};
Expand DownExpand Up@@ -531,10 +538,12 @@ fn concurrent(
const t: *Threaded = @ptrCast(@alignCast(userdata));
const cpu_count = t.cpu_count catch 1;
const gpa = t.allocator;
const context_offset = context_alignment.forward(@sizeOf(AsyncClosure));
const result_offset = result_alignment.forward(context_offset + context.len);
const n = result_offset + result_len;
const ac_bytes = gpa.alignedAlloc(u8, .of(AsyncClosure), n) catch
const context_offset_before_padding = @alignOf(AsyncClosure) + @sizeOf(AsyncClosure);
const context_offset_with_padding = context_alignment.forward(context_offset_before_padding);
const result_offset_before_padding = context_offset_with_padding + context.len;
const result_offset_with_padding = result_alignment.forward(result_offset_before_padding);
const allocated_size = result_offset_with_padding + result_len;
const ac_bytes = gpa.alignedAlloc(u8, .of(AsyncClosure), allocated_size) catch
return error.ConcurrencyUnavailable;
const ac: *AsyncClosure = @ptrCast(@alignCast(ac_bytes));

Expand All@@ -546,7 +555,8 @@ fn concurrent(
},
.func = start,
.context_alignment = context_alignment,
.result_offset = result_offset,
.result_alignment = result_alignment,
.result_offset_before_padding = result_offset_before_padding,
.reset_event = .unset,
.select_condition = null,
};
Expand DownExpand Up@@ -580,6 +590,8 @@ fn concurrent(
return @ptrCast(ac);
}

/// Trailing data:
/// 1. context
const GroupClosure = struct {
closure: Closure,
t: *Threaded,
Expand DownExpand Up@@ -621,17 +633,15 @@ const GroupClosure = struct {
gpa.free(base[0..contextEnd(gc.context_alignment, gc.context_len)]);
}

fn contextOffset(context_alignment: std.mem.Alignment) usize {
return context_alignment.forward(@sizeOf(GroupClosure));
}

fn contextEnd(context_alignment: std.mem.Alignment, context_len: usize) usize {
return contextOffset(context_alignment) + context_len;
const context_offset_before_padding = @alignOf(GroupClosure) + @sizeOf(GroupClosure);
const context_offset_with_padding = context_alignment.forward(context_offset_before_padding);
return context_offset_with_padding + context_len;
}

fn contextPointer(gc: *GroupClosure) [*]u8 {
const base: [*]u8 = @ptrCast(gc);
return base + contextOffset(gc.context_alignment);
return @ptrFromInt(gc.context_alignment.forward(@intFromPtr(base + @sizeOf(GroupClosure))));
}

const sync_is_waiting: usize = 1 << 0;
Expand Down
66 changes: 66 additions & 0 deletions lib/std/Io/Threaded/test.zig
Original file line numberDiff line numberDiff line change
Expand Up@@ -56,3 +56,69 @@ test "concurrent vs concurrent prevents deadlock via oversubscription" {
getter.await(io);
putter.await(io);
}

fn paramWithExtraAlignment(param: Align64) void {
assert(param.data == 3);
}

fn returnValueWithExtraAlignment() Align64 {
return .{ .data = 5 };
}

const Align64 = struct {
data: u8 align(64),
};

test "async closure where result or context has extra alignment" {
// A fixed buffer allocator is used instead of `std.testing.allocator` to
// not get memory that has better alignment than requested.
var buffer: [1024]u8 align(64) = undefined;
var fba: std.heap.FixedBufferAllocator = .init(buffer[1..]);

var threaded: std.Io.Threaded = .init(fba.allocator());
defer threaded.deinit();
const io = threaded.io();

{
var future = io.async(paramWithExtraAlignment, .{.{ .data = 3 }});
future.await(io);
}

{
var future = io.async(returnValueWithExtraAlignment, .{});
const result = future.await(io);
try std.testing.expectEqual(5, result.data);
}
}

test "group closure where context has extra alignment" {
// A fixed buffer allocator is used instead of `std.testing.allocator` to
// not get memory that has better alignment than requested.
var buffer: [1024]u8 align(64) = undefined;
var fba: std.heap.FixedBufferAllocator = .init(buffer[1..]);

var threaded: std.Io.Threaded = .init(fba.allocator());
defer threaded.deinit();
const io = threaded.io();

var group: std.Io.Group = .init;
defer group.cancel(io);

group.async(io, paramWithExtraAlignment, .{.{ .data = 3 }});
}

fn returnArray() [32]u8 {
return @splat(5);
}

test "async on function with array parameter or return type" {
var threaded: std.Io.Threaded = .init(std.testing.allocator);
defer threaded.deinit();
const io = threaded.io();

var future = io.async(returnArray, .{});
const result = future.await(io);
for (result) |actual| {
try std.testing.expectEqual(5, actual);
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions lib/std/Io.zig
Original file line numberDiff line numberDiff line change
Expand Up@@ -990,15 +990,15 @@ pub fn Future(Result: type) type {
/// Idempotent. Not threadsafe.
pub fn cancel(f: *@This(), io: Io) Result {
const any_future = f.any_future orelse return f.result;
io.vtable.cancel(io.userdata, any_future, @ptrCast((&f.result)[0..1]), .of(Result));
io.vtable.cancel(io.userdata, any_future, @ptrCast(&f.result), .of(Result));
f.any_future = null;
return f.result;
}

/// Idempotent. Not threadsafe.
pub fn await(f: *@This(), io: Io) Result {
const any_future = f.any_future orelse return f.result;
io.vtable.await(io.userdata, any_future, @ptrCast((&f.result)[0..1]), .of(Result));
io.vtable.await(io.userdata, any_future, @ptrCast(&f.result), .of(Result));
f.any_future = null;
return f.result;
}
Expand DownExpand Up@@ -1034,7 +1034,7 @@ pub const Group = struct {
@call(.auto, function, args_casted.*);
}
};
io.vtable.groupAsync(io.userdata, g, @ptrCast((&args)[0..1]), .of(Args), TypeErased.start);
io.vtable.groupAsync(io.userdata, g, @ptrCast(&args), .of(Args), TypeErased.start);
}

/// Blocks until all tasks of the group finish. During this time,
Expand DownExpand Up@@ -1111,7 +1111,7 @@ pub fn Select(comptime U: type) type {
}
};
_ = @atomicRmw(usize, &s.outstanding, .Add, 1, .monotonic);
s.io.vtable.groupAsync(s.io.userdata, &s.group, @ptrCast((&args)[0..1]), .of(Args), TypeErased.start);
s.io.vtable.groupAsync(s.io.userdata, &s.group, @ptrCast(&args), .of(Args), TypeErased.start);
}

/// Blocks until another task of the select finishes.
Expand DownExpand Up@@ -1539,9 +1539,9 @@ pub fn async(
var future: Future(Result) = undefined;
future.any_future = io.vtable.async(
io.userdata,
@ptrCast((&future.result)[0..1]),
@ptrCast(&future.result),
.of(Result),
@ptrCast((&args)[0..1]),
@ptrCast(&args),
.of(Args),
TypeErased.start,
);
Expand DownExpand Up@@ -1580,7 +1580,7 @@ pub fn concurrent(
io.userdata,
@sizeOf(Result),
.of(Result),
@ptrCast((&args)[0..1]),
@ptrCast(&args),
.of(Args),
TypeErased.start,
);
Expand Down
52 changes: 31 additions & 21 deletions lib/std/Io/Threaded.zig
Original file line numberDiff line numberDiff line change
Expand Up@@ -388,7 +388,8 @@ const AsyncClosure = struct {
reset_event: ResetEvent,
select_condition: ?*ResetEvent,
context_alignment: std.mem.Alignment,
result_offset: usize,
result_alignment: std.mem.Alignment,
result_offset_before_padding: usize,

const done_reset_event: *ResetEvent = @ptrFromInt(@alignOf(ResetEvent));

Expand DownExpand Up@@ -420,12 +421,12 @@ const AsyncClosure = struct {

fn resultPointer(ac: *AsyncClosure) [*]u8 {
const base: [*]u8 = @ptrCast(ac);
return base + ac.result_offset;
return @ptrFromInt(ac.result_alignment.forward(@intFromPtr(base + ac.result_offset_before_padding)));
}

fn contextPointer(ac: *AsyncClosure) [*]u8 {
const base: [*]u8 = @ptrCast(ac);
return base + ac.context_alignment.forward(@sizeOf(AsyncClosure));
return @ptrFromInt(ac.context_alignment.forward(@intFromPtr(base + @sizeOf(AsyncClosure))));
}

fn waitAndFree(ac: *AsyncClosure, gpa: Allocator, result: []u8) void {
Expand All@@ -436,7 +437,9 @@ const AsyncClosure = struct {

fn free(ac: *AsyncClosure, gpa: Allocator, result_len: usize) void {
const base: [*]align(@alignOf(AsyncClosure)) u8 = @ptrCast(ac);
gpa.free(base[0 .. ac.result_offset + result_len]);
const result_offset_with_padding = ac.result_alignment.forward(ac.result_offset_before_padding);
const allocated_size = result_offset_with_padding + result_len;
gpa.free(base[0..allocated_size]);
}
};

Expand All@@ -460,13 +463,16 @@ fn async(
};
};
const gpa = t.allocator;
const context_offset = context_alignment.forward(@sizeOf(AsyncClosure));
const result_offset = result_alignment.forward(context_offset + context.len);
const n = result_offset + result.len;
const ac: *AsyncClosure = @ptrCast(@alignCast(gpa.alignedAlloc(u8, .of(AsyncClosure), n) catch {
const context_offset_before_padding = @alignOf(AsyncClosure) + @sizeOf(AsyncClosure);
const context_offset_with_padding = context_alignment.forward(context_offset_before_padding);
const result_offset_before_padding = context_offset_with_padding + context.len;
const result_offset_with_padding = result_alignment.forward(result_offset_before_padding);
const allocated_size = result_offset_with_padding + result.len;
const ac_bytes = gpa.alignedAlloc(u8, .of(AsyncClosure), allocated_size) catch {
start(context.ptr, result.ptr);
return null;
}));
};
const ac: *AsyncClosure = @ptrCast(@alignCast(ac_bytes));

ac.* = .{
.closure = .{
Expand All@@ -476,7 +482,8 @@ fn async(
},
.func = start,
.context_alignment = context_alignment,
.result_offset = result_offset,
.result_alignment = result_alignment,
.result_offset_before_padding = result_offset_before_padding,
.reset_event = .unset,
.select_condition = null,
};
Expand DownExpand Up@@ -531,10 +538,12 @@ fn concurrent(
const t: *Threaded = @ptrCast(@alignCast(userdata));
const cpu_count = t.cpu_count catch 1;
const gpa = t.allocator;
const context_offset = context_alignment.forward(@sizeOf(AsyncClosure));
const result_offset = result_alignment.forward(context_offset + context.len);
const n = result_offset + result_len;
const ac_bytes = gpa.alignedAlloc(u8, .of(AsyncClosure), n) catch
const context_offset_before_padding = @alignOf(AsyncClosure) + @sizeOf(AsyncClosure);
const context_offset_with_padding = context_alignment.forward(context_offset_before_padding);
const result_offset_before_padding = context_offset_with_padding + context.len;
const result_offset_with_padding = result_alignment.forward(result_offset_before_padding);
const allocated_size = result_offset_with_padding + result_len;
const ac_bytes = gpa.alignedAlloc(u8, .of(AsyncClosure), allocated_size) catch
return error.ConcurrencyUnavailable;
const ac: *AsyncClosure = @ptrCast(@alignCast(ac_bytes));

Expand All@@ -546,7 +555,8 @@ fn concurrent(
},
.func = start,
.context_alignment = context_alignment,
.result_offset = result_offset,
.result_alignment = result_alignment,
.result_offset_before_padding = result_offset_before_padding,
.reset_event = .unset,
.select_condition = null,
};
Expand DownExpand Up@@ -580,6 +590,8 @@ fn concurrent(
return @ptrCast(ac);
}

/// Trailing data:
/// 1. context
const GroupClosure = struct {
closure: Closure,
t: *Threaded,
Expand DownExpand Up@@ -621,17 +633,15 @@ const GroupClosure = struct {
gpa.free(base[0..contextEnd(gc.context_alignment, gc.context_len)]);
}

fn contextOffset(context_alignment: std.mem.Alignment) usize {
return context_alignment.forward(@sizeOf(GroupClosure));
}

fn contextEnd(context_alignment: std.mem.Alignment, context_len: usize) usize {
return contextOffset(context_alignment) + context_len;
const context_offset_before_padding = @alignOf(GroupClosure) + @sizeOf(GroupClosure);
const context_offset_with_padding = context_alignment.forward(context_offset_before_padding);
return context_offset_with_padding + context_len;
}

fn contextPointer(gc: *GroupClosure) [*]u8 {
const base: [*]u8 = @ptrCast(gc);
return base + contextOffset(gc.context_alignment);
return @ptrFromInt(gc.context_alignment.forward(@intFromPtr(base + @sizeOf(GroupClosure))));
}

const sync_is_waiting: usize = 1 << 0;
Expand Down
66 changes: 66 additions & 0 deletions lib/std/Io/Threaded/test.zig
Original file line numberDiff line numberDiff line change
Expand Up@@ -56,3 +56,69 @@ test "concurrent vs concurrent prevents deadlock via oversubscription" {
getter.await(io);
putter.await(io);
}

fn paramWithExtraAlignment(param: Align64) void {
assert(param.data == 3);
}

fn returnValueWithExtraAlignment() Align64 {
return .{ .data = 5 };
}

const Align64 = struct {
data: u8 align(64),
};

test "async closure where result or context has extra alignment" {
// A fixed buffer allocator is used instead of `std.testing.allocator` to
// not get memory that has better alignment than requested.
var buffer: [1024]u8 align(64) = undefined;
var fba: std.heap.FixedBufferAllocator = .init(buffer[1..]);

var threaded: std.Io.Threaded = .init(fba.allocator());
defer threaded.deinit();
const io = threaded.io();

{
var future = io.async(paramWithExtraAlignment, .{.{ .data = 3 }});
future.await(io);
}

{
var future = io.async(returnValueWithExtraAlignment, .{});
const result = future.await(io);
try std.testing.expectEqual(5, result.data);
}
}

test "group closure where context has extra alignment" {
// A fixed buffer allocator is used instead of `std.testing.allocator` to
// not get memory that has better alignment than requested.
var buffer: [1024]u8 align(64) = undefined;
var fba: std.heap.FixedBufferAllocator = .init(buffer[1..]);

var threaded: std.Io.Threaded = .init(fba.allocator());
defer threaded.deinit();
const io = threaded.io();

var group: std.Io.Group = .init;
defer group.cancel(io);

group.async(io, paramWithExtraAlignment, .{.{ .data = 3 }});
}

fn returnArray() [32]u8 {
return @splat(5);
}

test "async on function with array parameter or return type" {
var threaded: std.Io.Threaded = .init(std.testing.allocator);
defer threaded.deinit();
const io = threaded.io();

var future = io.async(returnArray, .{});
const result = future.await(io);
for (result) |actual| {
try std.testing.expectEqual(5, actual);
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions lib/std/Io.zig
Original file line numberDiff line numberDiff line change
Expand Up@@ -990,15 +990,15 @@ pub fn Future(Result: type) type {
/// Idempotent. Not threadsafe.
pub fn cancel(f: *@This(), io: Io) Result {
const any_future = f.any_future orelse return f.result;
io.vtable.cancel(io.userdata, any_future, @ptrCast((&f.result)[0..1]), .of(Result));
io.vtable.cancel(io.userdata, any_future, @ptrCast(&f.result), .of(Result));
f.any_future = null;
return f.result;
}

/// Idempotent. Not threadsafe.
pub fn await(f: *@This(), io: Io) Result {
const any_future = f.any_future orelse return f.result;
io.vtable.await(io.userdata, any_future, @ptrCast((&f.result)[0..1]), .of(Result));
io.vtable.await(io.userdata, any_future, @ptrCast(&f.result), .of(Result));
f.any_future = null;
return f.result;
}
Expand DownExpand Up@@ -1034,7 +1034,7 @@ pub const Group = struct {
@call(.auto, function, args_casted.*);
}
};
io.vtable.groupAsync(io.userdata, g, @ptrCast((&args)[0..1]), .of(Args), TypeErased.start);
io.vtable.groupAsync(io.userdata, g, @ptrCast(&args), .of(Args), TypeErased.start);
}

/// Blocks until all tasks of the group finish. During this time,
Expand DownExpand Up@@ -1111,7 +1111,7 @@ pub fn Select(comptime U: type) type {
}
};
_ = @atomicRmw(usize, &s.outstanding, .Add, 1, .monotonic);
s.io.vtable.groupAsync(s.io.userdata, &s.group, @ptrCast((&args)[0..1]), .of(Args), TypeErased.start);
s.io.vtable.groupAsync(s.io.userdata, &s.group, @ptrCast(&args), .of(Args), TypeErased.start);
}

/// Blocks until another task of the select finishes.
Expand DownExpand Up@@ -1539,9 +1539,9 @@ pub fn async(
var future: Future(Result) = undefined;
future.any_future = io.vtable.async(
io.userdata,
@ptrCast((&future.result)[0..1]),
@ptrCast(&future.result),
.of(Result),
@ptrCast((&args)[0..1]),
@ptrCast(&args),
.of(Args),
TypeErased.start,
);
Expand DownExpand Up@@ -1580,7 +1580,7 @@ pub fn concurrent(
io.userdata,
@sizeOf(Result),
.of(Result),
@ptrCast((&args)[0..1]),
@ptrCast(&args),
.of(Args),
TypeErased.start,
);
Expand Down
52 changes: 31 additions & 21 deletions lib/std/Io/Threaded.zig
Original file line numberDiff line numberDiff line change
Expand Up@@ -388,7 +388,8 @@ const AsyncClosure = struct {
reset_event: ResetEvent,
select_condition: ?*ResetEvent,
context_alignment: std.mem.Alignment,
result_offset: usize,
result_alignment: std.mem.Alignment,
result_offset_before_padding: usize,

const done_reset_event: *ResetEvent = @ptrFromInt(@alignOf(ResetEvent));

Expand DownExpand Up@@ -420,12 +421,12 @@ const AsyncClosure = struct {

fn resultPointer(ac: *AsyncClosure) [*]u8 {
const base: [*]u8 = @ptrCast(ac);
return base + ac.result_offset;
return @ptrFromInt(ac.result_alignment.forward(@intFromPtr(base + ac.result_offset_before_padding)));
}

fn contextPointer(ac: *AsyncClosure) [*]u8 {
const base: [*]u8 = @ptrCast(ac);
return base + ac.context_alignment.forward(@sizeOf(AsyncClosure));
return @ptrFromInt(ac.context_alignment.forward(@intFromPtr(base + @sizeOf(AsyncClosure))));
}

fn waitAndFree(ac: *AsyncClosure, gpa: Allocator, result: []u8) void {
Expand All@@ -436,7 +437,9 @@ const AsyncClosure = struct {

fn free(ac: *AsyncClosure, gpa: Allocator, result_len: usize) void {
const base: [*]align(@alignOf(AsyncClosure)) u8 = @ptrCast(ac);
gpa.free(base[0 .. ac.result_offset + result_len]);
const result_offset_with_padding = ac.result_alignment.forward(ac.result_offset_before_padding);
const allocated_size = result_offset_with_padding + result_len;
gpa.free(base[0..allocated_size]);
}
};

Expand All@@ -460,13 +463,16 @@ fn async(
};
};
const gpa = t.allocator;
const context_offset = context_alignment.forward(@sizeOf(AsyncClosure));
const result_offset = result_alignment.forward(context_offset + context.len);
const n = result_offset + result.len;
const ac: *AsyncClosure = @ptrCast(@alignCast(gpa.alignedAlloc(u8, .of(AsyncClosure), n) catch {
const context_offset_before_padding = @alignOf(AsyncClosure) + @sizeOf(AsyncClosure);
const context_offset_with_padding = context_alignment.forward(context_offset_before_padding);
const result_offset_before_padding = context_offset_with_padding + context.len;
const result_offset_with_padding = result_alignment.forward(result_offset_before_padding);
const allocated_size = result_offset_with_padding + result.len;
const ac_bytes = gpa.alignedAlloc(u8, .of(AsyncClosure), allocated_size) catch {
start(context.ptr, result.ptr);
return null;
}));
};
const ac: *AsyncClosure = @ptrCast(@alignCast(ac_bytes));

ac.* = .{
.closure = .{
Expand All@@ -476,7 +482,8 @@ fn async(
},
.func = start,
.context_alignment = context_alignment,
.result_offset = result_offset,
.result_alignment = result_alignment,
.result_offset_before_padding = result_offset_before_padding,
.reset_event = .unset,
.select_condition = null,
};
Expand DownExpand Up@@ -531,10 +538,12 @@ fn concurrent(
const t: *Threaded = @ptrCast(@alignCast(userdata));
const cpu_count = t.cpu_count catch 1;
const gpa = t.allocator;
const context_offset = context_alignment.forward(@sizeOf(AsyncClosure));
const result_offset = result_alignment.forward(context_offset + context.len);
const n = result_offset + result_len;
const ac_bytes = gpa.alignedAlloc(u8, .of(AsyncClosure), n) catch
const context_offset_before_padding = @alignOf(AsyncClosure) + @sizeOf(AsyncClosure);
const context_offset_with_padding = context_alignment.forward(context_offset_before_padding);
const result_offset_before_padding = context_offset_with_padding + context.len;
const result_offset_with_padding = result_alignment.forward(result_offset_before_padding);
const allocated_size = result_offset_with_padding + result_len;
const ac_bytes = gpa.alignedAlloc(u8, .of(AsyncClosure), allocated_size) catch
return error.ConcurrencyUnavailable;
const ac: *AsyncClosure = @ptrCast(@alignCast(ac_bytes));

Expand All@@ -546,7 +555,8 @@ fn concurrent(
},
.func = start,
.context_alignment = context_alignment,
.result_offset = result_offset,
.result_alignment = result_alignment,
.result_offset_before_padding = result_offset_before_padding,
.reset_event = .unset,
.select_condition = null,
};
Expand DownExpand Up@@ -580,6 +590,8 @@ fn concurrent(
return @ptrCast(ac);
}

/// Trailing data:
/// 1. context
const GroupClosure = struct {
closure: Closure,
t: *Threaded,
Expand DownExpand Up@@ -621,17 +633,15 @@ const GroupClosure = struct {
gpa.free(base[0..contextEnd(gc.context_alignment, gc.context_len)]);
}

fn contextOffset(context_alignment: std.mem.Alignment) usize {
return context_alignment.forward(@sizeOf(GroupClosure));
}

fn contextEnd(context_alignment: std.mem.Alignment, context_len: usize) usize {
return contextOffset(context_alignment) + context_len;
const context_offset_before_padding = @alignOf(GroupClosure) + @sizeOf(GroupClosure);
const context_offset_with_padding = context_alignment.forward(context_offset_before_padding);
return context_offset_with_padding + context_len;
}

fn contextPointer(gc: *GroupClosure) [*]u8 {
const base: [*]u8 = @ptrCast(gc);
return base + contextOffset(gc.context_alignment);
return @ptrFromInt(gc.context_alignment.forward(@intFromPtr(base + @sizeOf(GroupClosure))));
}

const sync_is_waiting: usize = 1 << 0;
Expand Down
66 changes: 66 additions & 0 deletions lib/std/Io/Threaded/test.zig
Original file line numberDiff line numberDiff line change
Expand Up@@ -56,3 +56,69 @@ test "concurrent vs concurrent prevents deadlock via oversubscription" {
getter.await(io);
putter.await(io);
}

fn paramWithExtraAlignment(param: Align64) void {
assert(param.data == 3);
}

fn returnValueWithExtraAlignment() Align64 {
return .{ .data = 5 };
}

const Align64 = struct {
data: u8 align(64),
};

test "async closure where result or context has extra alignment" {
// A fixed buffer allocator is used instead of `std.testing.allocator` to
// not get memory that has better alignment than requested.
var buffer: [1024]u8 align(64) = undefined;
var fba: std.heap.FixedBufferAllocator = .init(buffer[1..]);

var threaded: std.Io.Threaded = .init(fba.allocator());
defer threaded.deinit();
const io = threaded.io();

{
var future = io.async(paramWithExtraAlignment, .{.{ .data = 3 }});
future.await(io);
}

{
var future = io.async(returnValueWithExtraAlignment, .{});
const result = future.await(io);
try std.testing.expectEqual(5, result.data);
}
}

test "group closure where context has extra alignment" {
// A fixed buffer allocator is used instead of `std.testing.allocator` to
// not get memory that has better alignment than requested.
var buffer: [1024]u8 align(64) = undefined;
var fba: std.heap.FixedBufferAllocator = .init(buffer[1..]);

var threaded: std.Io.Threaded = .init(fba.allocator());
defer threaded.deinit();
const io = threaded.io();

var group: std.Io.Group = .init;
defer group.cancel(io);

group.async(io, paramWithExtraAlignment, .{.{ .data = 3 }});
}

fn returnArray() [32]u8 {
return @splat(5);
}

test "async on function with array parameter or return type" {
var threaded: std.Io.Threaded = .init(std.testing.allocator);
defer threaded.deinit();
const io = threaded.io();

var future = io.async(returnArray, .{});
const result = future.await(io);
for (result) |actual| {
try std.testing.expectEqual(5, actual);
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions lib/std/Io.zig
Original file line numberDiff line numberDiff line change
Expand Up@@ -990,15 +990,15 @@ pub fn Future(Result: type) type {
/// Idempotent. Not threadsafe.
pub fn cancel(f: *@This(), io: Io) Result {
const any_future = f.any_future orelse return f.result;
io.vtable.cancel(io.userdata, any_future, @ptrCast((&f.result)[0..1]), .of(Result));
io.vtable.cancel(io.userdata, any_future, @ptrCast(&f.result), .of(Result));
f.any_future = null;
return f.result;
}

/// Idempotent. Not threadsafe.
pub fn await(f: *@This(), io: Io) Result {
const any_future = f.any_future orelse return f.result;
io.vtable.await(io.userdata, any_future, @ptrCast((&f.result)[0..1]), .of(Result));
io.vtable.await(io.userdata, any_future, @ptrCast(&f.result), .of(Result));
f.any_future = null;
return f.result;
}
Expand DownExpand Up@@ -1034,7 +1034,7 @@ pub const Group = struct {
@call(.auto, function, args_casted.*);
}
};
io.vtable.groupAsync(io.userdata, g, @ptrCast((&args)[0..1]), .of(Args), TypeErased.start);
io.vtable.groupAsync(io.userdata, g, @ptrCast(&args), .of(Args), TypeErased.start);
}

/// Blocks until all tasks of the group finish. During this time,
Expand DownExpand Up@@ -1111,7 +1111,7 @@ pub fn Select(comptime U: type) type {
}
};
_ = @atomicRmw(usize, &s.outstanding, .Add, 1, .monotonic);
s.io.vtable.groupAsync(s.io.userdata, &s.group, @ptrCast((&args)[0..1]), .of(Args), TypeErased.start);
s.io.vtable.groupAsync(s.io.userdata, &s.group, @ptrCast(&args), .of(Args), TypeErased.start);
}

/// Blocks until another task of the select finishes.
Expand DownExpand Up@@ -1539,9 +1539,9 @@ pub fn async(
var future: Future(Result) = undefined;
future.any_future = io.vtable.async(
io.userdata,
@ptrCast((&future.result)[0..1]),
@ptrCast(&future.result),
.of(Result),
@ptrCast((&args)[0..1]),
@ptrCast(&args),
.of(Args),
TypeErased.start,
);
Expand DownExpand Up@@ -1580,7 +1580,7 @@ pub fn concurrent(
io.userdata,
@sizeOf(Result),
.of(Result),
@ptrCast((&args)[0..1]),
@ptrCast(&args),
.of(Args),
TypeErased.start,
);
Expand Down
52 changes: 31 additions & 21 deletions lib/std/Io/Threaded.zig
Original file line numberDiff line numberDiff line change
Expand Up@@ -388,7 +388,8 @@ const AsyncClosure = struct {
reset_event: ResetEvent,
select_condition: ?*ResetEvent,
context_alignment: std.mem.Alignment,
result_offset: usize,
result_alignment: std.mem.Alignment,
result_offset_before_padding: usize,

const done_reset_event: *ResetEvent = @ptrFromInt(@alignOf(ResetEvent));

Expand DownExpand Up@@ -420,12 +421,12 @@ const AsyncClosure = struct {

fn resultPointer(ac: *AsyncClosure) [*]u8 {
const base: [*]u8 = @ptrCast(ac);
return base + ac.result_offset;
return @ptrFromInt(ac.result_alignment.forward(@intFromPtr(base + ac.result_offset_before_padding)));
}

fn contextPointer(ac: *AsyncClosure) [*]u8 {
const base: [*]u8 = @ptrCast(ac);
return base + ac.context_alignment.forward(@sizeOf(AsyncClosure));
return @ptrFromInt(ac.context_alignment.forward(@intFromPtr(base + @sizeOf(AsyncClosure))));
}

fn waitAndFree(ac: *AsyncClosure, gpa: Allocator, result: []u8) void {
Expand All@@ -436,7 +437,9 @@ const AsyncClosure = struct {

fn free(ac: *AsyncClosure, gpa: Allocator, result_len: usize) void {
const base: [*]align(@alignOf(AsyncClosure)) u8 = @ptrCast(ac);
gpa.free(base[0 .. ac.result_offset + result_len]);
const result_offset_with_padding = ac.result_alignment.forward(ac.result_offset_before_padding);
const allocated_size = result_offset_with_padding + result_len;
gpa.free(base[0..allocated_size]);
}
};

Expand All@@ -460,13 +463,16 @@ fn async(
};
};
const gpa = t.allocator;
const context_offset = context_alignment.forward(@sizeOf(AsyncClosure));
const result_offset = result_alignment.forward(context_offset + context.len);
const n = result_offset + result.len;
const ac: *AsyncClosure = @ptrCast(@alignCast(gpa.alignedAlloc(u8, .of(AsyncClosure), n) catch {
const context_offset_before_padding = @alignOf(AsyncClosure) + @sizeOf(AsyncClosure);
const context_offset_with_padding = context_alignment.forward(context_offset_before_padding);
const result_offset_before_padding = context_offset_with_padding + context.len;
const result_offset_with_padding = result_alignment.forward(result_offset_before_padding);
const allocated_size = result_offset_with_padding + result.len;
const ac_bytes = gpa.alignedAlloc(u8, .of(AsyncClosure), allocated_size) catch {
start(context.ptr, result.ptr);
return null;
}));
};
const ac: *AsyncClosure = @ptrCast(@alignCast(ac_bytes));

ac.* = .{
.closure = .{
Expand All@@ -476,7 +482,8 @@ fn async(
},
.func = start,
.context_alignment = context_alignment,
.result_offset = result_offset,
.result_alignment = result_alignment,
.result_offset_before_padding = result_offset_before_padding,
.reset_event = .unset,
.select_condition = null,
};
Expand DownExpand Up@@ -531,10 +538,12 @@ fn concurrent(
const t: *Threaded = @ptrCast(@alignCast(userdata));
const cpu_count = t.cpu_count catch 1;
const gpa = t.allocator;
const context_offset = context_alignment.forward(@sizeOf(AsyncClosure));
const result_offset = result_alignment.forward(context_offset + context.len);
const n = result_offset + result_len;
const ac_bytes = gpa.alignedAlloc(u8, .of(AsyncClosure), n) catch
const context_offset_before_padding = @alignOf(AsyncClosure) + @sizeOf(AsyncClosure);
const context_offset_with_padding = context_alignment.forward(context_offset_before_padding);
const result_offset_before_padding = context_offset_with_padding + context.len;
const result_offset_with_padding = result_alignment.forward(result_offset_before_padding);
const allocated_size = result_offset_with_padding + result_len;
const ac_bytes = gpa.alignedAlloc(u8, .of(AsyncClosure), allocated_size) catch
return error.ConcurrencyUnavailable;
const ac: *AsyncClosure = @ptrCast(@alignCast(ac_bytes));

Expand All@@ -546,7 +555,8 @@ fn concurrent(
},
.func = start,
.context_alignment = context_alignment,
.result_offset = result_offset,
.result_alignment = result_alignment,
.result_offset_before_padding = result_offset_before_padding,
.reset_event = .unset,
.select_condition = null,
};
Expand DownExpand Up@@ -580,6 +590,8 @@ fn concurrent(
return @ptrCast(ac);
}

/// Trailing data:
/// 1. context
const GroupClosure = struct {
closure: Closure,
t: *Threaded,
Expand DownExpand Up@@ -621,17 +633,15 @@ const GroupClosure = struct {
gpa.free(base[0..contextEnd(gc.context_alignment, gc.context_len)]);
}

fn contextOffset(context_alignment: std.mem.Alignment) usize {
return context_alignment.forward(@sizeOf(GroupClosure));
}

fn contextEnd(context_alignment: std.mem.Alignment, context_len: usize) usize {
return contextOffset(context_alignment) + context_len;
const context_offset_before_padding = @alignOf(GroupClosure) + @sizeOf(GroupClosure);
const context_offset_with_padding = context_alignment.forward(context_offset_before_padding);
return context_offset_with_padding + context_len;
}

fn contextPointer(gc: *GroupClosure) [*]u8 {
const base: [*]u8 = @ptrCast(gc);
return base + contextOffset(gc.context_alignment);
return @ptrFromInt(gc.context_alignment.forward(@intFromPtr(base + @sizeOf(GroupClosure))));
}

const sync_is_waiting: usize = 1 << 0;
Expand Down
66 changes: 66 additions & 0 deletions lib/std/Io/Threaded/test.zig
Original file line numberDiff line numberDiff line change
Expand Up@@ -56,3 +56,69 @@ test "concurrent vs concurrent prevents deadlock via oversubscription" {
getter.await(io);
putter.await(io);
}

fn paramWithExtraAlignment(param: Align64) void {
assert(param.data == 3);
}

fn returnValueWithExtraAlignment() Align64 {
return .{ .data = 5 };
}

const Align64 = struct {
data: u8 align(64),
};

test "async closure where result or context has extra alignment" {
// A fixed buffer allocator is used instead of `std.testing.allocator` to
// not get memory that has better alignment than requested.
var buffer: [1024]u8 align(64) = undefined;
var fba: std.heap.FixedBufferAllocator = .init(buffer[1..]);

var threaded: std.Io.Threaded = .init(fba.allocator());
defer threaded.deinit();
const io = threaded.io();

{
var future = io.async(paramWithExtraAlignment, .{.{ .data = 3 }});
future.await(io);
}

{
var future = io.async(returnValueWithExtraAlignment, .{});
const result = future.await(io);
try std.testing.expectEqual(5, result.data);
}
}

test "group closure where context has extra alignment" {
// A fixed buffer allocator is used instead of `std.testing.allocator` to
// not get memory that has better alignment than requested.
var buffer: [1024]u8 align(64) = undefined;
var fba: std.heap.FixedBufferAllocator = .init(buffer[1..]);

var threaded: std.Io.Threaded = .init(fba.allocator());
defer threaded.deinit();
const io = threaded.io();

var group: std.Io.Group = .init;
defer group.cancel(io);

group.async(io, paramWithExtraAlignment, .{.{ .data = 3 }});
}

fn returnArray() [32]u8 {
return @splat(5);
}

test "async on function with array parameter or return type" {
var threaded: std.Io.Threaded = .init(std.testing.allocator);
defer threaded.deinit();
const io = threaded.io();

var future = io.async(returnArray, .{});
const result = future.await(io);
for (result) |actual| {
try std.testing.expectEqual(5, actual);
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions lib/std/Io.zig
Original file line numberDiff line numberDiff line change
Expand Up@@ -990,15 +990,15 @@ pub fn Future(Result: type) type {
/// Idempotent. Not threadsafe.
pub fn cancel(f: *@This(), io: Io) Result {
const any_future = f.any_future orelse return f.result;
io.vtable.cancel(io.userdata, any_future, @ptrCast((&f.result)[0..1]), .of(Result));
io.vtable.cancel(io.userdata, any_future, @ptrCast(&f.result), .of(Result));
f.any_future = null;
return f.result;
}

/// Idempotent. Not threadsafe.
pub fn await(f: *@This(), io: Io) Result {
const any_future = f.any_future orelse return f.result;
io.vtable.await(io.userdata, any_future, @ptrCast((&f.result)[0..1]), .of(Result));
io.vtable.await(io.userdata, any_future, @ptrCast(&f.result), .of(Result));
f.any_future = null;
return f.result;
}
Expand DownExpand Up@@ -1034,7 +1034,7 @@ pub const Group = struct {
@call(.auto, function, args_casted.*);
}
};
io.vtable.groupAsync(io.userdata, g, @ptrCast((&args)[0..1]), .of(Args), TypeErased.start);
io.vtable.groupAsync(io.userdata, g, @ptrCast(&args), .of(Args), TypeErased.start);
}

/// Blocks until all tasks of the group finish. During this time,
Expand DownExpand Up@@ -1111,7 +1111,7 @@ pub fn Select(comptime U: type) type {
}
};
_ = @atomicRmw(usize, &s.outstanding, .Add, 1, .monotonic);
s.io.vtable.groupAsync(s.io.userdata, &s.group, @ptrCast((&args)[0..1]), .of(Args), TypeErased.start);
s.io.vtable.groupAsync(s.io.userdata, &s.group, @ptrCast(&args), .of(Args), TypeErased.start);
}

/// Blocks until another task of the select finishes.
Expand DownExpand Up@@ -1539,9 +1539,9 @@ pub fn async(
var future: Future(Result) = undefined;
future.any_future = io.vtable.async(
io.userdata,
@ptrCast((&future.result)[0..1]),
@ptrCast(&future.result),
.of(Result),
@ptrCast((&args)[0..1]),
@ptrCast(&args),
.of(Args),
TypeErased.start,
);
Expand DownExpand Up@@ -1580,7 +1580,7 @@ pub fn concurrent(
io.userdata,
@sizeOf(Result),
.of(Result),
@ptrCast((&args)[0..1]),
@ptrCast(&args),
.of(Args),
TypeErased.start,
);
Expand Down
52 changes: 31 additions & 21 deletions lib/std/Io/Threaded.zig
Original file line numberDiff line numberDiff line change
Expand Up@@ -388,7 +388,8 @@ const AsyncClosure = struct {
reset_event: ResetEvent,
select_condition: ?*ResetEvent,
context_alignment: std.mem.Alignment,
result_offset: usize,
result_alignment: std.mem.Alignment,
result_offset_before_padding: usize,

const done_reset_event: *ResetEvent = @ptrFromInt(@alignOf(ResetEvent));

Expand DownExpand Up@@ -420,12 +421,12 @@ const AsyncClosure = struct {

fn resultPointer(ac: *AsyncClosure) [*]u8 {
const base: [*]u8 = @ptrCast(ac);
return base + ac.result_offset;
return @ptrFromInt(ac.result_alignment.forward(@intFromPtr(base + ac.result_offset_before_padding)));
}

fn contextPointer(ac: *AsyncClosure) [*]u8 {
const base: [*]u8 = @ptrCast(ac);
return base + ac.context_alignment.forward(@sizeOf(AsyncClosure));
return @ptrFromInt(ac.context_alignment.forward(@intFromPtr(base + @sizeOf(AsyncClosure))));
}

fn waitAndFree(ac: *AsyncClosure, gpa: Allocator, result: []u8) void {
Expand All@@ -436,7 +437,9 @@ const AsyncClosure = struct {

fn free(ac: *AsyncClosure, gpa: Allocator, result_len: usize) void {
const base: [*]align(@alignOf(AsyncClosure)) u8 = @ptrCast(ac);
gpa.free(base[0 .. ac.result_offset + result_len]);
const result_offset_with_padding = ac.result_alignment.forward(ac.result_offset_before_padding);
const allocated_size = result_offset_with_padding + result_len;
gpa.free(base[0..allocated_size]);
}
};

Expand All@@ -460,13 +463,16 @@ fn async(
};
};
const gpa = t.allocator;
const context_offset = context_alignment.forward(@sizeOf(AsyncClosure));
const result_offset = result_alignment.forward(context_offset + context.len);
const n = result_offset + result.len;
const ac: *AsyncClosure = @ptrCast(@alignCast(gpa.alignedAlloc(u8, .of(AsyncClosure), n) catch {
const context_offset_before_padding = @alignOf(AsyncClosure) + @sizeOf(AsyncClosure);
const context_offset_with_padding = context_alignment.forward(context_offset_before_padding);
const result_offset_before_padding = context_offset_with_padding + context.len;
const result_offset_with_padding = result_alignment.forward(result_offset_before_padding);
const allocated_size = result_offset_with_padding + result.len;
const ac_bytes = gpa.alignedAlloc(u8, .of(AsyncClosure), allocated_size) catch {
start(context.ptr, result.ptr);
return null;
}));
};
const ac: *AsyncClosure = @ptrCast(@alignCast(ac_bytes));

ac.* = .{
.closure = .{
Expand All@@ -476,7 +482,8 @@ fn async(
},
.func = start,
.context_alignment = context_alignment,
.result_offset = result_offset,
.result_alignment = result_alignment,
.result_offset_before_padding = result_offset_before_padding,
.reset_event = .unset,
.select_condition = null,
};
Expand DownExpand Up@@ -531,10 +538,12 @@ fn concurrent(
const t: *Threaded = @ptrCast(@alignCast(userdata));
const cpu_count = t.cpu_count catch 1;
const gpa = t.allocator;
const context_offset = context_alignment.forward(@sizeOf(AsyncClosure));
const result_offset = result_alignment.forward(context_offset + context.len);
const n = result_offset + result_len;
const ac_bytes = gpa.alignedAlloc(u8, .of(AsyncClosure), n) catch
const context_offset_before_padding = @alignOf(AsyncClosure) + @sizeOf(AsyncClosure);
const context_offset_with_padding = context_alignment.forward(context_offset_before_padding);
const result_offset_before_padding = context_offset_with_padding + context.len;
const result_offset_with_padding = result_alignment.forward(result_offset_before_padding);
const allocated_size = result_offset_with_padding + result_len;
const ac_bytes = gpa.alignedAlloc(u8, .of(AsyncClosure), allocated_size) catch
return error.ConcurrencyUnavailable;
const ac: *AsyncClosure = @ptrCast(@alignCast(ac_bytes));

Expand All@@ -546,7 +555,8 @@ fn concurrent(
},
.func = start,
.context_alignment = context_alignment,
.result_offset = result_offset,
.result_alignment = result_alignment,
.result_offset_before_padding = result_offset_before_padding,
.reset_event = .unset,
.select_condition = null,
};
Expand DownExpand Up@@ -580,6 +590,8 @@ fn concurrent(
return @ptrCast(ac);
}

/// Trailing data:
/// 1. context
const GroupClosure = struct {
closure: Closure,
t: *Threaded,
Expand DownExpand Up@@ -621,17 +633,15 @@ const GroupClosure = struct {
gpa.free(base[0..contextEnd(gc.context_alignment, gc.context_len)]);
}

fn contextOffset(context_alignment: std.mem.Alignment) usize {
return context_alignment.forward(@sizeOf(GroupClosure));
}

fn contextEnd(context_alignment: std.mem.Alignment, context_len: usize) usize {
return contextOffset(context_alignment) + context_len;
const context_offset_before_padding = @alignOf(GroupClosure) + @sizeOf(GroupClosure);
const context_offset_with_padding = context_alignment.forward(context_offset_before_padding);
return context_offset_with_padding + context_len;
}

fn contextPointer(gc: *GroupClosure) [*]u8 {
const base: [*]u8 = @ptrCast(gc);
return base + contextOffset(gc.context_alignment);
return @ptrFromInt(gc.context_alignment.forward(@intFromPtr(base + @sizeOf(GroupClosure))));
}

const sync_is_waiting: usize = 1 << 0;
Expand Down
66 changes: 66 additions & 0 deletions lib/std/Io/Threaded/test.zig
Original file line numberDiff line numberDiff line change
Expand Up@@ -56,3 +56,69 @@ test "concurrent vs concurrent prevents deadlock via oversubscription" {
getter.await(io);
putter.await(io);
}

fn paramWithExtraAlignment(param: Align64) void {
assert(param.data == 3);
}

fn returnValueWithExtraAlignment() Align64 {
return .{ .data = 5 };
}

const Align64 = struct {
data: u8 align(64),
};

test "async closure where result or context has extra alignment" {
// A fixed buffer allocator is used instead of `std.testing.allocator` to
// not get memory that has better alignment than requested.
var buffer: [1024]u8 align(64) = undefined;
var fba: std.heap.FixedBufferAllocator = .init(buffer[1..]);

var threaded: std.Io.Threaded = .init(fba.allocator());
defer threaded.deinit();
const io = threaded.io();

{
var future = io.async(paramWithExtraAlignment, .{.{ .data = 3 }});
future.await(io);
}

{
var future = io.async(returnValueWithExtraAlignment, .{});
const result = future.await(io);
try std.testing.expectEqual(5, result.data);
}
}

test "group closure where context has extra alignment" {
// A fixed buffer allocator is used instead of `std.testing.allocator` to
// not get memory that has better alignment than requested.
var buffer: [1024]u8 align(64) = undefined;
var fba: std.heap.FixedBufferAllocator = .init(buffer[1..]);

var threaded: std.Io.Threaded = .init(fba.allocator());
defer threaded.deinit();
const io = threaded.io();

var group: std.Io.Group = .init;
defer group.cancel(io);

group.async(io, paramWithExtraAlignment, .{.{ .data = 3 }});
}

fn returnArray() [32]u8 {
return @splat(5);
}

test "async on function with array parameter or return type" {
var threaded: std.Io.Threaded = .init(std.testing.allocator);
defer threaded.deinit();
const io = threaded.io();

var future = io.async(returnArray, .{});
const result = future.await(io);
for (result) |actual| {
try std.testing.expectEqual(5, actual);
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions lib/std/Io.zig
Original file line numberDiff line numberDiff line change
Expand Up@@ -990,15 +990,15 @@ pub fn Future(Result: type) type {
/// Idempotent. Not threadsafe.
pub fn cancel(f: *@This(), io: Io) Result {
const any_future = f.any_future orelse return f.result;
io.vtable.cancel(io.userdata, any_future, @ptrCast((&f.result)[0..1]), .of(Result));
io.vtable.cancel(io.userdata, any_future, @ptrCast(&f.result), .of(Result));
f.any_future = null;
return f.result;
}

/// Idempotent. Not threadsafe.
pub fn await(f: *@This(), io: Io) Result {
const any_future = f.any_future orelse return f.result;
io.vtable.await(io.userdata, any_future, @ptrCast((&f.result)[0..1]), .of(Result));
io.vtable.await(io.userdata, any_future, @ptrCast(&f.result), .of(Result));
f.any_future = null;
return f.result;
}
Expand DownExpand Up@@ -1034,7 +1034,7 @@ pub const Group = struct {
@call(.auto, function, args_casted.*);
}
};
io.vtable.groupAsync(io.userdata, g, @ptrCast((&args)[0..1]), .of(Args), TypeErased.start);
io.vtable.groupAsync(io.userdata, g, @ptrCast(&args), .of(Args), TypeErased.start);
}

/// Blocks until all tasks of the group finish. During this time,
Expand DownExpand Up@@ -1111,7 +1111,7 @@ pub fn Select(comptime U: type) type {
}
};
_ = @atomicRmw(usize, &s.outstanding, .Add, 1, .monotonic);
s.io.vtable.groupAsync(s.io.userdata, &s.group, @ptrCast((&args)[0..1]), .of(Args), TypeErased.start);
s.io.vtable.groupAsync(s.io.userdata, &s.group, @ptrCast(&args), .of(Args), TypeErased.start);
}

/// Blocks until another task of the select finishes.
Expand DownExpand Up@@ -1539,9 +1539,9 @@ pub fn async(
var future: Future(Result) = undefined;
future.any_future = io.vtable.async(
io.userdata,
@ptrCast((&future.result)[0..1]),
@ptrCast(&future.result),
.of(Result),
@ptrCast((&args)[0..1]),
@ptrCast(&args),
.of(Args),
TypeErased.start,
);
Expand DownExpand Up@@ -1580,7 +1580,7 @@ pub fn concurrent(
io.userdata,
@sizeOf(Result),
.of(Result),
@ptrCast((&args)[0..1]),
@ptrCast(&args),
.of(Args),
TypeErased.start,
);
Expand Down
52 changes: 31 additions & 21 deletions lib/std/Io/Threaded.zig
Original file line numberDiff line numberDiff line change
Expand Up@@ -388,7 +388,8 @@ const AsyncClosure = struct {
reset_event: ResetEvent,
select_condition: ?*ResetEvent,
context_alignment: std.mem.Alignment,
result_offset: usize,
result_alignment: std.mem.Alignment,
result_offset_before_padding: usize,

const done_reset_event: *ResetEvent = @ptrFromInt(@alignOf(ResetEvent));

Expand DownExpand Up@@ -420,12 +421,12 @@ const AsyncClosure = struct {

fn resultPointer(ac: *AsyncClosure) [*]u8 {
const base: [*]u8 = @ptrCast(ac);
return base + ac.result_offset;
return @ptrFromInt(ac.result_alignment.forward(@intFromPtr(base + ac.result_offset_before_padding)));
}

fn contextPointer(ac: *AsyncClosure) [*]u8 {
const base: [*]u8 = @ptrCast(ac);
return base + ac.context_alignment.forward(@sizeOf(AsyncClosure));
return @ptrFromInt(ac.context_alignment.forward(@intFromPtr(base + @sizeOf(AsyncClosure))));
}

fn waitAndFree(ac: *AsyncClosure, gpa: Allocator, result: []u8) void {
Expand All@@ -436,7 +437,9 @@ const AsyncClosure = struct {

fn free(ac: *AsyncClosure, gpa: Allocator, result_len: usize) void {
const base: [*]align(@alignOf(AsyncClosure)) u8 = @ptrCast(ac);
gpa.free(base[0 .. ac.result_offset + result_len]);
const result_offset_with_padding = ac.result_alignment.forward(ac.result_offset_before_padding);
const allocated_size = result_offset_with_padding + result_len;
gpa.free(base[0..allocated_size]);
}
};

Expand All@@ -460,13 +463,16 @@ fn async(
};
};
const gpa = t.allocator;
const context_offset = context_alignment.forward(@sizeOf(AsyncClosure));
const result_offset = result_alignment.forward(context_offset + context.len);
const n = result_offset + result.len;
const ac: *AsyncClosure = @ptrCast(@alignCast(gpa.alignedAlloc(u8, .of(AsyncClosure), n) catch {
const context_offset_before_padding = @alignOf(AsyncClosure) + @sizeOf(AsyncClosure);
const context_offset_with_padding = context_alignment.forward(context_offset_before_padding);
const result_offset_before_padding = context_offset_with_padding + context.len;
const result_offset_with_padding = result_alignment.forward(result_offset_before_padding);
const allocated_size = result_offset_with_padding + result.len;
const ac_bytes = gpa.alignedAlloc(u8, .of(AsyncClosure), allocated_size) catch {
start(context.ptr, result.ptr);
return null;
}));
};
const ac: *AsyncClosure = @ptrCast(@alignCast(ac_bytes));

ac.* = .{
.closure = .{
Expand All@@ -476,7 +482,8 @@ fn async(
},
.func = start,
.context_alignment = context_alignment,
.result_offset = result_offset,
.result_alignment = result_alignment,
.result_offset_before_padding = result_offset_before_padding,
.reset_event = .unset,
.select_condition = null,
};
Expand DownExpand Up@@ -531,10 +538,12 @@ fn concurrent(
const t: *Threaded = @ptrCast(@alignCast(userdata));
const cpu_count = t.cpu_count catch 1;
const gpa = t.allocator;
const context_offset = context_alignment.forward(@sizeOf(AsyncClosure));
const result_offset = result_alignment.forward(context_offset + context.len);
const n = result_offset + result_len;
const ac_bytes = gpa.alignedAlloc(u8, .of(AsyncClosure), n) catch
const context_offset_before_padding = @alignOf(AsyncClosure) + @sizeOf(AsyncClosure);
const context_offset_with_padding = context_alignment.forward(context_offset_before_padding);
const result_offset_before_padding = context_offset_with_padding + context.len;
const result_offset_with_padding = result_alignment.forward(result_offset_before_padding);
const allocated_size = result_offset_with_padding + result_len;
const ac_bytes = gpa.alignedAlloc(u8, .of(AsyncClosure), allocated_size) catch
return error.ConcurrencyUnavailable;
const ac: *AsyncClosure = @ptrCast(@alignCast(ac_bytes));

Expand All@@ -546,7 +555,8 @@ fn concurrent(
},
.func = start,
.context_alignment = context_alignment,
.result_offset = result_offset,
.result_alignment = result_alignment,
.result_offset_before_padding = result_offset_before_padding,
.reset_event = .unset,
.select_condition = null,
};
Expand DownExpand Up@@ -580,6 +590,8 @@ fn concurrent(
return @ptrCast(ac);
}

/// Trailing data:
/// 1. context
const GroupClosure = struct {
closure: Closure,
t: *Threaded,
Expand DownExpand Up@@ -621,17 +633,15 @@ const GroupClosure = struct {
gpa.free(base[0..contextEnd(gc.context_alignment, gc.context_len)]);
}

fn contextOffset(context_alignment: std.mem.Alignment) usize {
return context_alignment.forward(@sizeOf(GroupClosure));
}

fn contextEnd(context_alignment: std.mem.Alignment, context_len: usize) usize {
return contextOffset(context_alignment) + context_len;
const context_offset_before_padding = @alignOf(GroupClosure) + @sizeOf(GroupClosure);
const context_offset_with_padding = context_alignment.forward(context_offset_before_padding);
return context_offset_with_padding + context_len;
}

fn contextPointer(gc: *GroupClosure) [*]u8 {
const base: [*]u8 = @ptrCast(gc);
return base + contextOffset(gc.context_alignment);
return @ptrFromInt(gc.context_alignment.forward(@intFromPtr(base + @sizeOf(GroupClosure))));
}

const sync_is_waiting: usize = 1 << 0;
Expand Down
66 changes: 66 additions & 0 deletions lib/std/Io/Threaded/test.zig
Original file line numberDiff line numberDiff line change
Expand Up@@ -56,3 +56,69 @@ test "concurrent vs concurrent prevents deadlock via oversubscription" {
getter.await(io);
putter.await(io);
}

fn paramWithExtraAlignment(param: Align64) void {
assert(param.data == 3);
}

fn returnValueWithExtraAlignment() Align64 {
return .{ .data = 5 };
}

const Align64 = struct {
data: u8 align(64),
};

test "async closure where result or context has extra alignment" {
// A fixed buffer allocator is used instead of `std.testing.allocator` to
// not get memory that has better alignment than requested.
var buffer: [1024]u8 align(64) = undefined;
var fba: std.heap.FixedBufferAllocator = .init(buffer[1..]);

var threaded: std.Io.Threaded = .init(fba.allocator());
defer threaded.deinit();
const io = threaded.io();

{
var future = io.async(paramWithExtraAlignment, .{.{ .data = 3 }});
future.await(io);
}

{
var future = io.async(returnValueWithExtraAlignment, .{});
const result = future.await(io);
try std.testing.expectEqual(5, result.data);
}
}

test "group closure where context has extra alignment" {
// A fixed buffer allocator is used instead of `std.testing.allocator` to
// not get memory that has better alignment than requested.
var buffer: [1024]u8 align(64) = undefined;
var fba: std.heap.FixedBufferAllocator = .init(buffer[1..]);

var threaded: std.Io.Threaded = .init(fba.allocator());
defer threaded.deinit();
const io = threaded.io();

var group: std.Io.Group = .init;
defer group.cancel(io);

group.async(io, paramWithExtraAlignment, .{.{ .data = 3 }});
}

fn returnArray() [32]u8 {
return @splat(5);
}

test "async on function with array parameter or return type" {
var threaded: std.Io.Threaded = .init(std.testing.allocator);
defer threaded.deinit();
const io = threaded.io();

var future = io.async(returnArray, .{});
const result = future.await(io);
for (result) |actual| {
try std.testing.expectEqual(5, actual);
}
}
Loading