Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const std = @import("std");
- const mem = @import("std").mem;
- const builtin = @import("builtin");
- fn tuple(comptime T: type) type {
- return struct {
- idx: usize,
- item: T,
- };
- }
- fn Iterator(comptime SELF: type, comptime Item: type) type {
- return struct {
- pub fn REQUIRE_next(self: *SELF) ?Item {
- return undefined;
- }
- pub fn enumerate(self: SELF) Enumerate(SELF, Item) {
- return Enumerate(SELF, Item).init(self);
- }
- };
- }
- pub fn Enumerate(comptime Iter: type, comptime Item: type) type {
- comptime {
- require(Iterator(Iter, Item), Iter, "Enumerate only works for Iterators");
- }
- return struct {
- idx: usize,
- iter: Iter,
- fn next(self: *this) ?tuple(Item) {
- var nxt = self.iter.next() orelse return null;
- self.idx += 1;
- return tuple(?Item) {.idx = self.idx, .item = nxt };
- }
- fn init(it: Iter) this {
- return this {
- .idx = 0,
- .iter = it
- };
- }
- };
- }
- fn range() type {
- return struct {
- const Self = this;
- start: usize,
- end: usize,
- fn init(start: usize, end: usize) Self {
- return Self {
- .start = start,
- .end = end,
- };
- }
- fn next(self: *Self) ?usize {
- if (self.start >= self.end) {
- return null;
- }
- self.start += 1;
- return self.start;
- }
- };
- }
- fn require(comptime TRAIT: var, comptime CHECK: var, comptime msg: []const u8) void {
- const fn_names_to_check = @typeInfo(TRAIT).Struct;
- const to_check_type_info = @typeInfo(CHECK).Struct;
- inline for(fn_names_to_check.defs) |name| {
- inline for (to_check_type_info.defs) |def| {
- if (mem.eql(u8, name.name[0..7], "REQUIRE")) {
- if(mem.eql(u8, name.name[8..], def.name)) {
- if (mem.eql(u8, @typeName(name.data.Fn.fn_type), @typeName(def.data.Fn.fn_type))) {
- return;
- }
- }
- }
- }
- }
- @compileError(msg);
- }
- pub fn main() void {
- var r = range().init(1, 100);
- var enumer = Iterator(range(), usize).enumerate(r);
- while (enumer.next()) |item| {
- std.debug.warn("{} {}\n", item.idx, item.item);
- }
- //while (r.next()) |item| {
- // std.debug.warn("{}", item);
- //}
- }
Advertisement
Add Comment
Please, Sign In to add comment