This repository was archived by the owner on Oct 9, 2022. It is now read-only.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflexarray.rs
More file actions
Latest commit
76 lines (63 loc) · 1.7 KB
/
Copy pathflexarray.rs
File metadata and controls
76 lines (63 loc) · 1.7 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
structFlexArrayField<T>([T, ..0]);
traitFlexArray<T>{
fnlen(&self) -> uint;
fnflex_element<'r>(&'rself) -> &'rFlexArrayField<T>;
fnallocate(base:Self) -> Box<Self>{
use std::mem::{min_align_of, size_of, transmute};
use std::rt::heap;
unsafe{
let size = size_of::<Self>() + base.len()*size_of::<T>();
let mem = heap::allocate(size,min_align_of::<Self>());
letmut result:Box<Self> = transmute(mem);
*result = base;
result
}
}
fnas_slice<'r>(&'rself) -> &'r[T]{
use std::mem::transmute;
use std::raw::Slice;
unsafe{
transmute::<Slice<T>,_>(Slice{
data:transmute(self.flex_element()),
len:self.len(),
})
}
}
fnas_mut_slice<'r>(&'rmutself) -> &'rmut[T]{
use std::mem::transmute;
use std::raw::Slice;
unsafe{
transmute::<Slice<T>,_>(Slice{
data:transmute(self.flex_element()),
len:self.len(),
})
}
}
}
#[repr(C)]
structFoo{
some_param:u8,
length:u8,
info:FlexArrayField<uint>,
}
implFlexArray<uint>forFoo{
fnlen(&self) -> uint{
self.lengthasuint
}
fnflex_element<'r>(&'rself) -> &'rFlexArrayField<uint>{
&self.info
}
}
fnmain(){
letmut foo:Box<Foo> = FlexArray::allocate(Foo{
some_param:8,
length:8,
info:FlexArrayField([])
});
for(i, elem)in foo.as_mut_slice().mut_iter().enumerate(){
*elem = 2* i;
}
for elem in foo.as_slice().iter(){
println!("{}", elem);
}
}