author | alfadur |
Wed, 28 Aug 2019 00:34:26 +0300 | |
changeset 15376 | 24a9afbf33c6 |
parent 15374 | 0f2fd8d12734 |
child 15377 | 7a3ed957cee9 |
permissions | -rw-r--r-- |
15359 | 1 |
use super::common::GearId; |
2 |
use std::{ |
|
3 |
any::TypeId, |
|
4 |
mem::{size_of, MaybeUninit}, |
|
5 |
num::NonZeroU16, |
|
15373 | 6 |
ptr::{copy_nonoverlapping, null_mut, NonNull}, |
15359 | 7 |
slice, |
8 |
}; |
|
15310 | 9 |
|
15373 | 10 |
pub trait TypeTuple: Sized { |
15310 | 11 |
fn len() -> usize; |
12 |
fn get_types(dest: &mut Vec<TypeId>); |
|
15373 | 13 |
unsafe fn iter<F: FnMut(Self)>(slices: &[*mut u8], count: usize, mut f: F); |
15310 | 14 |
} |
15 |
||
15374 | 16 |
macro_rules! type_tuple_impl { |
17 |
($($n: literal: $t: ident),+) => { |
|
18 |
impl<$($t: 'static),+> TypeTuple for ($(&$t),+,) { |
|
15373 | 19 |
fn len() -> usize { |
15374 | 20 |
[$({TypeId::of::<$t>(); 1}),+].iter().sum() |
15373 | 21 |
} |
22 |
||
23 |
fn get_types(types: &mut Vec<TypeId>) { |
|
15374 | 24 |
$(types.push(TypeId::of::<$t>()));+ |
15373 | 25 |
} |
15310 | 26 |
|
15376 | 27 |
unsafe fn iter<F: FnMut(Self)>(slices: &[*mut u8], count: usize, mut f: F) { |
15373 | 28 |
for i in 0..count { |
29 |
unsafe { |
|
15374 | 30 |
f(($(&*(*slices.get_unchecked($n) as *mut $t).add(i)),+,)); |
15373 | 31 |
} |
32 |
} |
|
33 |
} |
|
34 |
} |
|
15359 | 35 |
|
15374 | 36 |
impl<$($t: 'static),+> TypeTuple for ($(&mut $t),+,) { |
15373 | 37 |
fn len() -> usize { |
15374 | 38 |
[$({TypeId::of::<$t>(); 1}),+].iter().sum() |
15373 | 39 |
} |
40 |
||
41 |
fn get_types(types: &mut Vec<TypeId>) { |
|
15374 | 42 |
$(types.push(TypeId::of::<$t>()));+ |
15373 | 43 |
} |
44 |
||
15376 | 45 |
unsafe fn iter<F: FnMut(Self)>(slices: &[*mut u8], count: usize, mut f: F) { |
15373 | 46 |
for i in 0..count { |
47 |
unsafe { |
|
15374 | 48 |
f(($(&mut *(*slices.get_unchecked($n) as *mut $t).add(i)),+,)); |
15373 | 49 |
} |
50 |
} |
|
51 |
} |
|
15359 | 52 |
} |
53 |
} |
|
15310 | 54 |
} |
55 |
||
15374 | 56 |
type_tuple_impl!(0: A); |
57 |
type_tuple_impl!(0: A, 1: B); |
|
58 |
type_tuple_impl!(0: A, 1: B, 2: C); |
|
59 |
type_tuple_impl!(0: A, 1: B, 2: C, 3: D); |
|
60 |
type_tuple_impl!(0: A, 1: B, 2: C, 3: D, 4: E); |
|
15373 | 61 |
|
15359 | 62 |
const BLOCK_SIZE: usize = 32768; |
63 |
||
64 |
struct DataBlock { |
|
65 |
max_elements: u16, |
|
66 |
elements_count: u16, |
|
67 |
data: Box<[u8; BLOCK_SIZE]>, |
|
15363 | 68 |
component_blocks: [Option<NonNull<u8>>; 64], |
15310 | 69 |
} |
70 |
||
15359 | 71 |
impl Unpin for DataBlock {} |
72 |
||
73 |
impl DataBlock { |
|
74 |
fn new(mask: u64, element_sizes: &[u16; 64]) -> Self { |
|
75 |
let total_size: u16 = element_sizes |
|
76 |
.iter() |
|
77 |
.enumerate() |
|
15363 | 78 |
.filter(|(i, _)| mask & (1 << *i as u64) != 0) |
15359 | 79 |
.map(|(_, size)| *size) |
80 |
.sum(); |
|
81 |
let max_elements = (BLOCK_SIZE / total_size as usize) as u16; |
|
82 |
||
83 |
let mut data: Box<[u8; BLOCK_SIZE]> = |
|
15362 | 84 |
Box::new(unsafe { MaybeUninit::uninit().assume_init() }); |
15359 | 85 |
let mut blocks = [None; 64]; |
86 |
let mut offset = 0; |
|
87 |
||
88 |
for i in 0..64 { |
|
15363 | 89 |
if mask & (1 << i) != 0 { |
15359 | 90 |
blocks[i] = Some(NonNull::new(data[offset..].as_mut_ptr()).unwrap()); |
91 |
offset += element_sizes[i] as usize * max_elements as usize; |
|
92 |
} |
|
93 |
} |
|
15310 | 94 |
Self { |
15359 | 95 |
elements_count: 0, |
96 |
max_elements, |
|
97 |
data, |
|
15363 | 98 |
component_blocks: blocks, |
15310 | 99 |
} |
100 |
} |
|
101 |
||
15359 | 102 |
fn is_full(&self) -> bool { |
103 |
self.elements_count == self.max_elements |
|
104 |
} |
|
15310 | 105 |
} |
106 |
||
15359 | 107 |
#[derive(Clone, Copy, Debug, Default)] |
108 |
pub struct LookupEntry { |
|
109 |
index: Option<NonZeroU16>, |
|
110 |
block_index: u16, |
|
15310 | 111 |
} |
112 |
||
113 |
pub struct GearDataManager { |
|
114 |
types: Vec<TypeId>, |
|
15359 | 115 |
blocks: Vec<DataBlock>, |
116 |
block_masks: Vec<u64>, |
|
117 |
element_sizes: Box<[u16; 64]>, |
|
118 |
lookup: Box<[LookupEntry]>, |
|
15310 | 119 |
} |
120 |
||
121 |
impl GearDataManager { |
|
122 |
pub fn new() -> Self { |
|
123 |
Self { |
|
124 |
types: vec![], |
|
15359 | 125 |
blocks: vec![], |
126 |
block_masks: vec![], |
|
127 |
element_sizes: Box::new([0; 64]), |
|
128 |
lookup: vec![LookupEntry::default(); u16::max_value() as usize].into_boxed_slice(), |
|
129 |
} |
|
130 |
} |
|
131 |
||
132 |
#[inline] |
|
133 |
fn get_type_index<T: 'static>(&self) -> Option<usize> { |
|
134 |
let type_id = TypeId::of::<T>(); |
|
135 |
self.types.iter().position(|id| *id == type_id) |
|
136 |
} |
|
137 |
||
138 |
fn move_between_blocks(&mut self, from_block_index: u16, from_index: u16, to_block_index: u16) { |
|
15362 | 139 |
debug_assert!(from_block_index != to_block_index); |
15359 | 140 |
let source_mask = self.block_masks[from_block_index as usize]; |
141 |
let destination_mask = self.block_masks[to_block_index as usize]; |
|
142 |
debug_assert!(source_mask & destination_mask == source_mask); |
|
143 |
||
144 |
let source = &self.blocks[from_block_index as usize]; |
|
145 |
let destination = &self.blocks[to_block_index as usize]; |
|
15362 | 146 |
debug_assert!(from_index < source.elements_count); |
147 |
debug_assert!(!destination.is_full()); |
|
148 |
||
15359 | 149 |
for i in 0..64 { |
15363 | 150 |
if source_mask & 1 << i != 0 { |
15362 | 151 |
unsafe { |
152 |
copy_nonoverlapping( |
|
15363 | 153 |
source.component_blocks[i].unwrap().as_ptr(), |
154 |
destination.component_blocks[i].unwrap().as_ptr(), |
|
15362 | 155 |
self.element_sizes[i] as usize, |
156 |
); |
|
157 |
} |
|
158 |
} |
|
15359 | 159 |
} |
15362 | 160 |
self.blocks[from_block_index as usize].elements_count -= 1; |
161 |
self.blocks[to_block_index as usize].elements_count += 1; |
|
15359 | 162 |
} |
163 |
||
15361 | 164 |
fn add_to_block<T: Clone>(&mut self, block_index: u16, value: &T) { |
165 |
debug_assert!(self.block_masks[block_index as usize].count_ones() == 1); |
|
166 |
||
167 |
let block = &mut self.blocks[block_index as usize]; |
|
168 |
debug_assert!(block.elements_count < block.max_elements); |
|
169 |
||
170 |
unsafe { |
|
171 |
let slice = slice::from_raw_parts_mut( |
|
172 |
block.data.as_mut_ptr() as *mut T, |
|
173 |
block.max_elements as usize, |
|
174 |
); |
|
175 |
*slice.get_unchecked_mut(block.elements_count as usize) = value.clone(); |
|
176 |
}; |
|
177 |
block.elements_count += 1; |
|
15359 | 178 |
} |
179 |
||
180 |
fn remove_from_block(&mut self, block_index: u16, index: u16) { |
|
15361 | 181 |
let block = &mut self.blocks[block_index as usize]; |
182 |
debug_assert!(index < block.elements_count); |
|
183 |
||
184 |
for (i, size) in self.element_sizes.iter().cloned().enumerate() { |
|
185 |
if index < block.elements_count - 1 { |
|
15363 | 186 |
if let Some(ptr) = block.component_blocks[i] { |
15361 | 187 |
unsafe { |
15362 | 188 |
copy_nonoverlapping( |
15361 | 189 |
ptr.as_ptr() |
190 |
.add((size * (block.elements_count - 1)) as usize), |
|
191 |
ptr.as_ptr().add((size * index) as usize), |
|
192 |
size as usize, |
|
193 |
); |
|
194 |
} |
|
195 |
} |
|
196 |
} |
|
197 |
} |
|
198 |
block.elements_count -= 1; |
|
15359 | 199 |
} |
200 |
||
201 |
#[inline] |
|
15363 | 202 |
fn ensure_block(&mut self, mask: u64) -> u16 { |
15359 | 203 |
if let Some(index) = self |
204 |
.block_masks |
|
205 |
.iter() |
|
206 |
.enumerate() |
|
207 |
.position(|(i, m)| *m == mask && !self.blocks[i].is_full()) |
|
208 |
{ |
|
209 |
index as u16 |
|
210 |
} else { |
|
211 |
self.blocks.push(DataBlock::new(mask, &self.element_sizes)); |
|
15363 | 212 |
self.block_masks.push(mask); |
15359 | 213 |
(self.blocks.len() - 1) as u16 |
214 |
} |
|
215 |
} |
|
216 |
||
217 |
pub fn add<T: Clone + 'static>(&mut self, gear_id: GearId, value: &T) { |
|
218 |
if let Some(type_index) = self.get_type_index::<T>() { |
|
15363 | 219 |
let type_bit = 1 << type_index as u64; |
15359 | 220 |
let entry = self.lookup[gear_id.get() as usize - 1]; |
221 |
||
222 |
if let Some(index) = entry.index { |
|
223 |
let mask = self.block_masks[entry.block_index as usize]; |
|
224 |
let new_mask = mask | type_bit; |
|
225 |
||
226 |
if new_mask != mask { |
|
15363 | 227 |
let dest_block_index = self.ensure_block(new_mask); |
15359 | 228 |
self.move_between_blocks(entry.block_index, index.get() - 1, dest_block_index); |
229 |
} |
|
230 |
} else { |
|
15363 | 231 |
let dest_block_index = self.ensure_block(type_bit); |
15359 | 232 |
self.add_to_block(dest_block_index, value); |
233 |
} |
|
234 |
} else { |
|
235 |
panic!("Unregistered type") |
|
236 |
} |
|
237 |
} |
|
238 |
||
239 |
pub fn remove<T: 'static>(&mut self, gear_id: GearId) { |
|
240 |
if let Some(type_index) = self.get_type_index::<T>() { |
|
241 |
let entry = self.lookup[gear_id.get() as usize - 1]; |
|
242 |
if let Some(index) = entry.index { |
|
15362 | 243 |
let destination_mask = |
15363 | 244 |
self.block_masks[entry.block_index as usize] & !(1 << type_index as u64); |
15362 | 245 |
|
246 |
if destination_mask == 0 { |
|
247 |
self.remove_all(gear_id) |
|
248 |
} else { |
|
15363 | 249 |
let destination_block_index = self.ensure_block(destination_mask); |
15362 | 250 |
self.move_between_blocks( |
251 |
entry.block_index, |
|
252 |
index.get() - 1, |
|
253 |
destination_block_index, |
|
254 |
); |
|
255 |
} |
|
15359 | 256 |
} |
15362 | 257 |
} else { |
258 |
panic!("Unregistered type") |
|
259 |
} |
|
260 |
} |
|
261 |
||
262 |
pub fn remove_all(&mut self, gear_id: GearId) { |
|
263 |
let entry = self.lookup[gear_id.get() as usize - 1]; |
|
264 |
if let Some(index) = entry.index { |
|
265 |
self.remove_from_block(entry.block_index, index.get() - 1); |
|
15310 | 266 |
} |
267 |
} |
|
268 |
||
269 |
pub fn register<T: 'static>(&mut self) { |
|
15361 | 270 |
debug_assert!(!std::mem::needs_drop::<T>()); |
271 |
debug_assert!(self.types.len() <= 64); |
|
272 |
debug_assert!(size_of::<T>() <= u16::max_value() as usize); |
|
15359 | 273 |
|
15310 | 274 |
let id = TypeId::of::<T>(); |
275 |
if !self.types.contains(&id) { |
|
15359 | 276 |
self.element_sizes[self.types.len()] = size_of::<T>() as u16; |
15310 | 277 |
self.types.push(id); |
278 |
} |
|
279 |
} |
|
280 |
||
15372
d6b4586b271f
make sure component slice order corresponds to the type args
alfadur
parents:
15363
diff
changeset
|
281 |
pub fn iter<T: TypeTuple + 'static, F: FnMut(T)>(&self, mut f: F) { |
d6b4586b271f
make sure component slice order corresponds to the type args
alfadur
parents:
15363
diff
changeset
|
282 |
let mut arg_types = Vec::with_capacity(64); |
d6b4586b271f
make sure component slice order corresponds to the type args
alfadur
parents:
15363
diff
changeset
|
283 |
T::get_types(&mut arg_types); |
d6b4586b271f
make sure component slice order corresponds to the type args
alfadur
parents:
15363
diff
changeset
|
284 |
|
d6b4586b271f
make sure component slice order corresponds to the type args
alfadur
parents:
15363
diff
changeset
|
285 |
let mut type_indices = vec![-1i8; arg_types.len()]; |
d6b4586b271f
make sure component slice order corresponds to the type args
alfadur
parents:
15363
diff
changeset
|
286 |
let mut selector = 0u64; |
d6b4586b271f
make sure component slice order corresponds to the type args
alfadur
parents:
15363
diff
changeset
|
287 |
|
d6b4586b271f
make sure component slice order corresponds to the type args
alfadur
parents:
15363
diff
changeset
|
288 |
for (arg_index, type_id) in arg_types.iter().enumerate() { |
d6b4586b271f
make sure component slice order corresponds to the type args
alfadur
parents:
15363
diff
changeset
|
289 |
match self.types.iter().position(|t| t == type_id) { |
d6b4586b271f
make sure component slice order corresponds to the type args
alfadur
parents:
15363
diff
changeset
|
290 |
Some(i) if selector & 1 << i as u64 != 0 => panic!("Duplicate type"), |
d6b4586b271f
make sure component slice order corresponds to the type args
alfadur
parents:
15363
diff
changeset
|
291 |
Some(i) => { |
d6b4586b271f
make sure component slice order corresponds to the type args
alfadur
parents:
15363
diff
changeset
|
292 |
type_indices[arg_index] = i as i8; |
d6b4586b271f
make sure component slice order corresponds to the type args
alfadur
parents:
15363
diff
changeset
|
293 |
selector &= 1 << i as u64; |
15373 | 294 |
} |
295 |
None => panic!("Unregistered type"), |
|
15310 | 296 |
} |
297 |
} |
|
298 |
||
15372
d6b4586b271f
make sure component slice order corresponds to the type args
alfadur
parents:
15363
diff
changeset
|
299 |
let mut slices = vec![null_mut(); arg_types.len()]; |
15363 | 300 |
|
15359 | 301 |
for (block_index, mask) in self.block_masks.iter().enumerate() { |
302 |
if mask & selector == selector { |
|
303 |
let block = &self.blocks[block_index]; |
|
15363 | 304 |
|
15372
d6b4586b271f
make sure component slice order corresponds to the type args
alfadur
parents:
15363
diff
changeset
|
305 |
for (arg_index, type_index) in type_indices.iter().cloned().enumerate() { |
15373 | 306 |
slices[arg_index as usize] = block.component_blocks[type_index as usize] |
307 |
.unwrap() |
|
308 |
.as_ptr() |
|
15359 | 309 |
} |
15363 | 310 |
|
311 |
unsafe { |
|
312 |
T::iter(&slices[..], block.elements_count as usize, |x| f(x)); |
|
313 |
} |
|
15310 | 314 |
} |
315 |
} |
|
316 |
} |
|
317 |
} |
|
15359 | 318 |
|
319 |
#[cfg(test)] |
|
320 |
mod test { |
|
15363 | 321 |
use super::{super::common::GearId, GearDataManager}; |
15359 | 322 |
|
15363 | 323 |
#[derive(Clone)] |
15359 | 324 |
struct Datum { |
325 |
value: u32, |
|
326 |
} |
|
327 |
||
15376 | 328 |
#[derive(Clone)] |
329 |
struct Tag { |
|
330 |
nothing: u8, |
|
331 |
} |
|
332 |
||
15359 | 333 |
#[test] |
15363 | 334 |
fn single_component_iteration() { |
15359 | 335 |
let mut manager = GearDataManager::new(); |
336 |
manager.register::<Datum>(); |
|
15363 | 337 |
for i in 1..=5 { |
338 |
manager.add(GearId::new(i as u16).unwrap(), &Datum { value: i }); |
|
339 |
} |
|
340 |
||
341 |
let mut sum = 0; |
|
342 |
manager.iter(|(d,): (&Datum,)| sum += d.value); |
|
15373 | 343 |
assert_eq!(sum, 15); |
15363 | 344 |
|
15373 | 345 |
manager.iter(|(d,): (&mut Datum,)| d.value += 1); |
346 |
manager.iter(|(d,): (&Datum,)| sum += d.value); |
|
347 |
assert_eq!(sum, 35); |
|
15359 | 348 |
} |
15376 | 349 |
|
350 |
#[test] |
|
351 |
fn multiple_component_iteration() { |
|
352 |
let mut manager = GearDataManager::new(); |
|
353 |
manager.register::<Datum>(); |
|
354 |
manager.register::<Tag>(); |
|
355 |
for i in 1..=10 { |
|
356 |
let gear_id = GearId::new(i as u16).unwrap(); |
|
357 |
manager.add(gear_id, &Datum { value: i }); |
|
358 |
if i & 1 == 0 { |
|
359 |
manager.add(gear_id, &Tag { nothing: 0 }); |
|
360 |
} |
|
361 |
} |
|
362 |
||
363 |
let mut sum1 = 0; |
|
364 |
let mut sum2 = 0; |
|
365 |
manager.iter(|(d, _): (&Datum, &Tag)| sum1 += d.value); |
|
366 |
manager.iter(|(_, d): (&Tag, &Datum)| sum2 += d.value); |
|
367 |
assert_eq!(sum1, 30); |
|
368 |
assert_eq!(sum2, sum1); |
|
369 |
} |
|
15359 | 370 |
} |