-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
ziter.zig
2204 lines (1845 loc) · 69 KB
/
ziter.zig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const std = @import("std");
const math = std.math;
const testing = std.testing;
const ziter = @This();
/// Given *[N]T or []T, returns an iterator that can iterate over all items in these types both
/// forward and backwards. Items are iterated by pointer. If you want by value, see `deref`.
pub fn slice(s: anytype) Slice(ToSlice(@TypeOf(s))) {
return .{ .slice = s, .start = 0, .end = s.len };
}
pub fn Slice(comptime _T: type) type {
return struct {
slice: T,
start: usize,
end: usize,
pub const T = _T;
pub const Item = ToOnePtr(T);
pub fn next(it: *@This()) ?Item {
if (it.start >= it.end)
return null;
defer it.start += 1;
return &it.slice[it.start];
}
pub fn next_back(it: *@This()) ?Item {
if (it.start >= it.end)
return null;
it.end -= 1;
return &it.slice[it.end];
}
pub usingnamespace ziter;
};
}
fn ToOnePtr(comptime T: type) type {
var info = @typeInfo(T);
info.Pointer.child = std.meta.Elem(T);
info.Pointer.size = .One;
return @Type(info);
}
fn ToSlice(comptime T: type) type {
var info = @typeInfo(T);
info.Pointer.child = std.meta.Elem(T);
info.Pointer.size = .Slice;
return @Type(info);
}
test "slice" {
const items = "abcd";
var it1 = slice(items);
for (items) |*expected|
try testing.expectEqual(@as(?*const u8, expected), it1.next());
try testing.expectEqual(@as(?*const u8, null), it1.next());
var it2 = slice(items);
var i: usize = items.len;
while (i != 0) : (i -= 1)
try testing.expectEqual(@as(?*const u8, &items[i - 1]), it2.next_back());
try testing.expectEqual(@as(?*const u8, null), it2.next());
var it3 = slice(items);
try testing.expectEqual(@as(?*const u8, &items[0]), it3.next());
try testing.expectEqual(@as(?*const u8, &items[3]), it3.next_back());
try testing.expectEqual(@as(?*const u8, &items[2]), it3.next_back());
try testing.expectEqual(@as(?*const u8, &items[1]), it3.next());
try testing.expectEqual(@as(?*const u8, null), it3.next());
}
/// Creates an iterator that contains one item.
pub fn one(v: anytype) One(@TypeOf(v)) {
return .{ .item = v };
}
pub fn One(comptime _Item: type) type {
return struct {
item: ?Item,
pub const Item = _Item;
pub fn next(it: *@This()) ?Item {
defer it.item = null;
return it.item;
}
pub const next_back = next;
pub usingnamespace ziter;
};
}
test "one" {
try expectEqual(deref("a"), one(@as(u8, 'a')));
try expectEqualReverse(deref("a"), one(@as(u8, 'a')));
}
/// Given ?T, returns an iterator that first returns the payload (if any) and then null.
pub fn optional(o: anytype) Iterator(@TypeOf(o)) {
return .{ .item = o };
}
test "optional" {
try expectEqual(deref("a"), optional(@as(?u8, 'a')));
try expectEqual(deref(""), optional(@as(?u8, null)));
try expectEqualReverse(deref("a"), optional(@as(?u8, 'a')));
try expectEqualReverse(deref(""), optional(@as(?u8, null)));
}
/// Given anyerror!T, returns an iterator that first returns the payload (if any) and then null.
pub fn error_union(u: anytype) Iterator(@TypeOf(u)) {
return optional(u catch null);
}
test "error_union" {
try expectEqual(deref("a"), error_union(@as(anyerror!u8, 'a')));
try expectEqual(deref(""), error_union(@as(anyerror!u8, error.Oof)));
try expectEqualReverse(deref("a"), error_union(@as(anyerror!u8, 'a')));
try expectEqualReverse(deref(""), error_union(@as(anyerror!u8, error.Oof)));
}
/// Returns an iterator that gives all ints from `from` to `to`. Can be iterated backwards as well.
pub fn range(comptime Item: type, from: Item, to: Item) Range(Item) {
return .{ .from = from, .to = to };
}
pub fn Range(comptime _Item: type) type {
return struct {
from: Inner,
to: Inner,
// To avoid overflows when `from` is minInt or `to` is maxInt we have `from` and `to`
// be this new int that makes room for going above or below those values.
const Inner = math.IntFittingRange(math.minInt(Item) - 1, math.maxInt(Item) + 1);
pub const Item = _Item;
pub fn next(it: *@This()) ?Item {
if (it.from > it.to)
return null;
defer it.from += 1;
return @intCast(it.from);
}
pub fn next_back(it: *@This()) ?Item {
if (it.from > it.to)
return null;
defer it.to -= 1;
return @intCast(it.to);
}
pub usingnamespace ziter;
};
}
test "range" {
try expectEqual(deref("abcd"), range(u8, 'a', 'd'));
try expectEqualReverse(deref("abcd"), range(u8, 'a', 'd'));
try expectEqual(deref(&[_]u8{0}), range(u8, 0, 0));
try expectEqualReverse(deref(&[_]u8{0}), range(u8, 0, 0));
try expectEqual(deref(&[_]u8{255}), range(u8, 255, 255));
try expectEqualReverse(deref(&[_]u8{255}), range(u8, 255, 255));
const all_u8 = blk: {
var items: [256]u8 = undefined;
for (&items, 0..) |*item, i|
item.* = @intCast(i);
std.debug.assert(items[0] == 0);
std.debug.assert(items[255] == 255);
break :blk items;
};
try expectEqual(deref(&all_u8), range(u8, 0, 255));
try expectEqualReverse(deref(&all_u8), range(u8, 0, 255));
var i: u64 = 0;
while (i < 100) : (i += 1) {
var random = std.rand.DefaultPrng.init(i);
try expectEqualRandomOrder(random.random(), deref(&all_u8), range(u8, 0, 255));
}
}
/// Creates an empty iterator.
pub fn empty(comptime Item: type) Empty(Item) {
return .{};
}
pub fn Empty(comptime _Item: type) type {
return struct {
pub const Item = _Item;
pub fn next(_: @This()) ?Item {
return null;
}
};
}
test "empty" {
try expectEqual(slice(""), empty(*const u8));
try expectEqual(deref(""), empty(u8));
}
/// Counts the number of items `next` returns before `null`
pub fn count(_it: anytype) usize {
var result: usize = 0;
var it = iterator(_it);
while (it.next()) |_|
result += 1;
return result;
}
test "count" {
try testing.expectEqual(@as(usize, 4), slice("abcd").count());
try testing.expectEqual(@as(usize, 4), count(slice("abcd")));
try testing.expectEqual(@as(usize, 0), slice("").count());
try testing.expectEqual(@as(usize, 0), count(slice("")));
}
/// Given an iterator, this function will return the last item of the iterator. If the iterator
/// can be iterated backwards, then this function is O(1). If not, then it is O(n).
pub fn last(_it: anytype) ?IteratorItem(@TypeOf(_it)) {
const It = Iterator(@TypeOf(_it));
var it = iterator(_it);
if (@hasDecl(It, "next_back"))
return it.next_back();
var result: ?IteratorItem(@TypeOf(_it)) = null;
while (it.next()) |item|
result = item;
return result;
}
test "last" {
const items = "abcd";
try testing.expectEqual(@as(?*const u8, &items[items.len - 1]), slice(items).last());
try testing.expectEqual(@as(?*const u8, &items[items.len - 1]), last(slice(items)));
try testing.expectEqual(@as(?*const u8, null), slice("").last());
try testing.expectEqual(@as(?*const u8, null), last(slice("")));
}
/// Given an iterator, this function will return the first item of the iterator.
pub fn first(_it: anytype) ?IteratorItem(@TypeOf(_it)) {
return nth(_it, 0);
}
test "first" {
const items = "abcd";
try testing.expectEqual(@as(?*const u8, &items[0]), slice(items).first());
try testing.expectEqual(@as(?*const u8, &items[0]), first(slice(items)));
try testing.expectEqual(@as(?*const u8, null), slice("").first());
try testing.expectEqual(@as(?*const u8, null), first(slice("")));
}
/// Given an iterator, this function will return the nth item of the iterator. This function is
/// O(n) in worst case.
pub fn nth(_it: anytype, n: usize) ?IteratorItem(@TypeOf(_it)) {
var curr: usize = 0;
var it = iterator(_it);
var result = it.next() orelse return null;
while (curr < n) : (curr += 1)
result = it.next() orelse return null;
return result;
}
test "nth" {
const items = "abcd";
for (0..items.len) |i| {
try testing.expectEqual(@as(?*const u8, &items[i]), slice(items).nth(i));
try testing.expectEqual(@as(?*const u8, &items[i]), nth(slice(items), i));
}
try testing.expectEqual(@as(?*const u8, null), slice(items).nth(items.len));
try testing.expectEqual(@as(?*const u8, null), nth(slice(items), items.len));
}
/// Creates an iterator that starts at the old iterators first item and returns every nths item
/// from there. This is semantically the same as `it.nth(n*0); it.nth(n*1); it.nth(n*2); ...` in
/// iterator form.
pub fn step_by(_it: anytype, step: usize) StepBy(Iterator(@TypeOf(_it))) {
return .{ .it = iterator(_it), .step = step };
}
pub fn StepBy(comptime _It: type) type {
return struct {
it: It,
step: usize,
pub const It = _It;
pub const Item = IteratorItem(It);
pub fn next(it: *@This()) ?Item {
const result = it.it.next() orelse return null;
var times_stepped: usize = 1;
while (times_stepped < it.step) : (times_stepped += 1)
_ = it.it.next() orelse break;
return result;
}
pub usingnamespace ziter;
};
}
test "step_by" {
const items = deref("abcdefgh");
const results = deref("aceg");
try expectEqual(results, items.step_by(2));
try expectEqual(results, step_by(items, 2));
}
/// Creates an iterator that starts at `first` and continues on to `second` when `first` is
/// empty. Can be iterated backwards as well, starting at `second` until empty. Then continuing
/// to `first`. This requires that both iterators can be iterated backwards.
pub fn chain(first_it: anytype, second_it: anytype) Chain(
Iterator(@TypeOf(first_it)),
Iterator(@TypeOf(second_it)),
) {
return .{ .first = iterator(first_it), .second = iterator(second_it) };
}
pub fn Chain(comptime _First: type, comptime _Second: type) type {
return struct {
first: First,
second: Second,
pub const First = _First;
pub const Second = _Second;
pub const Item = IteratorItem(First);
pub fn next(it: *@This()) ?Item {
return it.first.next() orelse it.second.next();
}
pub fn next_back(it: *@This()) ?Item {
return it.second.next_back() orelse it.first.next_back();
}
pub usingnamespace ziter;
};
}
test "chain" {
const first_it = deref("ab");
const second_it = deref("cd");
const results = deref("abcd");
try expectEqual(results, chain(first_it, second_it));
try expectEqual(results, first_it.chain(second_it));
try expectEqualReverse(results, chain(first_it, second_it));
try expectEqualReverse(results, first_it.chain(second_it));
}
/// Creates an iterator that yields the items of both `a` and `b` when `next` is called. This
/// iterator ends when one of the iterator ends.
pub fn zip(a: anytype, b: anytype) Zip(
Iterator(@TypeOf(a)),
Iterator(@TypeOf(b)),
) {
return .{ .a = iterator(a), .b = iterator(b) };
}
pub fn Zip(comptime _A: type, comptime _B: type) type {
return struct {
a: A,
b: B,
pub const A = _A;
pub const B = _B;
pub const Item = std.meta.Tuple(&.{ IteratorItem(A), IteratorItem(B) });
pub fn next(it: *@This()) ?Item {
return Item{
it.a.next() orelse return null,
it.b.next() orelse return null,
};
}
pub usingnamespace ziter;
};
}
test "zip" {
const Item = std.meta.Tuple(&.{ u8, u8 });
const a = deref("ab");
const b = deref("cde");
const results = deref(&[_]Item{
.{ 'a', 'c' },
.{ 'b', 'd' },
});
try expectEqual(results, zip(a, b));
try expectEqual(results, a.zip(b));
}
/// Creates an iterator that puts seperators inbetween items. So for any iterator, this iterator
/// returns `item, sep, item, ..., sep, item, null`.
pub fn intersperse(
_it: anytype,
separator: IteratorItem(@TypeOf(_it)),
) Intersperse(Iterator(@TypeOf(_it))) {
return .{ .it = iterator(_it).peekable(), .separator = separator };
}
pub fn Intersperse(comptime _It: type) type {
return struct {
it: Peekable(It),
separator: Item,
which: enum { item, separator } = .item,
pub const It = _It;
pub const Item = IteratorItem(It);
pub fn next(it: *@This()) ?Item {
switch (it.which) {
.item => {
it.which = .separator;
return it.it.next();
},
.separator => {
_ = it.it.peek() orelse return null;
it.which = .item;
return it.separator;
},
}
}
pub usingnamespace ziter;
};
}
test "intersperse" {
const items = deref("abcd");
const results = deref("a b c d");
try expectEqual(results, intersperse(items, ' '));
try expectEqual(results, items.intersperse(' '));
}
/// Creates an iterator that transforms the items from the child iterator using `func`. If the
/// child iterator can be iterated backwards, then so can this one.
pub fn map(_it: anytype, ctx: anytype, func: anytype) Map(
Iterator(@TypeOf(_it)),
@TypeOf(ctx),
ReturnType(@TypeOf(func)),
) {
return .{ .it = iterator(_it), .ctx = ctx, .func = func };
}
pub fn Map(comptime _It: type, comptime _Ctx: type, comptime _Item: type) type {
return struct {
it: It,
ctx: Ctx,
func: *const fn (Ctx, IteratorItem(It)) Item,
pub const It = _It;
pub const Ctx = _Ctx;
pub const Item = _Item;
pub fn next(it: *@This()) ?Item {
const item = it.it.next() orelse return null;
return it.func(it.ctx, item);
}
pub fn next_back(it: *@This()) ?Item {
const item = it.it.next_back() orelse return null;
return it.func(it.ctx, item);
}
pub usingnamespace ziter;
};
}
test "map" {
const add = struct {
fn func(ctx: u8, item: u8) u8 {
return ctx + item;
}
}.func;
const items = deref("abcd");
const results = deref("bcde");
try expectEqual(results, map(items, @as(u8, 1), add));
try expectEqual(results, items.map(@as(u8, 1), add));
try expectEqualReverse(results, map(items, @as(u8, 1), add));
try expectEqualReverse(results, items.map(@as(u8, 1), add));
}
/// Creates an iterator that only returns items where `predicate` returns `true`. If the child
/// iterator can be iterated backwards, then so can this one.
pub fn filter(_it: anytype, ctx: anytype, predicate: anytype) Filter(
Iterator(@TypeOf(_it)),
@TypeOf(ctx),
) {
return .{ .it = iterator(_it), .ctx = ctx, .predicate = predicate };
}
pub fn Filter(comptime _It: type, comptime _Ctx: type) type {
return struct {
it: It,
ctx: Ctx,
predicate: *const fn (Ctx, Item) bool,
pub const It = _It;
pub const Ctx = _Ctx;
pub const Item = IteratorItem(It);
pub fn next(it: *@This()) ?Item {
while (it.it.next()) |item| {
if (it.predicate(it.ctx, item))
return item;
}
return null;
}
pub fn next_back(it: *@This()) ?Item {
while (it.it.next_back()) |item| {
if (it.predicate(it.ctx, item))
return item;
}
return null;
}
pub usingnamespace ziter;
};
}
test "filter" {
const filtering = struct {
fn func(ctx: u8, item: u8) bool {
return ctx != item;
}
}.func;
const items = deref("abcd");
const results = deref("acd");
try expectEqual(results, filter(items, @as(u8, 'b'), filtering));
try expectEqual(results, items.filter(@as(u8, 'b'), filtering));
try expectEqualReverse(results, filter(items, @as(u8, 'b'), filtering));
try expectEqualReverse(results, items.filter(@as(u8, 'b'), filtering));
}
/// Creates an iterator that only returns items where `func` does not return `null`. `func` is
/// allowed to transform the items into another type as well. If the child iterator can be iterated
/// backwards, then so can this one.
pub fn filter_map(_it: anytype, ctx: anytype, func: anytype) FilterMap(
Iterator(@TypeOf(_it)),
@TypeOf(ctx),
@typeInfo(ReturnType(@TypeOf(func))).Optional.child,
) {
return .{ .it = iterator(_it), .ctx = ctx, .func = func };
}
pub fn FilterMap(comptime _It: type, comptime _Ctx: type, comptime _Item: type) type {
return struct {
it: It,
ctx: Ctx,
func: *const fn (Ctx, IteratorItem(It)) ?Item,
pub const It = _It;
pub const Ctx = _Ctx;
pub const Item = _Item;
pub fn next(it: *@This()) ?Item {
while (it.it.next()) |item| {
if (it.func(it.ctx, item)) |result|
return result;
}
return null;
}
pub fn next_back(it: *@This()) ?Item {
while (it.it.next_back()) |item| {
if (it.func(it.ctx, item)) |result|
return result;
}
return null;
}
pub usingnamespace ziter;
};
}
test "filter_map" {
const Char = struct { c: u8 };
const filtering = struct {
fn func(ctx: u8, item: u8) ?Char {
if (ctx != item)
return Char{ .c = item + 1 };
return null;
}
}.func;
const items = deref("abcd");
const results = deref(&[_]Char{
.{ .c = 'b' },
.{ .c = 'd' },
.{ .c = 'e' },
});
try expectEqual(results, filter_map(items, @as(u8, 'b'), filtering));
try expectEqual(results, items.filter_map(@as(u8, 'b'), filtering));
try expectEqualReverse(results, filter_map(items, @as(u8, 'b'), filtering));
try expectEqualReverse(results, items.filter_map(@as(u8, 'b'), filtering));
}
/// Creates an iterator that returns the items of the child as well as the index of that those
/// items.
pub fn enumerate(_it: anytype) Enumerate(Iterator(@TypeOf(_it))) {
return .{ .it = iterator(_it) };
}
pub fn Enumerate(comptime _It: type) type {
return struct {
it: It,
i: usize = 0,
pub const It = _It;
pub const Item = EnumerateItem(IteratorItem(It));
pub fn next(it: *@This()) ?Item {
const item = it.it.next() orelse return null;
defer it.i += 1;
return Item{ .i = it.i, .item = item };
}
pub usingnamespace ziter;
};
}
pub fn EnumerateItem(comptime T: type) type {
return struct {
i: usize,
item: T,
};
}
test "enumerate" {
const items = deref("abcd");
const Item = EnumerateItem(u8);
const results = deref(&[_]Item{
.{ .i = 0, .item = 'a' },
.{ .i = 1, .item = 'b' },
.{ .i = 2, .item = 'c' },
.{ .i = 3, .item = 'd' },
});
try expectEqual(results, enumerate(items));
try expectEqual(results, items.enumerate());
}
/// Creates an iterator where the next item that been looked at without advancing the iterator.
/// This is also provided for backwards iteration of the child iterator can be iterated backwards.
pub fn peekable(_it: anytype) Peekable(Iterator(@TypeOf(_it))) {
return .{ .it = iterator(_it) };
}
pub fn Peekable(comptime _It: type) type {
return struct {
it: It,
peeked_front: ?Item = null,
peeked_back: ?Item = null,
pub const It = _It;
pub const Item = IteratorItem(It);
pub fn next(it: *@This()) ?Item {
if (it.peeked_front) |peeked| {
it.peeked_front = null;
return peeked;
}
if (it.it.next()) |item|
return item;
if (it.peeked_back) |peeked| {
it.peeked_back = null;
return peeked;
}
return null;
}
pub fn next_back(it: *@This()) ?Item {
if (it.peeked_back) |peeked| {
it.peeked_back = null;
return peeked;
}
if (it.it.next_back()) |item|
return item;
if (it.peeked_front) |peeked| {
it.peeked_front = null;
return peeked;
}
return null;
}
pub fn peek(it: *@This()) ?Item {
if (it.peeked_front) |peeked|
return peeked;
if (it.it.next()) |item| {
it.peeked_front = item;
return it.peeked_front;
}
return it.peeked_back;
}
pub fn peek_back(it: *@This()) ?Item {
if (it.peeked_back) |peeked|
return peeked;
if (it.it.next_back()) |item| {
it.peeked_back = item;
return it.peeked_back;
}
return it.peeked_front;
}
pub usingnamespace ziter;
};
}
test "peekable" {
const string = "abcd";
const items = deref(string);
var peekable1 = peekable(items);
var peekable2 = items.peekable();
for (string) |item| {
try testing.expectEqual(@as(?u8, item), peekable1.peek());
try testing.expectEqual(@as(?u8, item), peekable2.peek());
try testing.expectEqual(@as(?u8, item), peekable1.peek());
try testing.expectEqual(@as(?u8, item), peekable2.peek());
try testing.expectEqual(@as(?u8, item), peekable1.next());
try testing.expectEqual(@as(?u8, item), peekable2.next());
}
try testing.expectEqual(@as(?u8, null), peekable1.peek());
try testing.expectEqual(@as(?u8, null), peekable2.peek());
try testing.expectEqual(@as(?u8, null), peekable1.next());
try testing.expectEqual(@as(?u8, null), peekable2.next());
var peekable3 = peekable(items);
var peekable4 = items.peekable();
for (string) |item| {
try testing.expectEqual(@as(?u8, item), peekable3.next());
try testing.expectEqual(@as(?u8, item), peekable4.next());
}
try testing.expectEqual(@as(?u8, null), peekable3.next());
try testing.expectEqual(@as(?u8, null), peekable4.next());
var peekable5 = peekable(items);
try testing.expectEqual(@as(?u8, string[0]), peekable5.peek());
try testing.expectEqual(@as(?u8, string[3]), peekable5.peek_back());
try testing.expectEqual(@as(?u8, string[0]), peekable5.next());
try testing.expectEqual(@as(?u8, string[1]), peekable5.next());
try testing.expectEqual(@as(?u8, string[2]), peekable5.peek());
try testing.expectEqual(@as(?u8, string[3]), peekable5.peek_back());
try testing.expectEqual(@as(?u8, string[3]), peekable5.next_back());
try testing.expectEqual(@as(?u8, string[2]), peekable5.peek());
try testing.expectEqual(@as(?u8, string[2]), peekable5.peek_back());
try testing.expectEqual(@as(?u8, string[2]), peekable5.next_back());
try testing.expectEqual(@as(?u8, null), peekable5.peek());
try testing.expectEqual(@as(?u8, null), peekable5.peek_back());
}
/// Iterates the iterator, skipping items until `predicate` returns true. This iterator is then
/// returned. The iterator returned is `Peekable` as `skip_while` requires such an iterator to
/// function.
pub fn skip_while(_it: anytype, ctx: anytype, predicate: anytype) Peekable(Iterator(@TypeOf(_it))) {
var it = peekable(_it);
while (it.peek()) |item| {
if (!predicate(ctx, item))
break;
_ = it.next();
}
return it;
}
test "skip_while" {
const filtering = struct {
fn func(ctx: u8, item: u8) bool {
return ctx == item;
}
}.func;
const items = deref("aaaabcd");
const results = deref("bcd");
try expectEqual(results, skip_while(items, @as(u8, 'a'), filtering));
try expectEqual(results, items.skip_while(@as(u8, 'a'), filtering));
}
/// Creates an iterator that yields items while `predicate` on those items returns `true`. Once
/// `predicate` returns `false` on an item, the iterator ends.
pub fn take_while(_it: anytype, ctx: anytype, predicate: anytype) TakeWhile(
Iterator(@TypeOf(_it)),
@TypeOf(ctx),
) {
return .{ .it = iterator(_it), .ctx = ctx, .predicate = predicate };
}
pub fn TakeWhile(comptime _It: type, comptime _Ctx: type) type {
return struct {
it: It,
ctx: Ctx,
predicate: *const fn (Ctx, Item) bool,
done: bool = false,
pub const It = _It;
pub const Ctx = _Ctx;
pub const Item = IteratorItem(It);
pub fn next(it: *@This()) ?Item {
// !it.done and it.it.next() and it.predicate(item)
if (!it.done) if (it.it.next()) |item| if (it.predicate(it.ctx, item)) {
return item;
};
it.done = true;
return null;
}
pub usingnamespace ziter;
};
}
test "take_while" {
const filtering = struct {
fn func(ctx: u8, item: u8) bool {
return item == ctx;
}
}.func;
const items = deref("aaaabcd");
const results = deref("aaaa");
try expectEqual(results, take_while(items, @as(u8, 'a'), filtering));
try expectEqual(results, items.take_while(@as(u8, 'a'), filtering));
}
/// Creates an iterator that yields items while `func` does not return `null`. `func` is allowed
/// to transform the items to a new type. Once `func` returns `null` on an item, the iterator ends.
pub fn map_while(_it: anytype, ctx: anytype, func: anytype) MapWhile(
Iterator(@TypeOf(_it)),
@TypeOf(ctx),
@typeInfo(ReturnType(@TypeOf(func))).Optional.child,
) {
return .{ .it = iterator(_it), .ctx = ctx, .func = func };
}
pub fn MapWhile(comptime _It: type, comptime _Ctx: type, comptime _Item: type) type {
return struct {
it: It,
ctx: Ctx,
func: *const fn (Ctx, IteratorItem(It)) ?Item,
done: bool = false,
pub const It = _It;
pub const Ctx = _Ctx;
pub const Item = _Item;
pub fn next(it: *@This()) ?Item {
// !it.done and it.it.next() and it.func(item)
if (!it.done) if (it.it.next()) |item| if (it.func(it.ctx, item)) |result| {
return result;
};
it.done = true;
return null;
}
pub usingnamespace ziter;
};
}
test "map_while" {
const Char = struct { c: u8 };
const filtering = struct {
fn func(ctx: u8, item: u8) ?Char {
if (ctx == item)
return Char{ .c = item + 1 };
return null;
}
}.func;
const items = deref("aaaabcd");
const results = deref(&[_]Char{
.{ .c = 'b' },
.{ .c = 'b' },
.{ .c = 'b' },
.{ .c = 'b' },
});
try expectEqual(results, map_while(items, @as(u8, 'a'), filtering));
try expectEqual(results, items.map_while(@as(u8, 'a'), filtering));
}
/// Skips over the first `n` items in the iterator and returns it.
pub fn skip(_it: anytype, n: usize) Iterator(@TypeOf(_it)) {
var i: usize = 0;
var it = iterator(_it);
while (i < n) : (i += 1)
_ = it.next() orelse break;
return it;
}
test "skip" {
const items = deref("aaaabcd");
const results = deref("abcd");
try expectEqual(results, skip(items, 3));
try expectEqual(results, items.skip(3));
}
/// Creates an iterator that yields the first `n` items. Once those items have been yielded, the
/// iterator ends.
pub fn take(_it: anytype, n: usize) Take(Iterator(@TypeOf(_it))) {
return .{ .it = iterator(_it), .n = n };
}
pub fn Take(comptime _It: type) type {
return struct {
it: It,
n: usize,
pub const It = _It;
pub const Item = IteratorItem(It);
pub fn next(it: *@This()) ?Item {
if (it.n == 0)
return null;
it.n -= 1;
return it.it.next();
}
pub usingnamespace ziter;
};
}
test "take" {
const items = deref("aaaabcd");
const results = deref("aaaab");
try expectEqual(results, take(items, 5));
try expectEqual(results, items.take(5));
}
/// A wrapper function around `it.map(...).flatten()`.
pub fn flat_map(_it: anytype, ctx: anytype, func: anytype) Flatten(Map(
Iterator(@TypeOf(_it)),
@TypeOf(ctx),
ReturnType(@TypeOf(func)),
)) {
return map(_it, ctx, func).flatten();
}
test "flat_map" {
const to_optional = struct {
fn func(_: void, item: u8) ?u8 {
return item;
}
}.func;
try expectEqual(
deref("abcd"),
deref("abcd").flat_map({}, to_optional),
);
try expectEqual(
deref("abcd"),
flat_map(deref("abcd"), {}, to_optional),
);
}