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
use std::{
rc::Rc,
marker::PhantomData,
};
use crate::{
Prm, Buffer, Shape,
};
#[derive(Clone, Copy, Debug)]
pub struct Range {
pub start: isize,
pub end: isize,
pub step: isize,
}
#[derive(Clone, Copy, Debug)]
pub enum Index {
Single(isize),
Range(Range),
NewAxis,
}
pub trait Tensor<T: Prm>: Sized {
type Buffer : Buffer<T>;
unsafe fn new_uninit_in(context: &<Self::Buffer as Buffer<T>>::Context, shape: &Shape) -> Self;
fn new_filled_in(context: &<Self::Buffer as Buffer<T>>::Context, shape: &Shape, value: T) -> Self;
fn new_zeroed_in(context: &<Self::Buffer as Buffer<T>>::Context, shape: &Shape) -> Self;
fn shape(&self) -> &Shape;
fn reshape(&self, shape: &Shape) -> Self;
fn load(&self, dst: &mut [T]);
fn store(&mut self, src: &[T]);
}
pub struct CommonTensor<T: Prm, Buf: Buffer<T>> {
pub buffer: Rc<Buf>,
pub shape: Shape,
phantom: PhantomData<T>,
}
impl<T: Prm, Buf: Buffer<T>> CommonTensor<T, Buf> {
pub fn from_shared_buffer(rc_buffer: Rc<Buf>, shape: &Shape) -> Self {
Self {
buffer: rc_buffer,
shape: shape.clone(),
phantom: PhantomData::<T>,
}
}
pub fn from_buffer(buffer: Buf, shape: &Shape) -> Self {
assert_eq!(buffer.len(), shape.iter().product());
Self::from_shared_buffer(Rc::new(buffer), shape)
}
pub fn buffer(&self) -> &Buf {
self.buffer.as_ref()
}
pub fn buffer_mut(&mut self) -> &mut Buf {
Rc::make_mut(&mut self.buffer)
}
}
impl<T: Prm, Buf: Buffer<T>> Tensor<T> for CommonTensor<T, Buf> {
type Buffer = Buf;
unsafe fn new_uninit_in(context: &Buf::Context, shape: &Shape) -> Self {
Self::from_buffer(
Self::Buffer::new_uninit_in(context, shape.iter().product()),
shape,
)
}
fn new_filled_in(context: &Buf::Context, shape: &Shape, value: T) -> Self {
Self::from_buffer(
Self::Buffer::new_filled_in(context, shape.iter().product(), value),
shape,
)
}
fn new_zeroed_in(context: &Buf::Context, shape: &Shape) -> Self {
Self::new_filled_in(context, shape, T::zero())
}
fn shape(&self) -> &Shape {
&self.shape
}
fn reshape(&self, shape: &Shape) -> Self {
Self::from_shared_buffer(self.buffer.clone(), shape)
}
fn load(&self, dst: &mut [T]) {
self.buffer.load(dst);
}
fn store(&mut self, src: &[T]) {
Rc::make_mut(&mut self.buffer).store(src);
}
}