File: generics.rs

package info (click to toggle)
rustc 1.85.0%2Bdfsg3-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, sid, trixie
  • size: 893,396 kB
  • sloc: xml: 158,127; python: 35,830; javascript: 19,497; cpp: 19,002; sh: 17,245; ansic: 13,127; asm: 4,376; makefile: 1,051; perl: 29; lisp: 29; ruby: 19; sql: 11
file content (85 lines) | stat: -rw-r--r-- 1,547 bytes parent folder | download | duplicates (2)
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
//@ run-pass
#![allow(non_camel_case_types)]
#![feature(repr_simd, intrinsics)]

use std::ops;

#[repr(simd)]
#[derive(Copy, Clone)]
struct f32x4([f32; 4]);

#[repr(simd)]
#[derive(Copy, Clone)]
struct A<const N: usize>([f32; N]);

#[repr(simd)]
#[derive(Copy, Clone)]
struct B<T>([T; 4]);

#[repr(simd)]
#[derive(Copy, Clone)]
struct C<T, const N: usize>([T; N]);


extern "rust-intrinsic" {
    fn simd_add<T>(x: T, y: T) -> T;
}

fn add<T: ops::Add<Output=T>>(lhs: T, rhs: T) -> T {
    lhs + rhs
}

impl ops::Add for f32x4 {
    type Output = f32x4;

    fn add(self, rhs: f32x4) -> f32x4 {
        unsafe { simd_add(self, rhs) }
    }
}

impl ops::Add for A<4> {
    type Output = Self;

    fn add(self, rhs: Self) -> Self {
        unsafe { simd_add(self, rhs) }
    }
}

impl ops::Add for B<f32> {
    type Output = Self;

    fn add(self, rhs: Self) -> Self {
        unsafe { simd_add(self, rhs) }
    }
}

impl ops::Add for C<f32, 4> {
    type Output = Self;

    fn add(self, rhs: Self) -> Self {
        unsafe { simd_add(self, rhs) }
    }
}


pub fn main() {
    let x = [1.0f32, 2.0f32, 3.0f32, 4.0f32];
    let y = [2.0f32, 4.0f32, 6.0f32, 8.0f32];

    // lame-o
    let a = f32x4([1.0f32, 2.0f32, 3.0f32, 4.0f32]);
    let f32x4([a0, a1, a2, a3]) = add(a, a);
    assert_eq!(a0, 2.0f32);
    assert_eq!(a1, 4.0f32);
    assert_eq!(a2, 6.0f32);
    assert_eq!(a3, 8.0f32);

    let a = A(x);
    assert_eq!(add(a, a).0, y);

    let b = B(x);
    assert_eq!(add(b, b).0, y);

    let c = C(x);
    assert_eq!(add(c, c).0, y);
}