Thanks for using Compiler Explorer
Sponsors
Jakt
C++
Ada
Analysis
Android Java
Android Kotlin
Assembly
C
C3
Carbon
C++ (Circle)
CIRCT
Clean
CMake
CMakeScript
COBOL
C++ for OpenCL
MLIR
Cppx
Cppx-Blue
Cppx-Gold
Cpp2-cppfront
Crystal
C#
CUDA C++
D
Dart
Elixir
Erlang
Fortran
F#
GLSL
Go
Haskell
HLSL
Hook
Hylo
IL
ispc
Java
Julia
Kotlin
LLVM IR
LLVM MIR
Modula-2
Nim
Objective-C
Objective-C++
OCaml
Odin
OpenCL C
Pascal
Pony
Python
Racket
Ruby
Rust
Snowball
Scala
Slang
Solidity
Spice
SPIR-V
Swift
LLVM TableGen
Toit
TypeScript Native
V
Vala
Visual Basic
Vyper
WASM
Zig
Javascript
GIMPLE
Ygen
zig source #1
Output
Compile to binary object
Link to binary
Execute the code
Intel asm syntax
Demangle identifiers
Verbose demangling
Filters
Unused labels
Library functions
Directives
Comments
Horizontal whitespace
Debug intrinsics
Compiler
zig 0.10.0
zig 0.11.0
zig 0.12.0
zig 0.12.1
zig 0.13.0
zig 0.2.0
zig 0.3.0
zig 0.4.0
zig 0.5.0
zig 0.6.0
zig 0.7.0
zig 0.7.1
zig 0.8.0
zig 0.9.0
zig trunk
Options
Source code
const std = @import("std"); pub fn StateMachine(Impl: var) type { return struct { //@BUG: we should use a nullable for frame, but #5706 frame: @Frame(Impl.func), args: Impl.Args, result: Impl.Result, state: enum { NotStarted, Running, Finished, }, const Self = @This(); pub fn init() Self { return Self { .frame = undefined, .args = undefined, .result = undefined, .state = .NotStarted, }; } pub fn yield(self: *Self, args: var) Impl.Result { const fields = std.meta.fields(Impl.Args); if(args.len != fields.len) @compileError("incorrect number of arguments"); inline for(fields) |f, i| { @field(self.args, f.name) = args[i]; } switch(self.state) { .NotStarted => { self.state = .Running; _ = async self.funcWrapper(); }, .Running => resume self.frame, .Finished => {}, } return self.result; } pub fn reset(self: *Self) void { self.state = .NotStarted; } fn funcWrapper(self: *Self) void { self.frame = async Impl.func(&self.args, &self.result); const auto_reset = await self.frame; self.state = if(auto_reset) .NotStarted else .Finished; } }; } const Range = StateMachine(struct { const Args = struct { start: usize, end: usize, stride: usize, }; const Result = ?usize; fn func(args: *Args, result: *Result) bool { var n = args.start; while(n < args.end):(n += args.stride) { result.* = n; suspend; } result.* = null; return true; } }); pub fn main() void { var r = Range.init(); while(r.yield(.{5, 20, 2})) |n| { std.debug.warn("{}|", .{n}); } std.debug.warn("\n", .{}); //r.reset(); while(r.yield(.{35, 95, 5})) |n| { std.debug.warn("{}|", .{n}); } std.debug.warn("\n", .{}); }
Become a Patron
Sponsor on GitHub
Donate via PayPal
Source on GitHub
Mailing list
Installed libraries
Wiki
Report an issue
How it works
Contact the author
CE on Mastodon
CE on Bluesky
About the author
Statistics
Changelog
Version tree