65 lines
2.1 KiB
Zig
65 lines
2.1 KiB
Zig
///
|
|
/// Returns the return type of the function type `Fn`.
|
|
///
|
|
pub fn FnReturn(comptime Fn: type) type {
|
|
const type_info = @typeInfo(Fn);
|
|
|
|
if (type_info != .Fn) @compileError("`Fn` must be a function type");
|
|
|
|
return type_info.Fn.return_type orelse void;
|
|
}
|
|
|
|
///
|
|
/// Returns a single-input single-output closure type where `In` represents the input type, `Out`
|
|
/// represents the output type, and `captures_size` represents the size of the closure context.
|
|
///
|
|
pub fn Function(comptime captures_size: usize, comptime In: type, comptime Out: type) type {
|
|
return struct {
|
|
callErased: fn (*anyopaque, In) Out,
|
|
context: [captures_size]u8,
|
|
|
|
///
|
|
/// Function type.
|
|
///
|
|
const Self = @This();
|
|
|
|
///
|
|
/// Invokes `self` with `input`, producing a result according to the current context data.
|
|
///
|
|
pub fn call(self: *Self, input: In) Out {
|
|
return self.callErased(&self.context, input);
|
|
}
|
|
|
|
///
|
|
/// Creates a new [Self] by capturing the `captures` value as the context and `invoke` as
|
|
/// the as the behavior executed when [call] or [callErased] is called.
|
|
///
|
|
/// The newly created [Self] is returned.
|
|
///
|
|
pub fn capture(captures: anytype, comptime invoke: fn (@TypeOf(captures), In) Out) Self {
|
|
const Captures = @TypeOf(captures);
|
|
|
|
if (@sizeOf(Captures) > captures_size)
|
|
@compileError("`captures` exceeds the size limit of the capture context");
|
|
|
|
const captures_align = @alignOf(Captures);
|
|
|
|
var function = Self{
|
|
.context = undefined,
|
|
|
|
.callErased = struct {
|
|
fn callErased(erased: *anyopaque, input: In) Out {
|
|
return invoke(if (Captures == void) {} else @ptrCast(*Captures,
|
|
@alignCast(@alignOf(Captures), erased)).*, input);
|
|
}
|
|
}.callErased,
|
|
};
|
|
|
|
if (Captures != void)
|
|
@ptrCast(*Captures, @alignCast(captures_align, &function.context)).* = captures;
|
|
|
|
return function;
|
|
}
|
|
};
|
|
}
|