-
Notifications
You must be signed in to change notification settings - Fork 4
/
std.sunder
4837 lines (4240 loc) · 171 KB
/
std.sunder
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
namespace std;
import "sys";
alias umax = sys::umax;
alias smax = sys::smax;
# Common error type used within the standard library. The `std::error` type is
# typically used as the error template argument in `std::result` template
# instantiations. Type punning from `*[]byte` to `std::error` is supported.
alias error = *std::error_info;
# Strongly typed wrapper around a static byte-string providing information on
# the category of error that has occurred.
struct error_info {
var data: []byte;
}
# Type representing the outcome of a fallible computation. A result is either
# in the value state, indicating computation success, or the error state,
# indicating computation failure.
struct result[[T, E]] {
var _data: union {
var value: T;
var error: E;
};
var _is_value: bool;
# Initialize a result in the value state (success).
func init_value(value: T) result[[T, E]] {
return (:result[[T, E]]){
._data = (:union { var value: T; var error: E; }){.value = value},
._is_value = true,
};
}
# Initialize a result in the error state (failure).
func init_error(error: E) result[[T, E]] {
return (:result[[T, E]]){
._data = (:union { var value: T; var error: E; }){.error = error},
._is_value = false,
};
}
# Returns true if the result is in the value state.
func is_value(self: *result[[T, E]]) bool {
return self.*._is_value;
}
# Returns true if the result is in the error state.
func is_error(self: *result[[T, E]]) bool {
return not self.*._is_value;
}
# Returns the value associated with a result in the value state.
#
# Panics if the result is in the error state.
func value(self: *result[[T, E]]) T {
if not self.*._is_value {
std::panic("attempted to retrieve value from std::result in the error state");
}
return self.*._data.value;
}
# Returns the error associated with a result in the error state.
#
# Panics if the result is in the value state.
func error(self: *result[[T, E]]) E {
if self.*._is_value {
std::panic("attempted to retrieve error from std::result in the value state");
}
return self.*._data.error;
}
}
# Type representing a value that may not be present. An optional is either in
# the value state, indicating that the value is present, or the empty state,
# indicating that the value is absent.
struct optional[[T]] {
var _value: T;
var _is_value: bool;
# Optional in the empty state.
let EMPTY = (:optional[[T]]){
._value = uninit,
._is_value = false
};
# Initialize an optional in the value state (value is present).
func init_value(value: T) optional[[T]] {
return (:optional[[T]]){
._value = value,
._is_value = true
};
}
# Initialize an optional in the empty state (value is absent).
func init_empty() optional[[T]] {
return optional[[T]]::EMPTY;
}
# Returns true if the optional is in the value state.
func is_value(self: *optional[[T]]) bool {
return self.*._is_value;
}
# Returns true if the optional is in the empty state.
func is_empty(self: *optional[[T]]) bool {
return not self.*._is_value;
}
# Returns the value associated with a non-empty optional.
#
# Panics if the optional is in the empty state.
func value(self: *optional[[T]]) T {
if not self.*._is_value {
std::panic("attempted to retrieve value from empty std::optional");
}
return self.*._value;
}
}
struct reader_itable {
var read: func(*any, []byte) std::result[[usize, std::error]];
}
# Interface representing the read end of a byte stream.
struct reader {
var itable: *std::reader_itable;
var object: *any;
func init[[T]](object: *T) reader {
let itable = (:std::reader_itable){
.read = T::read
};
return (:reader){
.itable = &itable,
.object = object
};
}
# Attempt to read `countof(buf)` bytes using the provided reader. The read
# operation may mutate any portion of `buf`, even if less than
# `countof(buf)` bytes are read.
#
# On success, this function returns the number of bytes read, which must be
# less than or equal to `countof(buf)`, and which may be less than
# `countof(buf)` in the event of a partial read. A successful read of size
# zero indicates an end-of-stream condition for non-zero `countof(buf)`
# buffer sizes.
func read(self: *reader, buf: []byte) std::result[[usize, std::error]] {
return self.*.itable.*.read(self.*.object, buf);
}
}
struct writer_itable {
var write: func(*any, []byte) std::result[[usize, std::error]];
}
# Interface representing the write end of a byte stream.
struct writer {
var itable: *std::writer_itable;
var object: *any;
func init[[T]](object: *T) writer {
let itable = (:std::writer_itable){
.write = T::write
};
return (:writer){
.itable = &itable,
.object = object
};
}
# Attempt to write `countof(buf)` bytes to the provided writer. The write
# operation must not mutate the contents of `buf`.
#
# On success, this function returns the number of bytes written, which may
# be less than `countof(buf)` in the event of a partial write.
func write(self: *writer, buf: []byte) std::result[[usize, std::error]] {
return self.*.itable.*.write(self.*.object, buf);
}
}
struct formatter_itable {
var format: func(*any, std::writer, []byte) std::result[[void, std::error]];
}
# Interface wrapping the format member function. Types which implement format
# may be written to byte streams using type-specific formatting semantics via
# functions such as `std::write_format` and `std::print_format`.
struct formatter {
var itable: *std::formatter_itable;
var object: *any;
func init[[T]](object: *T) formatter {
let itable = (:std::formatter_itable){
.format = T::format
};
return (:formatter){
.itable = &itable,
.object = object
};
}
# Write a formatted representation of `self` to the provided writer. The
# format specifier `fmt` describes *how* to format `self`. Generally, each
# type will implement its own type-specific format specifier(s). However,
# the empty format specifier, `""`, should always be handled as a default
# formatting case.
func format(self: *formatter, writer: std::writer, fmt: []byte) std::result[[void, std::error]] {
return self.*.itable.*.format(self.*.object, writer, fmt);
}
}
struct iterator_itable[[T]] {
var advance: func(*any) bool;
var current: func(*any) T;
}
# Interface used to traverse a collection of elements independently of the
# collection's underlying data representation.
#
# Example:
# # Iterate over a collection of type `foo`, holding elements of type
# # `foo_element`, using the iterator interface applied to the concrete
# # iterator object of type `foo_iterator`.
# var iter = foo_iterator::init(&foo_object);
# var iter = std::iterator[[foo_element]]::init[[foo_iterator]](&iter);
# for iter.advance() {
# var current = iter.current();
# # Do something with the current element...
# }
struct iterator[[T]] {
var itable: *std::iterator_itable[[T]];
var object: *any;
func init[[I]](object: *I) iterator[[T]] {
let itable = (:std::iterator_itable[[T]]){
.advance = I::advance,
.current = I::current
};
return (:iterator[[T]]){
.itable = &itable,
.object = object
};
}
# Advance the iterator by one position. Returns true if the iterator was
# successfully advanced. Returns false if the iterator has reached an
# end-of-iteration condition.
func advance(self: *iterator[[T]]) bool {
return self.*.itable.*.advance(self.*.object);
}
# Returns the item at the current position of the iterator. If the backing
# iterator has not begun iteration, or if the backing iterator has reached
# an end-of-iteration condition, then the backing `current` function should
# panic.
func current(self: *iterator[[T]]) T {
return self.*.itable.*.current(self.*.object);
}
}
struct allocator_itable {
var allocate: func(*any, usize, usize) std::result[[*any, std::error]];
var reallocate: func(*any, *any, usize, usize, usize) std::result[[*any, std::error]];
var deallocate: func(*any, *any, usize, usize) void;
}
# Interface for types managing the dynamic allocation, reallocation, and
# deallocation of memory.
struct allocator {
var itable: *std::allocator_itable;
var object: *any;
func init[[T]](object: *T) allocator {
let itable = (:std::allocator_itable){
.allocate = T::allocate,
.reallocate = T::reallocate,
.deallocate = T::deallocate
};
return (:allocator){
.itable = &itable,
.object = object
};
}
# Attempt to allocate a chunk of memory with the provided alignment and
# size.
#
# On success, this function returns a pointer to the start of the allocated
# chunk.
func allocate(self: *allocator, align: usize, size: usize) std::result[[*any, std::error]] {
return self.*.itable.*.allocate(self.*.object, align, size);
}
# Reallocate a chunk of memory with the provided alignment and size,
# starting at the address `ptr`, which was previously allocated by this
# allocator.
#
# On success, this function returns a pointer to the start of the
# reallocated chunk, which may have same address as the input `ptr`
# argument in the event of a no-op reallocation.
func reallocate(self: *allocator, ptr: *any, align: usize, old_size: usize, new_size: usize) std::result[[*any, std::error]] {
return self.*.itable.*.reallocate(self.*.object, ptr, align, old_size, new_size);
}
# Deallocate a chunk of memory with the provided size and alignment,
# starting at the address `ptr`, which was previously allocated by this
# allocator.
func deallocate(self: *allocator, ptr: *any, align: usize, size: usize) void {
self.*.itable.*.deallocate(self.*.object, ptr, align, size);
}
}
let _DEFAULT_GLOBAL_ALLOCATOR_ITABLE = (:std::allocator_itable){
.allocate = std::general_allocator::allocate,
.reallocate = std::general_allocator::reallocate,
.deallocate = std::general_allocator::deallocate,
};
var _DEFAULT_GLOBAL_ALLOCATOR_OBJECT: std::general_allocator = uninit;
var _global_allocator = (:std::allocator){
.itable = &_DEFAULT_GLOBAL_ALLOCATOR_ITABLE,
.object = &_DEFAULT_GLOBAL_ALLOCATOR_OBJECT,
};
# Set the global allocator used by the standard library.
func set_global_allocator(allocator: std::allocator) void {
_global_allocator = allocator;
}
# Returns the allocator used by the standard library for dynamic memory
# allocation in scenarios where an allocator is not explicitly provided.
func global_allocator() std::allocator {
return _global_allocator;
}
# Allocator that will never successfully allocate, reallocate, or free memory.
# The purpose of this allocator is to provide a type that may be used as the
# allocator member for constants of a managed type such as `std::big_integer`.
# The members constants `ITABLE`, `OBJECT`, and `ALLOCATOR` are provided to
# explicitly support using the null allocator for constant definitions.
struct null_allocator {
func allocate(self_: *null_allocator, align_: usize, size_: usize) std::result[[*any, std::error]] {
return std::result[[*any, std::error]]::init_error(std::error::ALLOCATION_FAILURE);
}
func reallocate(self_: *null_allocator, ptr_: *any, align_: usize, old_size_: usize, new_size_: usize) std::result[[*any, std::error]] {
std::panic("attempted null_allocator reallocation");
return std::result[[*any, std::error]]::init_error(std::error::ALLOCATION_FAILURE);
}
func deallocate(self_: *null_allocator, ptr_: *any, align_: usize, size_: usize) void {
std::panic("attempted null_allocator deallocation");
}
func the() *null_allocator {
let the = (:null_allocator){};
return &the;
}
let ITABLE = (:std::allocator_itable){
.allocate = null_allocator::allocate,
.reallocate = null_allocator::reallocate,
.deallocate = null_allocator::deallocate
};
let OBJECT = (:std::null_allocator){};
let ALLOCATOR = (:std::allocator){
.itable = &null_allocator::ITABLE,
.object = &null_allocator::OBJECT
};
}
# Allocator that allocates and reallocates out of a fixed buffer of memory,
# also known as a bump allocator.
#
# Deallocation with `std::linear_allocator::deallocate` is a no-op.
struct linear_allocator {
var _buf: []byte;
var _old_offset: usize; # Previous offset into the backing buffer.
var _cur_offset: usize; # Current offset into the backing buffer.
# Initialize a linear allocator with the provided buffer of memory.
func init(buf: []byte) linear_allocator {
return (:std::linear_allocator){
._buf = buf,
._old_offset = 0,
._cur_offset = 0
};
}
# Initialize a linear allocator with a buffer of memory created from an
# existing slice of some type `T`. Useful for scenarios where the allocator
# will be used to allocate elements of type `T`.
#
# Example:
# var memory = (:[64]ssize)[0...];
# var allocator = std::linear_allocator::init_from_slice[[ssize]](memory[0:countof(memory)]);
# var allocator = std::allocator::init[[typeof(allocator)]](&allocator);
# # Later...
# var x = std::new_with_allocator[[ssize]](allocator);
func init_from_slice[[T]](slice: []T) linear_allocator {
var buf_start = startof(slice);
var buf_count = countof(slice) * sizeof(T);
return linear_allocator::init((:[]byte){(:*byte)buf_start, buf_count});
}
func allocate(self: *linear_allocator, align: usize, size: usize) std::result[[*any, std::error]] {
if size == 0 {
# Nothing to allocate. The null pointer is returned so that this
# allocator does not forward align the current offset for an
# allocation of size zero.
return std::result[[*any, std::error]]::init_value(std::ptr[[byte]]::NULL);
}
var buf_addr: usize = (:usize)startof(self.*._buf);
var cur_addr: usize = buf_addr + self.*._cur_offset;
var offset: usize = std::forward_align(cur_addr, align) - buf_addr;
if offset + size > countof(self.*._buf) {
return std::result[[*any, std::error]]::init_error(std::error::ALLOCATION_FAILURE);
}
self.*._old_offset = self.*._cur_offset;
self.*._cur_offset = offset + size;
return std::result[[*any, std::error]]::init_value(&self.*._buf[offset]);
}
func reallocate(self: *linear_allocator, ptr: *any, align: usize, old_size: usize, new_size: usize) std::result[[*any, std::error]] {
if old_size == 0 {
# Nothing was allocated in the previous allocate/reallocate call.
assert ptr == std::ptr[[byte]]::NULL;
return self.*.allocate(align, new_size);
}
var offset = (:usize)ptr - (:usize)startof(self.*._buf);
# True if the provided block of memory came from the most recent
# allocation, in which case some or all of the already allocated memory
# may be reclaimed.
var is_tail_allocation = offset >= self.*._old_offset;
if new_size < old_size {
if is_tail_allocation {
self.*._cur_offset = self.*._cur_offset - (old_size - new_size);
}
return std::result[[*any, std::error]]::init_value(ptr);
}
if is_tail_allocation {
if (new_size - old_size) > (countof(self.*._buf) - self.*._cur_offset) {
return std::result[[*any, std::error]]::init_error(std::error::ALLOCATION_FAILURE);
}
self.*._cur_offset = self.*._cur_offset + (new_size - old_size);
return std::result[[*any, std::error]]::init_value(ptr);
}
# Reallocation of memory that did *not* come from the most recent
# allocation. The existing memory cannot be reclaimed, so it is left as
# is and a new chunk of memory is allocated from the backing buffer.
var result = self.*.allocate(align, new_size);
if result.is_error() {
return result;
}
var new = result.value();
std::slice[[byte]]::copy((:[]byte){(:*byte)new, old_size}, (:[]byte){(:*byte)ptr, old_size});
return std::result[[*any, std::error]]::init_value(new);
}
func deallocate(self_: *linear_allocator, ptr_: *any, align_: usize, size_: usize) void {
# no-op
}
# Deallocate all allocated memory in the linear allocator at once,
# invalidating memory previously allocated by this allocator.
func deallocate_all(self: *linear_allocator) void {
self.*._old_offset = 0;
self.*._cur_offset = 0;
}
}
struct general_allocator_element {
var _prev: *general_allocator_element; # nullable
var _next: *general_allocator_element; # nullable
var _start: *any;
var _align: usize;
var _size: usize;
# Returns a pointer to the start of the allocated memory.
func start(self: *general_allocator_element) *any {
return self.*._start;
}
# Returns the alignment of the allocated memory.
func align(self: *general_allocator_element) usize {
return self.*._align;
}
# Returns the size of the allocated memory in bytes.
func size(self: *general_allocator_element) usize {
return self.*._size;
}
}
# General purpose heap allocator. This allocator tracks allocations and will
# automatically deallocate memory when `std::general_allocator::fini` is
# called.
#
# Example:
# var allocator = std::general_allocator::init();
# defer allocator.fini();
# var allocator = std::allocator::init[[typeof(allocator)]](&allocator);
# # Later...
# var x = std::new_with_allocator[[foo]](allocator);
# # At this point the memory allocated by `std::new_with_allocator` can be
# # explicitly deallocated with `std::delete_with_allocator`. If the memory
# # is not explicitly deallocated then the deferred `allocator.fini()` call
# # will automatically handle deallocation at scope exit.
struct general_allocator {
var _elements: *general_allocator_element; # nullable
# Initialize a general allocator.
func init() general_allocator {
return (:general_allocator){
._elements = std::ptr[[general_allocator_element]]::NULL
};
}
# Finalize resources associated with the general allocator. Memory that was
# allocated by this allocator, and which has not yet been explicitly
# deallocated, will be deallocated during finalization.
func fini(self: *general_allocator) void {
for self.*._elements != std::ptr[[std::general_allocator_element]]::NULL {
self.*.deallocate(self.*._elements.*._start, self.*._elements.*._align, self.*._elements.*._size);
}
}
func allocate(self: *general_allocator, align: usize, size: usize) std::result[[*any, std::error]] {
var offset = std::forward_align(sizeof(general_allocator_element), align);
var memory = sys::allocate(alignof(general_allocator_element), offset + size);
var element = (:*general_allocator_element)memory;
*element = (:general_allocator_element){
._prev = std::ptr[[std::general_allocator_element]]::NULL,
._next = std::ptr[[std::general_allocator_element]]::NULL,
._start = std::ptr[[byte]]::add((:*byte)memory, offset),
._align = align,
._size = size
};
self.*._insert_element(element);
return std::result[[*any, std::error]]::init_value(element.*._start);
}
func reallocate(self: *general_allocator, ptr: *any, align: usize, old_size: usize, new_size: usize) std::result[[*any, std::error]] {
var offset = std::forward_align(sizeof(general_allocator_element), align);
var old_element = (:*general_allocator_element)std::ptr[[byte]]::sub((:*byte)ptr, offset);
var new_element = (:*general_allocator_element)sys::allocate(alignof(general_allocator_element), offset + new_size);
*new_element = (:general_allocator_element){
._prev = std::ptr[[general_allocator_element]]::NULL,
._next = std::ptr[[general_allocator_element]]::NULL,
._start = std::ptr[[byte]]::add((:*byte)new_element, offset),
._align = align,
._size = new_size
};
var copy_size = usize::min(old_size, new_size);
std::slice[[byte]]::copy(
(:[]byte){(:*byte)new_element.*._start, copy_size},
(:[]byte){(:*byte)old_element.*._start, copy_size});
self.*._remove_element(old_element);
sys::deallocate(old_element, alignof(general_allocator_element), offset + old_size);
self.*._insert_element(new_element);
return std::result[[*any, std::error]]::init_value(new_element.*._start);
}
func deallocate(self: *general_allocator, ptr: *any, align: usize, size: usize) void {
var offset = std::forward_align(sizeof(general_allocator_element), align);
var element = (:*general_allocator_element)std::ptr[[byte]]::sub((:*byte)ptr, offset);
self.*._remove_element(element);
sys::deallocate(element, alignof(general_allocator_element), offset + size);
}
func _insert_element(self: *general_allocator, element: *general_allocator_element) void {
if self.*._elements == std::ptr[[std::general_allocator_element]]::NULL {
element.*._prev = element;
element.*._next = element;
self.*._elements = element;
return;
}
element.*._prev = self.*._elements.*._prev;
element.*._next = self.*._elements;
element.*._prev.*._next = element;
element.*._next.*._prev = element;
self.*._elements = element;
}
func _remove_element(self: *general_allocator, element: *general_allocator_element) void {
var prev = element.*._prev;
var next = element.*._next;
var is_only_element = prev == element and next == element;
if is_only_element {
assert self.*._elements == element;
self.*._elements = std::ptr[[general_allocator_element]]::NULL;
return;
}
prev.*._next = next;
next.*._prev = prev;
self.*._elements = next;
}
}
# Iterate over the live allocations of a general allocator.
struct general_allocator_iterator {
var _general_allocator: *std::general_allocator;
var _current: std::optional[[*general_allocator_element]];
func init(general_allocator: *std::general_allocator) general_allocator_iterator {
return (:general_allocator_iterator){
._general_allocator = general_allocator,
._current = std::optional[[*general_allocator_element]]::EMPTY
};
}
func advance(self: *general_allocator_iterator) bool {
if self.*._general_allocator.*._elements == std::ptr[[std::general_allocator_element]]::NULL {
return false; # end-of-iteration
}
if self.*._current.is_empty() {
self.*._current = std::optional[[*general_allocator_element]]::init_value(self.*._general_allocator.*._elements);
return true; # start-of-iteration
}
self.*._current = std::optional[[*general_allocator_element]]::init_value(self.*._current.value().*._next);
return self.*._current.value() != self.*._general_allocator.*._elements;
}
func current(self: *general_allocator_iterator) *general_allocator_element {
if self.*._current.is_empty() {
std::panic("invalid iterator");
}
return self.*._current.value();
}
}
# Generic NULL constant. Equivalent to the C NULL pointer cast as type `*any`.
let NULL = (:*any)0u;
struct ptr[[T]] { # namespace
var __namespace__: any;
# Typed NULL constant. Equivalent to the C NULL pointer cast as type `*T`.
let NULL = (:*T)0u;
# Equivalent to the C operation `ptr + n`.
func add(ptr: *T, n: usize) *T {
return (:*T)((:usize)ptr + n * sizeof(typeof(*ptr)));
}
# Equivalent to the C operation `ptr - n`.
func sub(ptr: *T, n: usize) *T {
return (:*T)((:usize)ptr - n * sizeof(typeof(*ptr)));
}
}
struct slice[[T]] { # namespace
var __namespace__: any;
# Copy the elements of `source` into `destination`. The source and
# destination buffers must contain the same number of elements.
func copy(destination: []T, source: []T) void {
if countof(destination) != countof(source) {
std::panic("source and destination buffers have different sizes");
}
if countof(source) == 0 {
# Nothing to copy.
return;
}
# If the copy operation is being performed on two slices into the same
# buffer then the direction in which the copy is performed does matter.
# Say there is some buffer:
#
# 0 1 2 3 4
# [A][B][C][D][E]
#
# and the following copy operation is performed:
#
# std::slice[[T]]::copy(buf[0:3], buf[1:4]);
#
# With a forwards copy the correct result is produced:
#
# 0 1 2 3 4
# [A][B][C][D][E] <- initial buffer
# [B][B][C][D][E] <- copy first element
# [B][C][C][D][E] <- copy second element
# [B][C][D][D][E] <- copy third element
#
# But with a backwards copy an incorrect result is produced:
#
# 0 1 2 3 4
# [A][B][C][D][E] <- initial buffer
# [A][B][D][D][E] <- copy first element
# [A][D][D][D][E] <- copy second element
# [D][D][D][D][E] <- copy third element
#
# So when the start of `destination` appears before the start of
# `source` the copy must be performed forwards, and when the start of
# `source` appears before the start of `destination` then copy must be
# performed backwards. When the start of `destination` and the start of
# `source` are the same, the copy is arbitrarily chosen to be performed
# forwards.
if &destination[0] <= &source[0] {
# Copy forwards.
for i in countof(source) {
destination[i] = source[i];
}
}
else {
# Copy backwards.
for i in countof(source) {
var index: usize = countof(source) - 1 - i;
destination[index] = source[index];
}
}
}
# Set every element of the provided slice to the provided value.
func fill(slice: []T, value: T) void {
for i in countof(slice) {
slice[i] = value;
}
}
# Reverse the elements of the provided slice.
func reverse(slice: []T) void {
if countof(slice) <= 1 {
return;
}
var b = 0u;
var e = countof(slice) - 1;
for b < e {
std::swap[[T]](&slice[b], &slice[e]);
b = b + 1;
e = e - 1;
}
}
# Allocate a slice of `count` elements.
#
# This function panics on error.
func new(count: usize) []T {
return std::slice[[T]]::new_with_allocator(std::global_allocator(), count);
}
# Allocate a slice of `count` elements using the provided allocator.
#
# This function panics on error.
func new_with_allocator(allocator: std::allocator, count: usize) []T {
var result = allocator.allocate(alignof(T), count * sizeof(T));
if result.is_error() {
std::panic(result.error().*.data);
}
return (:[]T){(:*T)result.value(), count};
}
# Resize the provided slice to `new_count` elements.
#
# This function panics on error.
func resize(slice: []T, new_count: usize) []T {
return std::slice[[T]]::resize_with_allocator(std::global_allocator(), slice, new_count);
}
# Resize the provided slice to `new_count` elements using the provided
# allocator.
#
# This function panics on error.
func resize_with_allocator(allocator: std::allocator, slice: []T, new_count: usize) []T {
var cur_count: usize = countof(slice);
var cur_size: usize = cur_count * sizeof(T);
var new_size: usize = new_count * sizeof(T);
var cur_pointer: *byte = (:*byte)startof(slice);
var result = allocator.reallocate(cur_pointer, alignof(T), cur_size, new_size);
if result.is_error() {
std::panic(result.error().*.data);
}
return (:[]T){(:*T)result.value(), new_count};
}
# Deallocate the provided slice.
func delete(slice: []T) void {
std::slice[[T]]::delete_with_allocator(std::global_allocator(), slice);
}
# Deallocate the provided slice using the provided allocator.
func delete_with_allocator(allocator: std::allocator, slice: []T) void {
var pointer: *byte = (:*byte)startof(slice);
var size: usize = countof(slice) * sizeof(T);
allocator.deallocate(pointer, alignof(T), size);
}
}
# Iterator traversing over the elements of a slice.
struct slice_iterator[[T]] {
var _slice: []T;
var _index: std::optional[[usize]];
func init(slice: []T) slice_iterator[[T]] {
return (:slice_iterator[[T]]){
._slice = slice,
._index = std::optional[[usize]]::EMPTY
};
}
func advance(self: *slice_iterator[[T]]) bool {
if countof(self.*._slice) == 0 {
return false; # end-of-iteration
}
if self.*._index.is_empty() {
self.*._index = std::optional[[usize]]::init_value(0);
return true; # start-of-iteration
}
self.*._index = std::optional[[usize]]::init_value(self.*._index.value() + 1);
return self.*._index.value() < countof(self.*._slice);
}
func current(self: *slice_iterator[[T]]) *T {
if self.*._index.is_empty() or self.*._index.value() >= countof(self.*._slice) {
std::panic("invalid iterator");
}
return &self.*._slice[self.*._index.value()];
}
}
struct str { # namespace
var __namespace__: any;
# Returns true if `str` starts with `target`.
func starts_with(str: []byte, target: []byte) bool {
if countof(str) < countof(target) {
return false;
}
for i in countof(target) {
if str[i] != target[i] {
return false;
}
}
return true;
}
# Returns true if `str` ends with `target`.
func ends_with(str: []byte, target: []byte) bool {
if countof(str) < countof(target) {
return false;
}
var start = countof(str) - countof(target);
for i in countof(target) {
if str[start+i] != target[i] {
return false;
}
}
return true;
}
# Returns true if `str` contains `target`.
func contains(str: []byte, target: []byte) bool {
var found = std::str::find(str, target);
return found.is_value();
}
# Returns a non-empty optional containing the index of the first occurance
# of `target` within `str` if `target` is contained within `str`.
func find(str: []byte, target: []byte) std::optional[[usize]] {
if countof(str) < countof(target) {
return std::optional[[usize]]::EMPTY;
}
var start = 0u;
for start <= (countof(str) - countof(target)) {
var i = 0u;
for i < countof(target) {
if str[start+i] != target[i] {
break;
}
i = i + 1;
}
if i == countof(target) {
return std::optional[[usize]]::init_value(start);
}
start = start + 1;
}
return std::optional[[usize]]::EMPTY;
}
# Returns a newly allocated slice containing the fields of `str` split on
# all occurrences of `delimiter`. Consecutive delimiters are not grouped
# together and are deemed to delimit empty strings. Elements of the
# returned slice are created from, and thus share a lifetime with, the
# input string, with the exception of an optional final empty string in the
# case of:
#
# std::str::split("bytes<delimiter>", "<delimiter>");
#
# which has a static lifetime.
#
# Example:
# var fields = std::str::split(input, " ");
# defer std::slice[[[]byte]]::delete(fields);
# for i in countof(fields) {
# # Do something with each split field...
# }
func split(str: []byte, delimiter: []byte) [][]byte {
return std::str::split_with_allocator(std::global_allocator(), str, delimiter);
}
# Returns a newly allocated slice, using the provided allocator, containing
# the fields of `str` split on all occurrences of `delimiter`. Consecutive
# delimiters are not grouped together and are deemed to delimit empty
# strings. Elements of the returned slice are created from, and thus share
# a lifetime with, the input string, with the exception of an optional
# final empty string in the case of
#
# std::str::split_with_allocator(allocator, "bytes<delimiter>", "<delimiter>")
#
# which has a static lifetime.
#
# Example:
# var fields = std::str::split_with_allocator(allocator, input, " ");
# defer std::slice[[[]byte]]::delete_with_allocator(allocator, fields);
# for i in countof(fields) {
# # Do something with each split field...
# }
func split_with_allocator(allocator: std::allocator, str: []byte, delimiter: []byte) [][]byte {
var slice = std::slice[[[]byte]]::new_with_allocator(allocator, 0);
var start = 0u;
var cur = 0u;
for cur < countof(str) {
if not std::str::starts_with(str[cur:countof(str)], delimiter) {
cur = cur + 1;
continue;
}
slice = std::slice[[[]byte]]::resize_with_allocator(allocator, slice, countof(slice) + 1);
slice[countof(slice) - 1] = (:[]byte){&str[start], cur - start};
cur = cur + countof(delimiter);
start = cur;
}
slice = std::slice[[[]byte]]::resize_with_allocator(allocator, slice, countof(slice) + 1);
if start < countof(str) {
slice[countof(slice) - 1] = (:[]byte){&str[start], cur - start};
}
else {
slice[countof(slice) - 1] = (:[]byte){(:*byte)0u, 0};
}
return slice;
}
# Returns true if `lhs` is lexicographically equal to `rhs`.
func eq(lhs: []byte, rhs: []byte) bool {
return lhs.compare(&rhs) == 0;
}
# Returns true if `lhs` is not lexicographically equal to `rhs`.
func ne(lhs: []byte, rhs: []byte) bool {
return lhs.compare(&rhs) != 0;
}
# Returns true if `lhs` is lexicographically less than to `rhs`.
func lt(lhs: []byte, rhs: []byte) bool {
return lhs.compare(&rhs) < 0;
}
# Returns true if `lhs` is lexicographically less than or equal to `rhs`.
func le(lhs: []byte, rhs: []byte) bool {
return lhs.compare(&rhs) <= 0;
}