cubecl-core 0.10.0-pre.3

CubeCL core create
Documentation
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
use cubecl_macros::derive_expand;

use crate as cubecl;
use crate::prelude::*;

#[derive_expand(CubeType, CubeTypeMut, IntoRuntime)]
#[cube(runtime_variants, no_constructors)]
pub enum Option<T: CubeType> {
    /// No value.
    None,
    /// Some value of type `T`.
    Some(T),
}

fn discriminant(variant_name: &'static str) -> i32 {
    OptionExpand::<u32>::discriminant_of(variant_name)
}

pub enum OptionArgs<T: LaunchArg, R: Runtime> {
    Some(<T as LaunchArg>::RuntimeArg<R>),
    None,
}

impl<T: LaunchArg, R: Runtime> From<Option<<T as LaunchArg>::RuntimeArg<R>>> for OptionArgs<T, R> {
    fn from(value: Option<<T as LaunchArg>::RuntimeArg<R>>) -> Self {
        match value {
            Some(arg) => Self::Some(arg),
            None => Self::None,
        }
    }
}

impl<T: LaunchArg + Default + IntoRuntime> LaunchArg for Option<T> {
    type RuntimeArg<R: Runtime> = OptionArgs<T, R>;
    type CompilationArg = OptionCompilationArg<T>;

    fn register<R: Runtime>(
        arg: Self::RuntimeArg<R>,
        launcher: &mut KernelLauncher<R>,
    ) -> Self::CompilationArg {
        match arg {
            OptionArgs::Some(arg) => OptionCompilationArg::Some(T::register(arg, launcher)),
            OptionArgs::None => OptionCompilationArg::None,
        }
    }

    fn expand(
        arg: &Self::CompilationArg,
        builder: &mut KernelBuilder,
    ) -> <Self as CubeType>::ExpandType {
        match arg {
            OptionCompilationArg::Some(value) => {
                let value = T::expand(value, builder);
                OptionExpand {
                    discriminant: discriminant("Some").into(),
                    value,
                }
            }
            OptionCompilationArg::None => OptionExpand {
                discriminant: discriminant("None").into(),
                value: T::default().__expand_runtime_method(&mut builder.scope),
            },
        }
    }

    fn expand_output(
        arg: &Self::CompilationArg,
        builder: &mut KernelBuilder,
    ) -> <Self as CubeType>::ExpandType {
        match arg {
            OptionCompilationArg::Some(value) => {
                let value = T::expand_output(value, builder);
                OptionExpand {
                    discriminant: discriminant("Some").into(),
                    value,
                }
            }
            OptionCompilationArg::None => OptionExpand {
                discriminant: discriminant("None").into(),
                value: T::default().__expand_runtime_method(&mut builder.scope),
            },
        }
    }
}

pub enum OptionCompilationArg<T: LaunchArg> {
    Some(T::CompilationArg),
    None,
}

impl<T: LaunchArg> Clone for OptionCompilationArg<T> {
    fn clone(&self) -> Self {
        match self {
            OptionCompilationArg::Some(value) => OptionCompilationArg::Some(value.clone()),
            OptionCompilationArg::None => OptionCompilationArg::None,
        }
    }
}

impl<T: LaunchArg> PartialEq for OptionCompilationArg<T> {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Some(l0), Self::Some(r0)) => l0 == r0,
            _ => core::mem::discriminant(self) == core::mem::discriminant(other),
        }
    }
}

impl<T: LaunchArg> Eq for OptionCompilationArg<T> {}

impl<T: LaunchArg> core::hash::Hash for OptionCompilationArg<T> {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        core::mem::discriminant(self).hash(state);
        match self {
            OptionCompilationArg::Some(value) => value.hash(state),
            OptionCompilationArg::None => {}
        }
    }
}

impl<T: LaunchArg> core::fmt::Debug for OptionCompilationArg<T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Some(arg0) => f.debug_tuple("Some").field(arg0).finish(),
            Self::None => write!(f, "None"),
        }
    }
}

/// Extensions for [`Option`]
#[allow(non_snake_case)]
pub trait CubeOption<T: CubeType> {
    /// Create a new [`Option::Some`] in a kernel
    fn new_Some(_0: T) -> Option<T> {
        Option::Some(_0)
    }
    fn none_with_default(_0: T) -> Option<T> {
        Option::None
    }

    #[doc(hidden)]
    fn __expand_Some(scope: &mut Scope, value: T::ExpandType) -> OptionExpand<T> {
        Self::__expand_new_Some(scope, value)
    }
    #[doc(hidden)]
    fn __expand_new_Some(_scope: &mut Scope, value: T::ExpandType) -> OptionExpand<T> {
        OptionExpand::<T> {
            discriminant: discriminant("Some").into(),
            value,
        }
    }
    fn __expand_none_with_default(_scope: &mut Scope, value: T::ExpandType) -> OptionExpand<T> {
        OptionExpand {
            discriminant: discriminant("None").into(),
            value,
        }
    }
}

/// Extensions for [`Option`] that require default
#[allow(non_snake_case)]
pub trait CubeOptionDefault<T: CubeType + Default + IntoRuntime>: CubeOption<T> {
    /// Create a new [`Option::None`] in a kernel
    fn new_None() -> Option<T> {
        Option::None
    }

    #[doc(hidden)]
    fn __expand_new_None(scope: &mut Scope) -> OptionExpand<T> {
        let value = T::default().__expand_runtime_method(scope);
        Self::__expand_none_with_default(scope, value)
    }
}

impl<T: CubeType> CubeOption<T> for Option<T> {}
impl<T: CubeType + Default + IntoRuntime> CubeOptionDefault<T> for Option<T> {}

mod impls {
    use core::ops::{Deref, DerefMut};

    use super::*;
    use crate as cubecl;

    /////////////////////////////////////////////////////////////////////////////
    // Type implementation
    /////////////////////////////////////////////////////////////////////////////

    #[doc(hidden)]
    impl<T: CubeType> OptionExpand<T> {
        pub fn __expand_is_some_and_method(
            self,
            scope: &mut Scope,
            f: impl FnOnce(&mut Scope, T::ExpandType) -> NativeExpand<bool>,
        ) -> NativeExpand<bool> {
            match_expand_expr(scope, self, discriminant("None"), |_, _| false.into())
                .case(scope, discriminant("Some"), |scope, value| f(scope, value))
                .finish(scope)
        }

        pub fn __expand_is_none_or_method(
            self,
            scope: &mut Scope,
            f: impl FnOnce(&mut Scope, T::ExpandType) -> NativeExpand<bool>,
        ) -> NativeExpand<bool> {
            match_expand_expr(scope, self, discriminant("None"), |_, _| true.into())
                .case(scope, discriminant("Some"), |scope, value| f(scope, value))
                .finish(scope)
        }

        pub fn __expand_as_ref_method(&self, _scope: &mut Scope) -> OptionExpand<T> {
            self.clone()
        }

        pub fn __expand_as_mut_method(&mut self, _scope: &mut Scope) -> OptionExpand<T> {
            self.clone()
        }

        pub fn __expand_expect_method(self, scope: &mut Scope, msg: &str) -> T::ExpandType
        where
            T::ExpandType: Assign,
        {
            // Replace with `trap` eventually to ensure execution doesn't continue to the next kernel
            match_expand_expr(scope, self, discriminant("Some"), |_, value| value)
                .case(scope, discriminant("None"), |scope, value| {
                    printf_expand(scope, msg, alloc::vec![]);
                    terminate!();
                    value
                })
                .finish(scope)
        }

        pub fn __expand_unwrap_or_else_method<F>(self, scope: &mut Scope, f: F) -> T::ExpandType
        where
            F: FnOnce(&mut Scope) -> T::ExpandType,
            T::ExpandType: Assign,
        {
            match_expand_expr(scope, self, discriminant("Some"), |_, value| value)
                .case(scope, discriminant("None"), |scope, _| f(scope))
                .finish(scope)
        }

        pub fn __expand_map_method<U, F>(self, scope: &mut Scope, f: F) -> OptionExpand<U>
        where
            F: FnOnce(&mut Scope, T::ExpandType) -> U::ExpandType,
            U: CubeType + IntoRuntime + Default,
            OptionExpand<U>: Assign,
        {
            match_expand_expr(scope, self, discriminant("Some"), |scope, value| {
                let value = f(scope, value);
                Option::__expand_new_Some(scope, value)
            })
            .case(scope, discriminant("None"), |scope, _| {
                Option::__expand_new_None(scope)
            })
            .finish(scope)
        }

        pub fn __expand_inspect_method<F>(self, scope: &mut Scope, f: F) -> Self
        where
            F: FnOnce(&mut Scope, &T::ExpandType),
        {
            match_expand(scope, self.clone(), discriminant("Some"), |scope, value| {
                f(scope, &value)
            })
            .case(scope, discriminant("None"), |_, _| {})
            .finish(scope);
            self
        }

        pub fn __expand_map_or_method<U, F>(
            self,
            scope: &mut Scope,
            default: U::ExpandType,
            f: F,
        ) -> U::ExpandType
        where
            F: FnOnce(&mut Scope, T::ExpandType) -> U::ExpandType,
            U: CubeType + Default + IntoRuntime,
            U::ExpandType: Assign,
        {
            match_expand_expr(scope, self, discriminant("Some"), f)
                .case(scope, discriminant("None"), |_, _| default)
                .finish(scope)
        }

        pub fn __expand_map_or_else_method<U, D, F>(
            self,
            scope: &mut Scope,
            default: D,
            f: F,
        ) -> U::ExpandType
        where
            D: FnOnce(&mut Scope) -> U::ExpandType,
            F: FnOnce(&mut Scope, T::ExpandType) -> U::ExpandType,
            U: CubeType + Default + IntoRuntime,
            U::ExpandType: Assign,
        {
            match_expand_expr(scope, self, discriminant("Some"), f)
                .case(scope, discriminant("None"), |scope, _| default(scope))
                .finish(scope)
        }

        pub fn __expand_map_or_default_method<U, F>(self, scope: &mut Scope, f: F) -> U::ExpandType
        where
            U: CubeType + IntoRuntime + Default,
            F: FnOnce(&mut Scope, T::ExpandType) -> U::ExpandType,
            U::ExpandType: Assign,
        {
            match_expand_expr(scope, self, discriminant("Some"), f)
                .case(scope, discriminant("None"), |scope, _| {
                    U::default().__expand_runtime_method(scope)
                })
                .finish(scope)
        }

        pub fn __expand_as_deref_method(self, scope: &mut Scope) -> OptionExpand<T::Target>
        where
            T: Deref<Target: CubeType + Default + IntoRuntime>,
            T::ExpandType: Deref<Target = <T::Target as CubeType>::ExpandType>,
            <T::Target as CubeType>::ExpandType: Assign,
        {
            self.__expand_map_method(scope, |_, value| (*value).clone())
        }

        pub fn __expand_as_deref_mut_method(self, scope: &mut Scope) -> OptionExpand<T::Target>
        where
            T: DerefMut<Target: CubeType + Default + IntoRuntime>,
            T::ExpandType: Deref<Target = <T::Target as CubeType>::ExpandType>,
            <T::Target as CubeType>::ExpandType: Assign,
        {
            self.__expand_map_method(scope, |_, value| (*value).clone())
        }

        pub fn __expand_and_then_method<U, F>(self, scope: &mut Scope, f: F) -> OptionExpand<U>
        where
            F: FnOnce(&mut Scope, T::ExpandType) -> OptionExpand<U>,
            U: CubeType + IntoRuntime + Default,
            U::ExpandType: Assign,
        {
            match_expand_expr(scope, self, discriminant("Some"), f)
                .case(scope, discriminant("None"), |scope, _| {
                    Option::__expand_new_None(scope)
                })
                .finish(scope)
        }

        pub fn __expand_filter_method<P>(self, scope: &mut Scope, predicate: P) -> Self
        where
            P: FnOnce(&mut Scope, T::ExpandType) -> NativeExpand<bool>,
            T: Default + IntoRuntime,
            Self: Assign,
        {
            match_expand_expr(scope, self, discriminant("Some"), |scope, value| {
                let cond = predicate(scope, value.clone());
                if_else_expr_expand(scope, cond, |scope| Option::__expand_new_Some(scope, value))
                    .or_else(scope, |scope| Option::__expand_new_None(scope))
            })
            .case(scope, discriminant("None"), |scope, _| {
                Option::__expand_new_None(scope)
            })
            .finish(scope)
        }

        pub fn __expand_or_else_method<F>(self, scope: &mut Scope, f: F) -> OptionExpand<T>
        where
            F: FnOnce(&mut Scope) -> OptionExpand<T>,
            OptionExpand<T>: Assign,
        {
            let is_some = self.clone().__expand_is_some_method(scope);
            if_else_expr_expand(scope, is_some, |_| self).or_else(scope, |scope| f(scope))
        }

        pub fn __expand_zip_with_method<U, F, R>(
            self,
            scope: &mut Scope,
            other: OptionExpand<U>,
            f: F,
        ) -> OptionExpand<R>
        where
            F: FnOnce(&mut Scope, T::ExpandType, U::ExpandType) -> R::ExpandType,
            U: CubeType,
            R: CubeType + IntoRuntime + Default,
            OptionExpand<R>: Assign,
        {
            match_expand_expr(scope, self, discriminant("Some"), |scope, value| {
                match_expand_expr(scope, other, discriminant("Some"), |scope, other| {
                    let value = f(scope, value, other);
                    Option::__expand_new_Some(scope, value)
                })
                .case(scope, discriminant("None"), |scope, _| {
                    Option::__expand_new_None(scope)
                })
                .finish(scope)
            })
            .case(scope, discriminant("None"), |scope, _| {
                Option::__expand_new_None(scope)
            })
            .finish(scope)
        }

        pub fn __expand_reduce_method<U, R, F>(
            self,
            scope: &mut Scope,
            other: OptionExpand<U>,
            f: F,
        ) -> OptionExpand<R>
        where
            T::ExpandType: Into<R::ExpandType>,
            U::ExpandType: Into<R::ExpandType>,
            F: FnOnce(&mut Scope, T::ExpandType, U::ExpandType) -> R::ExpandType,
            U: CubeType + IntoRuntime + Default,
            R: CubeType + IntoRuntime + Default,
            OptionExpand<R>: Assign,
        {
            match_expand_expr(scope, self, discriminant("Some"), {
                let other = other.clone();
                |scope, value| {
                    match_expand_expr(scope, other, discriminant("Some"), {
                        let value = value.clone();
                        |scope, other| {
                            let value = f(scope, value, other);
                            Option::__expand_new_Some(scope, value)
                        }
                    })
                    .case(scope, discriminant("None"), |scope, _| {
                        Option::__expand_new_Some(scope, value.into())
                    })
                    .finish(scope)
                }
            })
            .case(scope, discriminant("None"), |scope, _| {
                match_expand_expr(scope, other, discriminant("Some"), |scope, other| {
                    Option::__expand_new_Some(scope, other.into())
                })
                .case(scope, discriminant("None"), |scope, _| {
                    Option::__expand_new_None(scope)
                })
                .finish(scope)
            })
            .finish(scope)
        }

        #[allow(clippy::missing_safety_doc)]
        pub unsafe fn __expand_unwrap_unchecked_method(self, scope: &mut Scope) -> T::ExpandType
        where
            T::ExpandType: Assign,
        {
            match_expand_expr(scope, self, discriminant("Some"), |_, value| value).finish(scope)
        }
    }

    #[cube(expand_only)]
    impl<T: CubeType> Option<T> {
        /////////////////////////////////////////////////////////////////////////
        // Querying the contained values
        /////////////////////////////////////////////////////////////////////////

        /// Returns `true` if the option is a [`Some`] value.
        ///
        /// # Examples
        ///
        /// ```
        /// let x: Option<u32> = Some(2);
        /// assert_eq!(x.is_some(), true);
        ///
        /// let x: Option<u32> = None;
        /// assert_eq!(x.is_some(), false);
        /// ```
        pub fn is_some(&self) -> bool {
            match self {
                Option::Some(_) => true.runtime(),
                Option::None => false.runtime(),
            }
        }

        /// Returns `true` if the option is a [`None`] value.
        ///
        /// # Examples
        ///
        /// ```
        /// let x: Option<u32> = Some(2);
        /// assert_eq!(x.is_none(), false);
        ///
        /// let x: Option<u32> = None;
        /// assert_eq!(x.is_none(), true);
        /// ```
        #[must_use = "if you intended to assert that this doesn't have a value, consider \
                  wrapping this in an `assert!()` instead"]
        pub fn is_none(&self) -> bool {
            !self.is_some()
        }

        /////////////////////////////////////////////////////////////////////////
        // Getting to contained values
        /////////////////////////////////////////////////////////////////////////

        /// Returns the contained [`Some`] value, consuming the `self` value.
        ///
        /// Because this function may panic, its use is generally discouraged.
        /// Panics are meant for unrecoverable errors, and
        /// [may abort the entire program][panic-abort].
        ///
        /// Instead, prefer to use pattern matching and handle the [`None`]
        /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
        /// [`unwrap_or_default`]. In functions returning `Option`, you can use
        /// [the `?` (try) operator][try-option].
        ///
        /// [panic-abort]: https://doc.rust-lang.org/book/ch09-01-unrecoverable-errors-with-panic.html
        /// [try-option]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#where-the--operator-can-be-used
        /// [`unwrap_or`]: Option::unwrap_or
        /// [`unwrap_or_else`]: Option::unwrap_or_else
        /// [`unwrap_or_default`]: Option::unwrap_or_default
        ///
        /// # Panics
        ///
        /// Panics if the self value equals [`None`].
        ///
        /// # Examples
        ///
        /// ```
        /// let x = Some("air");
        /// assert_eq!(x.unwrap(), "air");
        /// ```
        ///
        /// ```should_panic
        /// let x: Option<&str> = None;
        /// assert_eq!(x.unwrap(), "air"); // fails
        /// ```
        pub fn unwrap(self) -> T
        where
            T::ExpandType: Assign,
        {
            self.expect("called `Option::unwrap()` on a `None` value")
        }

        /// Returns the contained [`Some`] value or a provided default.
        ///
        /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
        /// the result of a function call, it is recommended to use [`unwrap_or_else`],
        /// which is lazily evaluated.
        ///
        /// [`unwrap_or_else`]: Option::unwrap_or_else
        ///
        /// # Examples
        ///
        /// ```
        /// assert_eq!(Some("car").unwrap_or("bike"), "car");
        /// assert_eq!(None.unwrap_or("bike"), "bike");
        /// ```
        pub fn unwrap_or(self, default: T) -> T
        where
            T::ExpandType: Assign,
        {
            match self {
                Some(x) => x,
                None => default,
            }
        }

        /// Returns the contained [`Some`] value or a default.
        ///
        /// Consumes the `self` argument then, if [`Some`], returns the contained
        /// value, otherwise if [`None`], returns the [default value] for that
        /// type.
        ///
        /// # Examples
        ///
        /// ```
        /// let x: Option<u32> = None;
        /// let y: Option<u32> = Some(12);
        ///
        /// assert_eq!(x.unwrap_or_default(), 0);
        /// assert_eq!(y.unwrap_or_default(), 12);
        /// ```
        ///
        /// [default value]: Default::default
        /// [`parse`]: str::parse
        /// [`FromStr`]: crate::str::FromStr
        pub fn unwrap_or_default(self) -> T
        where
            T: Default + IntoRuntime,
            T::ExpandType: Assign,
        {
            match self {
                Some(x) => x,
                None => comptime![T::default()].runtime(),
            }
        }

        /////////////////////////////////////////////////////////////////////////
        // Transforming contained values
        /////////////////////////////////////////////////////////////////////////

        /////////////////////////////////////////////////////////////////////////
        // Boolean operations on the values, eager and lazy
        /////////////////////////////////////////////////////////////////////////

        /// Returns [`None`] if the option is [`None`], otherwise returns `optb`.
        ///
        /// Arguments passed to `and` are eagerly evaluated; if you are passing the
        /// result of a function call, it is recommended to use [`and_then`], which is
        /// lazily evaluated.
        ///
        /// [`and_then`]: Option::and_then
        ///
        /// # Examples
        ///
        /// ```
        /// let x = Some(2);
        /// let y: Option<&str> = None;
        /// assert_eq!(x.and(y), None);
        ///
        /// let x: Option<u32> = None;
        /// let y = Some("foo");
        /// assert_eq!(x.and(y), None);
        ///
        /// let x = Some(2);
        /// let y = Some("foo");
        /// assert_eq!(x.and(y), Some("foo"));
        ///
        /// let x: Option<u32> = None;
        /// let y: Option<&str> = None;
        /// assert_eq!(x.and(y), None);
        /// ```
        pub fn and<U>(self, optb: Option<U>) -> Option<U>
        where
            U: CubeType + IntoRuntime + Default,
            U::ExpandType: Assign,
        {
            match self {
                Option::Some(_) => optb,
                Option::None => Option::new_None(),
            }
        }

        /// Returns the option if it contains a value, otherwise returns `optb`.
        ///
        /// Arguments passed to `or` are eagerly evaluated; if you are passing the
        /// result of a function call, it is recommended to use [`or_else`], which is
        /// lazily evaluated.
        ///
        /// [`or_else`]: Option::or_else
        ///
        /// # Examples
        ///
        /// ```
        /// let x = Some(2);
        /// let y = None;
        /// assert_eq!(x.or(y), Some(2));
        ///
        /// let x = None;
        /// let y = Some(100);
        /// assert_eq!(x.or(y), Some(100));
        ///
        /// let x = Some(2);
        /// let y = Some(100);
        /// assert_eq!(x.or(y), Some(2));
        ///
        /// let x: Option<u32> = None;
        /// let y = None;
        /// assert_eq!(x.or(y), None);
        /// ```
        pub fn or(self, optb: Option<T>) -> Option<T>
        where
            T::ExpandType: Assign,
        {
            if self.is_some() { self } else { optb }
        }

        /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`].
        ///
        /// # Examples
        ///
        /// ```
        /// let x = Some(2);
        /// let y: Option<u32> = None;
        /// assert_eq!(x.xor(y), Some(2));
        ///
        /// let x: Option<u32> = None;
        /// let y = Some(2);
        /// assert_eq!(x.xor(y), Some(2));
        ///
        /// let x = Some(2);
        /// let y = Some(2);
        /// assert_eq!(x.xor(y), None);
        ///
        /// let x: Option<u32> = None;
        /// let y: Option<u32> = None;
        /// assert_eq!(x.xor(y), None);
        /// ```
        pub fn xor(self, optb: Option<T>) -> Option<T>
        where
            T: Default + IntoRuntime,
            T::ExpandType: Assign,
        {
            if self.is_some() && optb.is_none() {
                self
            } else if self.is_none() && optb.is_some() {
                optb
            } else {
                Option::new_None()
            }
        }

        /////////////////////////////////////////////////////////////////////////
        // Misc
        /////////////////////////////////////////////////////////////////////////

        // TODO: `take`/`take_if`/`replace`

        /// Zips `self` with another `Option`.
        ///
        /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some((s, o))`.
        /// Otherwise, `None` is returned.
        ///
        /// # Examples
        ///
        /// ```
        /// let x = Some(1);
        /// let y = Some("hi");
        /// let z = None::<u8>;
        ///
        /// assert_eq!(x.zip(y), Some((1, "hi")));
        /// assert_eq!(x.zip(z), None);
        /// ```
        pub fn zip<U>(self, other: Option<U>) -> Option<(T, U)>
        where
            U: CubeType,
            (T, U): Default + IntoRuntime,
            (T::ExpandType, U::ExpandType): Into<<(T, U) as CubeType>::ExpandType>,
            OptionExpand<(T, U)>: Assign,
        {
            match self {
                Some(a) => match other {
                    Some(b) => Option::Some((a, b)),
                    None => Option::new_None(),
                },
                None => Option::new_None(),
            }
        }
    }

    #[cube(expand_only)]
    impl<
        T: CubeType<ExpandType: Assign> + IntoRuntime + Default,
        U: CubeType<ExpandType: Assign> + IntoRuntime + Default,
    > Option<(T, U)>
    {
        /// Unzips an option containing a tuple of two options.
        ///
        /// If `self` is `Some((a, b))` this method returns `(Some(a), Some(b))`.
        /// Otherwise, `(None, None)` is returned.
        ///
        /// # Examples
        ///
        /// ```
        /// let x = Some((1, "hi"));
        /// let y = None::<(u8, u32)>;
        ///
        /// assert_eq!(x.unzip(), (Some(1), Some("hi")));
        /// assert_eq!(y.unzip(), (None, None));
        /// ```
        #[inline]
        pub fn unzip(self) -> (Option<T>, Option<U>) {
            match self {
                Option::Some(value) => (Option::Some(value.0), Option::Some(value.1)),
                Option::None => (Option::new_None(), Option::new_None()),
            }
        }
    }
}