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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
pub use self::KeyValue::*;
use core::prelude::*;
use alloc::heap;
use collections::TreeMap;
use core::cmp;
use core::kinds::marker;
use core::mem;
use core::ptr;
use core::fmt;
use core::cell::UnsafeCell;
use local::Local;
use task::{Task, LocalStorage};
pub type Key<T> = &'static KeyValue<T>;
#[allow(missing_docs)]
pub enum KeyValue<T> { KeyValueKey }
#[doc(hidden)]
pub type Map = TreeMap<uint, TLDValue>;
#[unsafe_no_drop_flag]
struct TLDValue {
box_ptr: *mut (),
drop_fn: unsafe fn(p: *mut ())
}
struct TLDValueBox<T> {
value: T,
refcount: UnsafeCell<uint>
}
unsafe fn get_local_map<'a>() -> Option<&'a mut Map> {
if !Local::exists(None::<Task>) { return None }
let task: *mut Task = Local::unsafe_borrow();
match &mut (*task).storage {
&LocalStorage(Some(ref mut map_ptr)) => {
return Some(map_ptr);
}
&LocalStorage(ref mut slot) => {
*slot = Some(TreeMap::new());
match *slot {
Some(ref mut map_ptr) => { return Some(map_ptr) }
None => panic!("unreachable code"),
}
}
}
}
pub struct Ref<T:'static> {
_inner: &'static TLDValueBox<T>,
_marker: marker::NoSend
}
fn key_to_key_value<T: 'static>(key: Key<T>) -> uint {
key as *const _ as uint
}
impl<T: 'static> KeyValue<T> {
pub fn replace(&'static self, data: Option<T>) -> Option<T> {
let map = match unsafe { get_local_map() } {
Some(map) => map,
None => panic!("must have a local task to insert into TLD"),
};
let keyval = key_to_key_value(self);
let data = match (map.get_mut(&keyval), data) {
(None, Some(data)) => {
data
}
(None, None) => {
return None
}
(Some(slot), data) => {
let value_box = slot.box_ptr as *mut TLDValueBox<T>;
let refcount = unsafe { *(*value_box).refcount.get() };
return match (refcount, data) {
(0, None) => {
None
}
(0, Some(new_value)) => {
unsafe {
ptr::write(&mut (*value_box).value, new_value);
*(*value_box).refcount.get() = 1;
None
}
}
(1, None) => {
unsafe {
let ret = ptr::read(&(*value_box).value);
*(*value_box).refcount.get() = 0;
Some(ret)
}
}
(1, Some(new_value)) => {
let value_ref = unsafe { &mut (*value_box).value };
let ret = mem::replace(value_ref, new_value);
Some(ret)
}
_ => {
panic!("TLD value cannot be replaced because it is already borrowed");
}
}
}
};
map.insert(keyval, TLDValue::new(data));
None
}
pub fn get(&'static self) -> Option<Ref<T>> {
let map = match unsafe { get_local_map() } {
Some(map) => map,
None => return None,
};
let keyval = key_to_key_value(self);
match map.get(&keyval) {
Some(slot) => {
let value_box = slot.box_ptr as *mut TLDValueBox<T>;
if unsafe { *(*value_box).refcount.get() } >= 1 {
unsafe {
*(*value_box).refcount.get() += 1;
Some(Ref {
_inner: &*value_box,
_marker: marker::NoSend
})
}
} else {
None
}
}
None => None
}
}
#[cfg(test)]
fn clear(&'static self) {
let map = match unsafe { get_local_map() } {
Some(map) => map,
None => return
};
let keyval = key_to_key_value(self);
self.replace(None);
map.remove(&keyval);
}
}
impl<T: 'static> Deref<T> for Ref<T> {
#[inline(always)]
fn deref<'a>(&'a self) -> &'a T {
&self._inner.value
}
}
impl<T: 'static + fmt::Show> fmt::Show for Ref<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
(**self).fmt(f)
}
}
impl<T: cmp::PartialEq + 'static> cmp::PartialEq for Ref<T> {
fn eq(&self, other: &Ref<T>) -> bool {
(**self).eq(&**other)
}
fn ne(&self, other: &Ref<T>) -> bool {
(**self).ne(&**other)
}
}
impl<T: cmp::Eq + 'static> cmp::Eq for Ref<T> {}
impl<T: cmp::PartialOrd + 'static> cmp::PartialOrd for Ref<T> {
fn partial_cmp(&self, other: &Ref<T>) -> Option<cmp::Ordering> {
(**self).partial_cmp(&**other)
}
fn lt(&self, other: &Ref<T>) -> bool { (**self).lt(&**other) }
fn le(&self, other: &Ref<T>) -> bool { (**self).le(&**other) }
fn gt(&self, other: &Ref<T>) -> bool { (**self).gt(&**other) }
fn ge(&self, other: &Ref<T>) -> bool { (**self).ge(&**other) }
}
impl<T: cmp::Ord + 'static> cmp::Ord for Ref<T> {
fn cmp(&self, other: &Ref<T>) -> cmp::Ordering {
(**self).cmp(&**other)
}
}
#[unsafe_destructor]
impl<T: 'static> Drop for Ref<T> {
fn drop(&mut self) {
unsafe {
*self._inner.refcount.get() -= 1;
}
}
}
impl TLDValue {
fn new<T>(value: T) -> TLDValue {
let box_ptr = unsafe {
let allocation = heap::allocate(mem::size_of::<TLDValueBox<T>>(),
mem::min_align_of::<TLDValueBox<T>>());
if allocation.is_null() { ::alloc::oom() }
let value_box = allocation as *mut TLDValueBox<T>;
ptr::write(value_box, TLDValueBox {
value: value,
refcount: UnsafeCell::new(1)
});
value_box as *mut ()
};
unsafe fn d<T>(p: *mut ()) {
let value_box = p as *mut TLDValueBox<T>;
debug_assert!(*(*value_box).refcount.get() < 2, "TLDValue destructed while borrowed");
struct Guard<T> {
p: *mut TLDValueBox<T>
}
#[unsafe_destructor]
impl<T> Drop for Guard<T> {
fn drop(&mut self) {
let size = mem::size_of::<TLDValueBox<T>>();
let align = mem::align_of::<TLDValueBox<T>>();
unsafe { heap::deallocate(self.p as *mut u8, size, align); }
}
}
let _guard = Guard::<T> { p: value_box };
if *(*value_box).refcount.get() != 0 {
ptr::read(&(*value_box).value);
}
}
TLDValue {
box_ptr: box_ptr,
drop_fn: d::<T>
}
}
}
impl Drop for TLDValue {
fn drop(&mut self) {
if !self.box_ptr.is_null() {
unsafe { (self.drop_fn)(self.box_ptr) }
}
}
}
#[cfg(test)]
mod tests {
extern crate test;
use std::prelude::*;
use super::*;
use std::task;
#[test]
fn test_tls_multitask() {
static MY_KEY: Key<String> = &KeyValueKey;
MY_KEY.replace(Some("parent data".to_string()));
task::spawn(proc() {
assert!(MY_KEY.get().is_none());
MY_KEY.replace(Some("child data".to_string()));
assert!(MY_KEY.get().as_ref().unwrap().as_slice() == "child data");
});
assert!(MY_KEY.get().unwrap().as_slice() == "parent data");
assert!(MY_KEY.get().unwrap().as_slice() == "parent data");
assert!(MY_KEY.get().unwrap().as_slice() == "parent data");
}
#[test]
fn test_tls_overwrite() {
static MY_KEY: Key<String> = &KeyValueKey;
MY_KEY.replace(Some("first data".to_string()));
MY_KEY.replace(Some("next data".to_string()));
assert!(MY_KEY.get().unwrap().as_slice() == "next data");
}
#[test]
fn test_tls_pop() {
static MY_KEY: Key<String> = &KeyValueKey;
MY_KEY.replace(Some("weasel".to_string()));
assert!(MY_KEY.replace(None).unwrap() == "weasel".to_string());
assert!(MY_KEY.replace(None).is_none());
}
#[test]
fn test_tls_crust_automorestack_memorial_bug() {
static MY_KEY: Key<String> = &KeyValueKey;
task::spawn(proc() {
MY_KEY.replace(Some("hax".to_string()));
});
}
#[test]
fn test_tls_multiple_types() {
static STR_KEY: Key<String> = &KeyValueKey;
static BOX_KEY: Key<Box<int>> = &KeyValueKey;
static INT_KEY: Key<int> = &KeyValueKey;
task::spawn(proc() {
STR_KEY.replace(Some("string data".to_string()));
BOX_KEY.replace(Some(box 0));
INT_KEY.replace(Some(42));
});
}
#[test]
fn test_tls_overwrite_multiple_types() {
static STR_KEY: Key<String> = &KeyValueKey;
static BOX_KEY: Key<Box<int>> = &KeyValueKey;
static INT_KEY: Key<int> = &KeyValueKey;
task::spawn(proc() {
STR_KEY.replace(Some("string data".to_string()));
STR_KEY.replace(Some("string data 2".to_string()));
BOX_KEY.replace(Some(box 0));
BOX_KEY.replace(Some(box 1));
INT_KEY.replace(Some(42));
INT_KEY.replace(Some(31337));
});
}
#[test]
#[should_fail]
fn test_tls_cleanup_on_panic() {
static STR_KEY: Key<String> = &KeyValueKey;
static BOX_KEY: Key<Box<int>> = &KeyValueKey;
static INT_KEY: Key<int> = &KeyValueKey;
STR_KEY.replace(Some("parent data".to_string()));
BOX_KEY.replace(Some(box 0));
task::spawn(proc() {
STR_KEY.replace(Some("string data".to_string()));
BOX_KEY.replace(Some(box 2));
INT_KEY.replace(Some(42));
panic!();
});
INT_KEY.replace(Some(31337));
panic!();
}
#[test]
fn test_cleanup_drops_values() {
let (tx, rx) = channel::<()>();
struct Dropper {
tx: Sender<()>
};
impl Drop for Dropper {
fn drop(&mut self) {
self.tx.send(());
}
}
static KEY: Key<Dropper> = &KeyValueKey;
let _ = task::try(proc() {
KEY.replace(Some(Dropper{ tx: tx }));
});
assert_eq!(rx.try_recv(), Ok(()));
}
#[test]
fn test_static_pointer() {
static KEY: Key<&'static int> = &KeyValueKey;
static VALUE: int = 0;
KEY.replace(Some(&VALUE));
}
#[test]
fn test_owned() {
static KEY: Key<Box<int>> = &KeyValueKey;
KEY.replace(Some(box 1));
{
let k1 = KEY.get().unwrap();
let k2 = KEY.get().unwrap();
let k3 = KEY.get().unwrap();
assert_eq!(**k1, 1);
assert_eq!(**k2, 1);
assert_eq!(**k3, 1);
}
KEY.replace(Some(box 2));
assert_eq!(**KEY.get().unwrap(), 2);
}
#[test]
fn test_same_key_type() {
static KEY1: Key<int> = &KeyValueKey;
static KEY2: Key<int> = &KeyValueKey;
static KEY3: Key<int> = &KeyValueKey;
static KEY4: Key<int> = &KeyValueKey;
static KEY5: Key<int> = &KeyValueKey;
KEY1.replace(Some(1));
KEY2.replace(Some(2));
KEY3.replace(Some(3));
KEY4.replace(Some(4));
KEY5.replace(Some(5));
assert_eq!(*KEY1.get().unwrap(), 1);
assert_eq!(*KEY2.get().unwrap(), 2);
assert_eq!(*KEY3.get().unwrap(), 3);
assert_eq!(*KEY4.get().unwrap(), 4);
assert_eq!(*KEY5.get().unwrap(), 5);
}
#[test]
#[should_fail]
fn test_nested_get_set1() {
static KEY: Key<int> = &KeyValueKey;
assert_eq!(KEY.replace(Some(4)), None);
let _k = KEY.get();
KEY.replace(Some(4));
}
struct ClearKey<T>(Key<T>);
#[unsafe_destructor]
impl<T: 'static> Drop for ClearKey<T> {
fn drop(&mut self) {
let ClearKey(ref key) = *self;
key.clear();
}
}
#[bench]
fn bench_replace_none(b: &mut test::Bencher) {
static KEY: Key<uint> = &KeyValueKey;
let _clear = ClearKey(KEY);
KEY.replace(None);
b.iter(|| {
KEY.replace(None)
});
}
#[bench]
fn bench_replace_some(b: &mut test::Bencher) {
static KEY: Key<uint> = &KeyValueKey;
let _clear = ClearKey(KEY);
KEY.replace(Some(1u));
b.iter(|| {
KEY.replace(Some(2))
});
}
#[bench]
fn bench_replace_none_some(b: &mut test::Bencher) {
static KEY: Key<uint> = &KeyValueKey;
let _clear = ClearKey(KEY);
KEY.replace(Some(0u));
b.iter(|| {
let old = KEY.replace(None).unwrap();
let new = old + 1;
KEY.replace(Some(new))
});
}
#[bench]
fn bench_100_keys_replace_last(b: &mut test::Bencher) {
static KEYS: [KeyValue<uint>, ..100] = [KeyValueKey, ..100];
let _clear = KEYS.iter().map(ClearKey).collect::<Vec<ClearKey<uint>>>();
for (i, key) in KEYS.iter().enumerate() {
key.replace(Some(i));
}
b.iter(|| {
let key: Key<uint> = &KEYS[99];
key.replace(Some(42))
});
}
#[bench]
fn bench_1000_keys_replace_last(b: &mut test::Bencher) {
static KEYS: [KeyValue<uint>, ..1000] = [KeyValueKey, ..1000];
let _clear = KEYS.iter().map(ClearKey).collect::<Vec<ClearKey<uint>>>();
for (i, key) in KEYS.iter().enumerate() {
key.replace(Some(i));
}
b.iter(|| {
let key: Key<uint> = &KEYS[999];
key.replace(Some(42))
});
for key in KEYS.iter() { key.clear(); }
}
#[bench]
fn bench_get(b: &mut test::Bencher) {
static KEY: Key<uint> = &KeyValueKey;
let _clear = ClearKey(KEY);
KEY.replace(Some(42));
b.iter(|| {
KEY.get()
});
}
#[bench]
fn bench_100_keys_get_last(b: &mut test::Bencher) {
static KEYS: [KeyValue<uint>, ..100] = [KeyValueKey, ..100];
let _clear = KEYS.iter().map(ClearKey).collect::<Vec<ClearKey<uint>>>();
for (i, key) in KEYS.iter().enumerate() {
key.replace(Some(i));
}
b.iter(|| {
let key: Key<uint> = &KEYS[99];
key.get()
});
}
#[bench]
fn bench_1000_keys_get_last(b: &mut test::Bencher) {
static KEYS: [KeyValue<uint>, ..1000] = [KeyValueKey, ..1000];
let _clear = KEYS.iter().map(ClearKey).collect::<Vec<ClearKey<uint>>>();
for (i, key) in KEYS.iter().enumerate() {
key.replace(Some(i));
}
b.iter(|| {
let key: Key<uint> = &KEYS[999];
key.get()
});
}
}