-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathlib.rs
More file actions
1721 lines (1601 loc) · 59.8 KB
/
Copy pathlib.rs
File metadata and controls
1721 lines (1601 loc) · 59.8 KB
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
/// Rust functions that the root scope binds.
use std::collections::HashSet;
use std::hash::{Hash, Hasher};
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use std::sync::OnceLock;
pub use ordered_hash_map::OrderedHashMap;
pub use uuid::Uuid;
pub use wgpu::BufferUsages;
use winit::application::ApplicationHandler;
use winit::event::WindowEvent;
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
use winit::window::{Window, WindowAttributes, WindowId};
/// The `AlanError` type is a *cloneable* error that all errors are implemented as within Alan, to
/// simplify error handling. In the future it will have a stack trace based on the Alan source
/// code, but for now only a simple error message is provided.
#[derive(Clone, Debug)]
pub struct AlanError {
pub message: String,
}
impl std::fmt::Display for AlanError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Error: {}", self.message)
}
}
impl std::error::Error for AlanError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
None
}
}
impl From<&str> for AlanError {
fn from(s: &str) -> AlanError {
AlanError {
message: s.to_string(),
}
}
}
impl From<String> for AlanError {
fn from(s: String) -> AlanError {
AlanError { message: s }
}
}
// String-related functions
/// Converts anything that implements ToString into a string. Needed to convert all errors into
/// AlanError since it doesn't seem possible to `impl From<dyn std::error::Error>`
pub fn stringify<T: std::string::ToString>(v: T) -> String {
v.to_string()
}
/// `splitstring` creates a vector of strings split by the specified separator string
#[inline(always)]
pub fn splitstring(a: &str, b: &str) -> Vec<String> {
// For now, special handling if the split string is an empty string to make it behave as
// expected as creating a character array
if b.is_empty() {
a.chars().map(|v| v.to_string()).collect::<Vec<String>>()
} else {
a.split(b).map(|v| v.to_string()).collect::<Vec<String>>()
}
}
/// `getstring` returns the character at the specified index (TODO: What is a "character" in Alan?)
#[inline(always)]
pub fn getstring(a: &str, i: &i64) -> Result<String, AlanError> {
a.chars()
.nth(*i as usize)
.map(String::from)
.ok_or(AlanError {
message: format!(
"Index {} is out-of-bounds for a string length of {}",
i,
a.chars().collect::<Vec<char>>().len()
),
})
}
/// `indexstring` finds the index where the specified substring starts, if possible
#[inline(always)]
pub fn indexstring(a: &String, b: &String) -> Result<i64, AlanError> {
a.find(b).map(|v| v as i64).ok_or(AlanError {
message: format!("Could not find {b} in {a}"),
})
}
// Boolean-related functions
/// `ifbool` executes the true function on true, and the false function on false, returning the
/// value returned by either function
#[inline(always)]
pub fn ifbool<T>(c: &bool, mut t: impl FnMut() -> T, mut f: impl FnMut() -> T) -> T {
if *c {
t()
} else {
f()
}
}
// Array-related functions
/// `getarray` returns a value from an array at the location specified
#[inline(always)]
pub fn getarray<T: Clone>(a: &[T], i: &i64) -> Option<T> {
a.get(*i as usize).cloned()
}
/// `filled` returns a filled Vec<V> of the provided value for the provided size
#[inline(always)]
pub fn filled<V: std::clone::Clone>(i: &V, l: &i64) -> Vec<V> {
vec![i.clone(); *l as usize]
}
/// `map_onearg` runs the provided single-argument function on each element of the vector,
/// returning a new vector
#[inline(always)]
pub fn map_onearg<A, B>(v: &[A], m: impl FnMut(&A) -> B) -> Vec<B> {
v.iter().map(m).collect::<Vec<B>>()
}
/// `map_twoarg` runs the provided two-argument (value, index) function on each element of the
/// vector, returning a new vector
#[inline(always)]
pub fn map_twoarg<A, B>(v: &[A], mut m: impl FnMut(&A, i64) -> B) -> Vec<B> {
v.iter()
.enumerate()
.map(|(i, val)| m(val, i as i64))
.collect::<Vec<B>>()
}
/// `parmap_onearg` runs the provided single-argument function on each element of the vector, with
/// a different subset of the vector run in parallel across all threads.
pub fn parmap_onearg<
A: std::marker::Sync + 'static,
B: std::marker::Send + std::clone::Clone + 'static,
>(
v: &[A],
m: fn(&A) -> B,
) -> Vec<B> {
let par = std::thread::available_parallelism();
match par {
Err(_) => map_onearg(v, m), // Fall back to sequential if there's no available parallelism
Ok(p) if p.get() == 1 => map_onearg(v, m), // Same here
Ok(p) => {
let l = v.len();
let slice_len: isize = (l / p).try_into().unwrap();
let mut out = Vec::new();
out.reserve_exact(l);
if slice_len == 0 {
// We have more CPU cores than values to parallelize, let's assume the user knows
// what they're doing and parallelize anyway
let mut handles: Vec<std::thread::JoinHandle<()>> = Vec::new();
handles.reserve_exact(l);
for i in 0..l {
let v_ptr = v.as_ptr() as usize;
let o_ptr = out.as_ptr() as usize;
handles.push(std::thread::spawn(move || unsafe {
let val = (v_ptr as *const A).add(i).as_ref().unwrap();
let out = (o_ptr as *mut B).add(i);
out.write(m(val));
}));
}
for handle in handles {
let res = handle.join();
if let Err(e) = res {
panic!("{e:?}")
}
}
} else {
// We have more values than CPU cores, so let's divvy this up in batches per core
let mut handles: Vec<std::thread::JoinHandle<()>> = Vec::new();
handles.reserve_exact(p.into());
for i in 0..p.into() {
// I wanted to do this with slices, but their size varies at compile time so
// I'm just going with pointers instead
let v_ptr = v.as_ptr() as usize;
let o_ptr = out.as_ptr() as usize;
let s: isize = (i * (slice_len as usize)).try_into().unwrap();
let e: isize = if i == p.get() - 1 {
l.try_into().unwrap()
} else {
((i + 1) * (slice_len as usize)).try_into().unwrap()
};
handles.push(std::thread::spawn(move || {
let v_ptr = v_ptr as *const A;
let o_ptr = o_ptr as *mut B;
for i in s..e {
unsafe {
let val = v_ptr.offset(i).as_ref().unwrap();
let out = o_ptr.offset(i);
out.write(m(val));
}
}
}));
}
for handle in handles {
let res = handle.join();
if let Err(e) = res {
panic!("{e:?}")
}
}
}
// We need to tweak the len, the values are there but the Vec doesn't know that
unsafe {
out.set_len(l);
}
out
}
}
}
/// `filter_onearg` runs the provided single-argument function on each element of the vector,
/// returning a new vector
#[inline(always)]
pub fn filter_onearg<A: std::clone::Clone>(v: &[A], mut f: impl FnMut(&A) -> bool) -> Vec<A> {
v.iter().filter(|val| f(val)).cloned().collect::<Vec<A>>()
}
/// `filter_twoarg` runs the provided function each element of the vector plus its index,
/// returning a new vector
#[inline(always)]
pub fn filter_twoarg<A: std::clone::Clone>(v: &[A], mut f: impl FnMut(&A, i64) -> bool) -> Vec<A> {
v.iter()
.enumerate()
.filter(|(i, val)| f(val, *i as i64))
.map(|(_, val)| val.clone())
.collect::<Vec<A>>()
}
/// `reduce_sametype` runs the provided function to reduce the vector into a singular value
#[inline(always)]
pub fn reduce_sametype<A: std::clone::Clone>(v: &[A], mut f: impl FnMut(&A, &A) -> A) -> Option<A> {
// The built-in iter `reduce` is awkward for our use case
if v.is_empty() {
None
} else if v.len() == 1 {
Some(v[0].clone())
} else {
let mut out = v[0].clone();
for val in v.iter().skip(1) {
out = f(&out, val);
}
Some(out)
}
}
/// `reduce_sametype_idx` runs the provided function to reduce the vector into a singular value
#[inline(always)]
pub fn reduce_sametype_idx<A: std::clone::Clone>(
v: &[A],
mut f: impl FnMut(&A, &A, &i64) -> A,
) -> Option<A> {
// The built-in iter `reduce` is awkward for our use case
if v.is_empty() {
None
} else if v.len() == 1 {
Some(v[0].clone())
} else {
let mut out = v[0].clone();
for (i, val) in v.iter().enumerate().skip(1) {
out = f(&out, val, &(i as i64));
}
Some(out)
}
}
/// `reduce_difftype` runs the provided function and initial value to reduce the vector into a
/// singular value. Because an initial value is provided, it always returns at least that value
#[inline(always)]
pub fn reduce_difftype<A: std::clone::Clone, B: std::clone::Clone>(
v: &[A],
i: &B,
mut f: impl FnMut(&B, &A) -> B,
) -> B {
let mut out = i.clone();
for val in v {
out = f(&out, val);
}
out
}
/// `reduce_difftype_idx` runs the provided function and initial value to reduce the vector into a
/// singular value. Because an initial value is provided, it always returns at least that value
#[inline(always)]
pub fn reduce_difftype_idx<A: std::clone::Clone, B: std::clone::Clone>(
v: &[A],
i: &B,
mut f: impl FnMut(&B, &A, &i64) -> B,
) -> B {
let mut out = i.clone();
for (i, val) in v.iter().enumerate() {
out = f(&out, val, &(i as i64));
}
out
}
/// `concat` returns a new vector combining the two vectors provided
#[inline(always)]
pub fn concat<A: std::clone::Clone>(a: &[A], b: &[A]) -> Vec<A> {
let mut out = Vec::new();
for v in a {
out.push(v.clone());
}
for v in b {
out.push(v.clone());
}
out
}
/// `append` mutates the first vector copying the second vector into it
#[inline(always)]
pub fn append<A: std::clone::Clone>(a: &mut Vec<A>, b: &[A]) {
for v in b {
a.push(v.clone());
}
}
/// `hasfnarray` returns true if the check function returns true for any element of the vector
#[inline(always)]
pub fn hasfnarray<T>(a: &[T], mut f: impl FnMut(&T) -> bool) -> bool {
for v in a {
if f(v) {
return true;
}
}
false
}
/// `findarray` returns the first value from the vector that matches the check function, if any
#[inline(always)]
pub fn findarray<T: std::clone::Clone>(a: &[T], mut f: impl FnMut(&T) -> bool) -> Option<T> {
for v in a {
if f(v) {
return Some(v.clone());
}
}
None
}
/// `everyarray` returns true if every value in the vector matches the check function
#[inline(always)]
pub fn everyarray<T>(a: &[T], mut f: impl FnMut(&T) -> bool) -> bool {
for v in a {
if !f(v) {
return false;
}
}
true
}
/// `somearray` returns true if any value in the vector matches the check function
#[inline(always)]
pub fn somearray<T>(a: &[T], mut f: impl FnMut(&T) -> bool) -> bool {
for v in a {
if f(v) {
return true;
}
}
false
}
/// `repeatarray` returns a new array with the original array repeated N times
#[inline(always)]
pub fn repeatarray<T: std::clone::Clone>(a: &[T], c: &i64) -> Vec<T> {
let mut out = Vec::new();
for _ in 0..*c {
for v in a {
out.push(v.clone());
}
}
out
}
/// `storearray` inserts a new value at the specified index, but fails if the index is greater than
/// the length of the length of the array (so there would be at least one "gap" in the array in
/// that situation)
#[inline(always)]
pub fn storearray<T: std::clone::Clone>(a: &mut Vec<T>, i: &i64, v: &T) -> Result<(), AlanError> {
match (*i as usize) > a.len() {
true => {
Err(format!("Provided array index {i} is greater than the length of the array").into())
}
false => {
a.insert(*i as usize, v.clone());
Ok(())
}
}
}
/// `deletearray` deletes a value at the specified index, but fails if the index is out-of-bounds.
/// If it succeeds, it returns the value wrapped in a Fallible.
#[inline(always)]
pub fn deletearray<T: std::clone::Clone>(a: &mut Vec<T>, i: &i64) -> Result<T, AlanError> {
match (*i as usize) >= a.len() {
true => Err(format!("Provided array index {i} is beyond the bounds of the array").into()),
false => Ok(a.remove(*i as usize).clone()),
}
}
/// `swaparray` swaps the values at the specified indicies (or fails if either index is out of
/// bounds). It returns a Fallible void value.
#[inline(always)]
pub fn swaparray<T>(a: &mut [T], i: &i64, j: &i64) -> Result<(), AlanError> {
if *i < 0 {
return Err(format!("Provided array index {i} is beyond the bounds of the array").into());
}
if *j < 0 {
return Err(format!("Provided array index {j} is beyond the bounds of the array").into());
}
let i = *i as usize;
let j = *j as usize;
if i >= a.len() {
return Err(format!("Provided array index {i} is beyond the bounds of the array").into());
}
if j >= a.len() {
return Err(format!("Provided array index {j} is beyond the bounds of the array").into());
}
if i == j {
return Ok(());
}
if i < j {
let (i_section, j_section) = a.split_at_mut(j);
std::mem::swap(&mut i_section[i], &mut j_section[0]);
} else {
let (j_section, i_section) = a.split_at_mut(j);
std::mem::swap(&mut j_section[j], &mut i_section[0]);
}
Ok(())
}
/// `sortarray` is a thin wrapper around `sort_by` allowing for the sort decision to be done by
/// numeric operation rather than the `Ordering` enum, which is not exposed
#[inline(always)]
pub fn sortarray<T>(a: &mut [T], mut sorter: impl FnMut(&T, &T) -> i8) {
a.sort_by(|a, b| sorter(a, b).cmp(&0));
}
// Buffer-related functions
/// `getbuffer` returns the value at the given index presuming it exists
#[inline(always)]
pub fn getbuffer<T: std::clone::Clone, const S: usize>(b: &[T; S], i: &i64) -> Option<T> {
b.get(*i as usize).cloned()
}
/// `mapbuffer_onearg` runs the provided single-argument function on each element of the buffer,
/// returning a new buffer
#[inline(always)]
pub fn mapbuffer_onearg<A, const N: usize, B>(v: &[A; N], mut m: impl FnMut(&A) -> B) -> [B; N] {
std::array::from_fn(|i| m(&v[i]))
}
/// `mapbuffer_twoarg` runs the provided two-argument (value, index) function on each element of the
/// buffer, returning a new buffer
#[inline(always)]
pub fn mapbuffer_twoarg<A, const N: usize, B: std::marker::Copy>(
v: &[A; N],
mut m: impl FnMut(&A, &i64) -> B,
) -> [B; N] {
let mut out = [m(&v[0], &0); N];
for i in 1..N {
out[i] = m(&v[i], &(i as i64));
}
out
}
/// `reducebuffer_sametype` runs the provided function to reduce the buffer into a singular
/// value
#[inline(always)]
pub fn reducebuffer_sametype<A: std::clone::Clone, const S: usize>(
b: &[A; S],
mut f: impl FnMut(&A, &A) -> A,
) -> Option<A> {
// The built-in iter `reduce` is awkward for our use case
if b.is_empty() {
None
} else if b.len() == 1 {
Some(b[0].clone())
} else {
let mut out = b[0].clone();
for v in b.iter().skip(1) {
out = f(&out, v);
}
Some(out)
}
}
/// `reducebuffer_difftype` runs the provided function and initial value to reduce the buffer into a
/// singular value. Because an initial value is provided, it always returns at least that value
#[inline(always)]
pub fn reducebuffer_difftype<A: std::clone::Clone, const S: usize, B: std::clone::Clone>(
b: &[A; S],
i: &B,
mut f: impl FnMut(&B, &A) -> B,
) -> B {
let mut out = i.clone();
for v in b {
out = f(&out, v);
}
out
}
/// `hasbuffer` returns true if the specified value exists anywhere in the array
#[inline(always)]
pub fn hasbuffer<T: std::cmp::PartialEq, const S: usize>(a: &[T; S], v: &T) -> bool {
for val in a {
if val == v {
return true;
}
}
false
}
/// `hasfnbuffer` returns true if the check function returns true for any element of the array
#[inline(always)]
pub fn hasfnbuffer<T, const S: usize>(a: &[T; S], mut f: impl FnMut(&T) -> bool) -> bool {
for v in a {
if f(v) {
return true;
}
}
false
}
/// `findbuffer` returns the first value from the buffer that matches the check function, if any
#[inline(always)]
pub fn findbuffer<T: std::clone::Clone, const S: usize>(
a: &[T; S],
mut f: impl FnMut(&T) -> bool,
) -> Option<T> {
for v in a {
if f(v) {
return Some(v.clone());
}
}
None
}
/// `everybuffer` returns true if every value in the array matches the check function
#[inline(always)]
pub fn everybuffer<T, const S: usize>(a: &[T; S], mut f: impl FnMut(&T) -> bool) -> bool {
for v in a {
if !f(v) {
return false;
}
}
true
}
/// `concatbuffer` mutates the first buffer given with the values of the other two. It depends on
/// the provided buffer to be the right size to fit the data from both of the other buffers.
#[inline(always)]
pub fn concatbuffer<T: std::clone::Clone, const S: usize, const N: usize, const O: usize>(
o: &mut [T; O],
a: &[T; S],
b: &[T; N],
) {
for (i, v) in a.iter().chain(b).enumerate() {
o[i] = v.clone();
}
}
/// `repeatbuffertoarray` returns a new array with the original buffer repeated N times
#[inline(always)]
pub fn repeatbuffertoarray<T: std::clone::Clone, const S: usize>(a: &[T; S], c: &i64) -> Vec<T> {
let mut out = Vec::new();
for _ in 0..*c {
for v in a {
out.push(v.clone());
}
}
out
}
/// `storebuffer` stores the provided value in the specified index. If the index is out-of-bounds
/// for the buffer it fails, otherwise it returns the old value.
#[inline(always)]
pub fn storebuffer<T: std::clone::Clone, const S: usize>(
a: &mut [T; S],
i: &i64,
v: &T,
) -> Result<T, AlanError> {
match (*i as usize) < a.len() {
false => {
Err(format!("The provided index {i} is out-of-bounds for the specified buffer").into())
}
true => Ok(std::mem::replace(a.each_mut()[*i as usize], v.clone())),
}
}
/// `swapbuffer` swaps the values at the specified indicies (or fails if either index is out of
/// bounds). It returns a Fallible void value.
#[inline(always)]
pub fn swapbuffer<T, const S: usize>(a: &mut [T; S], i: &i64, j: &i64) -> Result<(), AlanError> {
if *i < 0 {
return Err(format!("Provided buffer index {i} is beyond the bounds of the buffer").into());
}
if *j < 0 {
return Err(format!("Provided buffer index {j} is beyond the bounds of the buffer").into());
}
let i = *i as usize;
let j = *j as usize;
if i >= a.len() {
return Err(format!("Provided buffer index {i} is beyond the bounds of the buffer").into());
}
if j >= a.len() {
return Err(format!("Provided buffer index {j} is beyond the bounds of the buffer").into());
}
if i == j {
return Ok(());
}
if i < j {
let (i_section, j_section) = a.split_at_mut(j);
std::mem::swap(&mut i_section[i], &mut j_section[0]);
} else {
let (j_section, i_section) = a.split_at_mut(i);
std::mem::swap(&mut j_section[j], &mut i_section[0]);
}
Ok(())
}
/// `sortbuffer` is a thin wrapper around `sort_by` allowing for the sort decision to be done by
/// numeric operation rather than the `Ordering` enum, which is not exposed
#[inline(always)]
pub fn sortbuffer<T, const S: usize>(a: &mut [T; S], mut sorter: impl FnMut(&T, &T) -> i8) {
a.sort_by(|a, b| sorter(a, b).cmp(&0));
}
// Dictionary-related bindings
/// `getdict` returns the value for the given key, if it exists
#[inline(always)]
pub fn getdict<K: std::hash::Hash + Eq, V: std::clone::Clone>(
d: &OrderedHashMap<K, V>,
k: &K,
) -> Option<V> {
d.get(k).cloned()
}
/// `keysdict` returns an array of keys from the dictionary
#[inline(always)]
pub fn keysdict<K: std::clone::Clone, V>(d: &OrderedHashMap<K, V>) -> Vec<K> {
d.keys().cloned().collect::<Vec<K>>()
}
/// `valsdict` returns an array of values from the dictionary
#[inline(always)]
pub fn valsdict<K, V: std::clone::Clone>(d: &OrderedHashMap<K, V>) -> Vec<V> {
d.values().cloned().collect::<Vec<V>>()
}
/// `arraydict` returns an array of key-value tuples representing the dictionary
#[inline(always)]
pub fn arraydict<K: std::clone::Clone, V: std::clone::Clone>(
d: &OrderedHashMap<K, V>,
) -> Vec<(K, V)> {
d.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect::<Vec<(K, V)>>()
}
/// `concatdict` returns a new dictionary containing the key-value pairs of the original two
/// dictionaries. Insertion order follows the first dictionary followed by the second dictionary.
/// In cases of key collision, the insertion order of the first dictionary is followed but with the
/// second dictionary's value.
#[inline(always)]
pub fn concatdict<K: std::clone::Clone + std::hash::Hash + Eq, V: std::clone::Clone>(
a: &OrderedHashMap<K, V>,
b: &OrderedHashMap<K, V>,
) -> OrderedHashMap<K, V> {
let mut out = OrderedHashMap::new();
for k in a.keys() {
if b.contains_key(k) {
out.insert(k.clone(), b.get(k).unwrap().clone());
} else {
out.insert(k.clone(), a.get(k).unwrap().clone());
}
}
for k in b.keys() {
if !a.contains_key(k) {
out.insert(k.clone(), b.get(k).unwrap().clone());
}
}
out
}
// Set-related bindings
/// `arrayset` returns an array of values in the set
#[inline(always)]
pub fn arrayset<V: std::clone::Clone>(s: &HashSet<V>) -> Vec<V> {
s.iter().cloned().collect::<Vec<V>>()
}
/// `unionset` returns a new set that is the union of the original two sets
#[inline(always)]
pub fn unionset<V: std::clone::Clone + std::hash::Hash + Eq>(
a: &HashSet<V>,
b: &HashSet<V>,
) -> HashSet<V> {
// Rust's own `union` method returns a specialized `Union` type to eliminate duplication, which
// is much more efficient in certain circumstances, but it doesn't appear to implement all of
// the functions of a `HashSet`, so I am only using it internally to generate a new `HashSet`
// that I can be sure is usable everywhere.
a.union(b).cloned().collect::<HashSet<V>>()
}
/// `intersectset` returns a new set that is the intersection of the original two sets
#[inline(always)]
pub fn intersectset<V: std::clone::Clone + std::hash::Hash + Eq>(
a: &HashSet<V>,
b: &HashSet<V>,
) -> HashSet<V> {
a.intersection(b).cloned().collect::<HashSet<V>>()
}
/// `differenceset` returns the difference of the original two sets (values in A not in B)
#[inline(always)]
pub fn differenceset<V: std::clone::Clone + std::hash::Hash + Eq>(
a: &HashSet<V>,
b: &HashSet<V>,
) -> HashSet<V> {
a.difference(b).cloned().collect::<HashSet<V>>()
}
/// `symmetric_differenceset` returns the symmetric difference of the original two sets (values in
/// A not in B *and* values in B not in A)
#[inline(always)]
pub fn symmetric_differenceset<V: std::clone::Clone + std::hash::Hash + Eq>(
a: &HashSet<V>,
b: &HashSet<V>,
) -> HashSet<V> {
a.symmetric_difference(b).cloned().collect::<HashSet<V>>()
}
/// `productset` returns the product of the original two sets (a set of tuples of all combinations
/// of values in each set)
#[inline(always)]
pub fn productset<V: std::clone::Clone + std::hash::Hash + Eq>(
a: &HashSet<V>,
b: &HashSet<V>,
) -> HashSet<(V, V)> {
let mut out = HashSet::new();
for va in a.iter() {
for vb in b.iter() {
out.insert((va.clone(), vb.clone()));
}
}
out
}
// Vector-related functions
pub fn cross_f32(a: &[f32; 3], b: &[f32; 3]) -> [f32; 3] {
[
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
]
}
pub fn cross_f64(a: &[f64; 3], b: &[f64; 3]) -> [f64; 3] {
[
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
]
}
// GPU-related functions and types
pub struct GPU {
pub adapter: wgpu::Adapter,
pub device: wgpu::Device,
pub queue: wgpu::Queue,
}
impl GPU {
pub fn list() -> Vec<wgpu::Adapter> {
let instance = wgpu::Instance::default();
let mut out = Vec::new();
let adapters_future = instance.enumerate_adapters(wgpu::Backends::all());
let adapters = futures::executor::block_on(adapters_future);
for adapter in adapters {
if adapter.get_downlevel_capabilities().is_webgpu_compliant() {
out.push(adapter);
}
}
out
}
pub fn init(adapters: Vec<wgpu::Adapter>) -> Vec<GPU> {
let mut out = Vec::new();
for adapter in adapters {
let limits = adapter.limits();
let info = adapter.get_info();
let device_future = adapter.request_device(&wgpu::DeviceDescriptor {
label: Some(&format!("{} on {}", info.name, info.backend.to_str())),
required_features: wgpu::Features::empty(),
required_limits: limits,
experimental_features: wgpu::ExperimentalFeatures::disabled(),
memory_hints: wgpu::MemoryHints::Performance,
trace: wgpu::Trace::Off,
});
match futures::executor::block_on(device_future) {
Ok((device, queue)) => {
out.push(GPU {
adapter,
device,
queue,
});
}
Err(_) => {}
};
}
out
}
}
static GPUS: OnceLock<Vec<GPU>> = OnceLock::new();
static SUBGROUP_MAX_SIZE: OnceLock<u32> = OnceLock::new();
fn gpu() -> &'static GPU {
match GPUS.get_or_init(|| GPU::init(GPU::list())).first() {
Some(g) => g,
None => panic!(
"This program requires a GPU but there are no WebGPU-compliant GPUs on this machine"
),
}
}
fn subgroup_max_size() -> u32 {
*SUBGROUP_MAX_SIZE.get_or_init(|| {
let g = gpu();
g.adapter.get_info().subgroup_max_size
})
}
pub fn optimal_local_group(global: [i64; 3]) -> [i64; 3] {
let total_global = (global[0] as u64) * (global[1] as u64) * (global[2] as u64);
if total_global == 0 {
return [1, 1, 1];
}
let g = gpu();
let sub_max = subgroup_max_size();
let max_invocations = g.adapter.limits().max_compute_invocations_per_workgroup as u64;
// Target totalInvocationsPerWorkgroup so that totalWorkgroups ~ subgroup_max_size
let mut target = (total_global as f64 / sub_max as f64).ceil() as u64;
// Clamp to [8, maxInvocations]
target = target.max(8).min(max_invocations);
// Snap to nearest multiple of 8 (hardware alignment)
target = ((target + 7) / 8) * 8;
// Shape: prefer S*S*1, then D*8*1
let sqrt = (target as f64).sqrt() as u64;
if sqrt >= 8 && sqrt * sqrt == target {
return [sqrt as i64, sqrt as i64, 1];
}
if target % 8 == 0 {
return [(target / 8) as i64, 8, 1];
}
[target as i64, 1, 1]
}
#[derive(Clone)]
pub struct GBuffer {
buffer: Rc<wgpu::Buffer>,
id: String,
element_size: i8,
}
impl PartialEq for GBuffer {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl Eq for GBuffer {}
impl Hash for GBuffer {
fn hash<H: Hasher>(&self, state: &mut H) {
self.buffer.hash(state);
}
}
impl Deref for GBuffer {
type Target = Rc<wgpu::Buffer>;
fn deref(&self) -> &Self::Target {
&self.buffer
}
}
impl DerefMut for GBuffer {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.buffer
}
}
pub fn create_buffer_init<T>(
usage: &wgpu::BufferUsages,
vals: &[T],
element_size: &i8,
) -> Result<GBuffer, AlanError> {
let g = gpu();
let val_ptr = vals.as_ptr();
let val_u8_len = vals.len() * (*element_size as usize);
let limits = g.device.limits();
if limits.max_buffer_size < val_u8_len as u64 {
return Err(AlanError { message: format!("Cannot load the array into the GPU, as it is too large. GBuffer on your GPU only supports up to {} bytes per buffer", limits.max_buffer_size), });
}
// Create an empty buffer first
let buf = GBuffer {
buffer: Rc::new(g.device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: val_u8_len as u64,
usage: *usage,
mapped_at_creation: false,
})),
id: format!("buffer_{}", format!("{}", Uuid::new_v4()).replace("-", "_")),
element_size: *element_size,
};
// Create a staging buffer with the data
let val_u8: &[u8] = unsafe { std::slice::from_raw_parts(val_ptr as *const u8, val_u8_len) };
let staging_buffer = g.device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: val_u8_len as u64,
usage: wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::MAP_WRITE,
mapped_at_creation: true,
});
// Write data to staging buffer
{
let view = staging_buffer.slice(..);
view.get_mapped_range_mut().copy_from_slice(val_u8);
}
staging_buffer.unmap();
// Copy from staging buffer to target buffer
let mut encoder = g
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
encoder.copy_buffer_to_buffer(&staging_buffer, 0, &buf, 0, val_u8_len as u64);
// Submit and wait for the copy to complete
let submission_index = g.queue.submit(Some(encoder.finish()));
match g.device.poll(wgpu::PollType::Wait {
submission_index: Some(submission_index),
timeout: None,
}) {
Ok(_) => Ok(()),
Err(e) => Err(AlanError {
message: format!("Failed to create buffer {e:?}"),
}),
}?;
Ok(buf)
}
pub fn create_empty_buffer(
usage: &wgpu::BufferUsages,
size: &i64,
element_size: &i8,
) -> Result<GBuffer, AlanError> {
let g = gpu();
let limits = g.device.limits();
if limits.max_buffer_size < *size as u64 {
return Err(AlanError { message: format!("Cannot load the array into the GPU, as it is too large. GBuffer on your GPU only supports up to {} bytes per buffer", limits.max_buffer_size), });
}
Ok(GBuffer {
buffer: Rc::new(g.device.create_buffer(&wgpu::BufferDescriptor {
label: None, // TODO: Add a label for easier debugging?
size: (*size as u64) * (*element_size as u64),
usage: *usage,
mapped_at_creation: false, // TODO: With `create_buffer_init` does this make any sense?
})),
id: format!("buffer_{}", format!("{}", Uuid::new_v4()).replace("-", "_")),
element_size: *element_size,
})
}
// TODO: Either add the ability to bind to const values, or come up with a better solution. For
// now, just hardwire a few buffer usage types in these functions
#[inline(always)]
pub fn map_read_buffer_type() -> wgpu::BufferUsages {
wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST
}
#[inline(always)]
pub fn map_write_buffer_type() -> wgpu::BufferUsages {
wgpu::BufferUsages::MAP_WRITE | wgpu::BufferUsages::COPY_SRC
}
#[inline(always)]
pub fn storage_buffer_type() -> wgpu::BufferUsages {