zigar.function.Generator(T, allocating).init(ptr, cb) - chung-leong/zigar GitHub Wiki

Initialize a generator struct using the given pointer and function reference.

Usage

const std = @import("std");
const zigar = @import("zigar");

const Generator = zigar.function.Generator(?[]const u8, false);
var gpa = std.heap.DebugAllocator(.{}).init;
const allocator = gpa.allocator();

const Response = struct {
    name: []u8,

    pub fn onResult(self: *@This(), arg: ?[]const u8) bool {
        if (arg) |text| {
            std.debug.print("{s}: {s}\n", .{ self.name, text });
            return true;
        } else {
            allocator.free(self.name);
            allocator.destroy(self);
            return false;
        }
    }
};

pub fn call(cb: *const fn (Generator) void) !void {
    const response = try allocator.create(Response);
    response.name = try allocator.dupe(u8, "Bart");
    const generator = Generator.init(response, Response.onResult);
    cb(generator);
}
import { call } from './generator-example-9.zig';

call(async function*() {
    const catchphrases = [
        'Eat My Shorts!',
        'Don\'t Have a Cow, Man!',
        '¡Ay, caramba!',
    ];
    for (const catchphrase of catchphrases) {
        yield catchphrase;
    }
});
Bart: Eat my shorts!
Bart: Don't have a cow, man!
Bart: ¡Ay, caramba!

Arguments:

  • ptr: ?*const anyopaque
    Basically any pointer--or null. If a const pointer is given, it's @constCast() to *anyopaque, with the expectation that cb will take a matching const pointer.
  • callback: anytype
    A function or a pointer to one that accepts a pointer as the first argument and T as the second. For convenience sake the first argument can be any single pointer. It does not need to be ?*anyopaque. Any pointer, optional or not, will do.

Return value:

Generator(T, allocating)


Generator(T, allocating)