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
|
use std::cell::Ref;
use std::ops::{Deref, DerefMut};
pub trait Sortable
{
type Item;
fn sort_by_key_b<Key, Func>(&mut self, func: Func)
where
Func: FnMut(&Self::Item) -> Key,
Key: Ord;
}
impl<Item> Sortable for [Item]
{
type Item = Item;
fn sort_by_key_b<Key, Func>(&mut self, func: Func)
where
Func: FnMut(&Self::Item) -> Key,
Key: Ord,
{
self.sort_by_key(func)
}
}
impl<Item, const LENGTH: usize> Sortable for [Item; LENGTH]
{
type Item = Item;
fn sort_by_key_b<Key, Func>(&mut self, func: Func)
where
Func: FnMut(&Self::Item) -> Key,
Key: Ord,
{
self.sort_by_key(func)
}
}
impl<Item> Sortable for Vec<Item>
{
type Item = Item;
fn sort_by_key_b<Key, Func>(&mut self, func: Func)
where
Func: FnMut(&Self::Item) -> Key,
Key: Ord,
{
self.sort_by_key(func)
}
}
#[derive(Debug)]
pub struct RefCellRefMap<'a, Value: 'a, MappedValue: 'a>
{
mapped_value: MappedValue,
_refcell_ref: Ref<'a, Value>,
}
impl<'a, Value: 'a, MappedValue: 'a> RefCellRefMap<'a, Value, MappedValue>
{
pub fn new(
refcell_ref: Ref<'a, Value>,
map_fn: impl Fn(&'a Value) -> MappedValue,
) -> Self
{
// Convert the lifetime to 'static. This is necessary to make the compiler not
// complain about refcell_ref being moved
//
// SAFETY: This is fine since we pass it to map_fn with the original lifetime 'a
let val_ref = unsafe { &*(&*refcell_ref as *const Value) };
let mapped_value = map_fn(val_ref);
Self {
mapped_value,
_refcell_ref: refcell_ref,
}
}
}
impl<'a, Value: 'a, MappedValue: 'a> Deref for RefCellRefMap<'a, Value, MappedValue>
{
type Target = MappedValue;
fn deref(&self) -> &Self::Target
{
&self.mapped_value
}
}
impl<'a, Value: 'a, MappedValue: 'a> DerefMut for RefCellRefMap<'a, Value, MappedValue>
{
fn deref_mut(&mut self) -> &mut Self::Target
{
&mut self.mapped_value
}
}
|