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 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
//! A lock-free concurrent object pool.
//!
//! See the [`Pool` type's documentation][pool] for details on the object pool API and how
//! it differs from the [`Slab`] API.
//!
//! [pool]: ../struct.Pool.html
//! [`Slab`]: ../struct.Slab.html
use crate::{
cfg::{self, CfgPrivate, DefaultConfig},
clear::Clear,
page, shard,
tid::Tid,
Pack, Shard,
};
use std::{fmt, marker::PhantomData, sync::Arc};
/// A lock-free concurrent object pool.
///
/// Slabs provide pre-allocated storage for many instances of a single type. But, when working with
/// heap allocated objects, the advantages of a slab are lost, as the memory allocated for the
/// object is freed when the object is removed from the slab. With a pool, we can instead reuse
/// this memory for objects being added to the pool in the future, therefore reducing memory
/// fragmentation and avoiding additional allocations.
///
/// This type implements a lock-free concurrent pool, indexed by `usize`s. The items stored in this
/// type need to implement [`Clear`] and `Default`.
///
/// The `Pool` type shares similar semantics to [`Slab`] when it comes to sharing across threads
/// and storing mutable shared data. The biggest difference is there are no [`Slab::insert`] and
/// [`Slab::take`] analouges for the `Pool` type. Instead new items are added to the pool by using
/// the [`Pool::create`] method, and marked for clearing by the [`Pool::clear`] method.
///
/// # Examples
///
/// Add an entry to the pool, returning an index:
/// ```
/// # use sharded_slab::Pool;
/// let pool: Pool<String> = Pool::new();
///
/// let key = pool.create_with(|item| item.push_str("hello world")).unwrap();
/// assert_eq!(pool.get(key).unwrap(), String::from("hello world"));
/// ```
///
/// Create a new pooled item, returning a guard that allows mutable access:
/// ```
/// # use sharded_slab::Pool;
/// let pool: Pool<String> = Pool::new();
///
/// let mut guard = pool.create().unwrap();
/// let key = guard.key();
/// guard.push_str("hello world");
///
/// drop(guard); // release the guard, allowing immutable access.
/// assert_eq!(pool.get(key).unwrap(), String::from("hello world"));
/// ```
///
/// Pool entries can be cleared by calling [`Pool::clear`]. This marks the entry to
/// be cleared when the guards referencing to it are dropped.
/// ```
/// # use sharded_slab::Pool;
/// let pool: Pool<String> = Pool::new();
///
/// let key = pool.create_with(|item| item.push_str("hello world")).unwrap();
///
/// // Mark this entry to be cleared.
/// pool.clear(key);
///
/// // The cleared entry is no longer available in the pool
/// assert!(pool.get(key).is_none());
/// ```
/// # Configuration
///
/// Both `Pool` and [`Slab`] share the same configuration mechanism. See [crate level documentation][config-doc]
/// for more details.
///
/// [`Slab::take`]: ../struct.Slab.html#method.take
/// [`Slab::insert`]: ../struct.Slab.html#method.insert
/// [`Pool::create`]: struct.Pool.html#method.create
/// [`Pool::clear`]: struct.Pool.html#method.clear
/// [config-doc]: ../index.html#configuration
/// [`Clear`]: trait.Clear.html
/// [`Slab`]: struct.Slab.html
pub struct Pool<T, C = DefaultConfig>
where
T: Clear + Default,
C: cfg::Config,
{
shards: shard::Array<T, C>,
_cfg: PhantomData<C>,
}
/// A guard that allows access to an object in a pool.
///
/// While the guard exists, it indicates to the pool that the item the guard references is
/// currently being accessed. If the item is removed from the pool while the guard exists, the
/// removal will be deferred until all guards are dropped.
pub struct Ref<'a, T, C = DefaultConfig>
where
T: Clear + Default,
C: cfg::Config,
{
inner: page::slot::Guard<T, C>,
shard: &'a Shard<T, C>,
key: usize,
}
/// A guard that allows exclusive mutable access to an object in a pool.
///
/// While the guard exists, it indicates to the pool that the item the guard
/// references is currently being accessed. If the item is removed from the pool
/// while a guard exists, the removal will be deferred until the guard is
/// dropped. The slot cannot be accessed by other threads while it is accessed
/// mutably.
pub struct RefMut<'a, T, C = DefaultConfig>
where
T: Clear + Default,
C: cfg::Config,
{
inner: page::slot::InitGuard<T, C>,
shard: &'a Shard<T, C>,
key: usize,
}
/// An owned guard that allows shared immutable access to an object in a pool.
///
/// While the guard exists, it indicates to the pool that the item the guard references is
/// currently being accessed. If the item is removed from the pool while the guard exists, the
/// removal will be deferred until all guards are dropped.
///
/// Unlike [`Ref`], which borrows the pool, an `OwnedRef` clones the `Arc`
/// around the pool. Therefore, it keeps the pool from being dropped until all
/// such guards have been dropped. This means that an `OwnedRef` may be held for
/// an arbitrary lifetime.
///
///
/// # Examples
///
/// ```
/// # use sharded_slab::Pool;
/// use std::sync::Arc;
///
/// let pool: Arc<Pool<String>> = Arc::new(Pool::new());
/// let key = pool.create_with(|item| item.push_str("hello world")).unwrap();
///
/// // Look up the created `Key`, returning an `OwnedRef`.
/// let value = pool.clone().get_owned(key).unwrap();
///
/// // Now, the original `Arc` clone of the pool may be dropped, but the
/// // returned `OwnedRef` can still access the value.
/// assert_eq!(value, String::from("hello world"));
/// ```
///
/// Unlike [`Ref`], an `OwnedRef` may be stored in a struct which must live
/// for the `'static` lifetime:
///
/// ```
/// # use sharded_slab::Pool;
/// use sharded_slab::pool::OwnedRef;
/// use std::sync::Arc;
///
/// pub struct MyStruct {
/// pool_ref: OwnedRef<String>,
/// // ... other fields ...
/// }
///
/// // Suppose this is some arbitrary function which requires a value that
/// // lives for the 'static lifetime...
/// fn function_requiring_static<T: 'static>(t: &T) {
/// // ... do something extremely important and interesting ...
/// }
///
/// let pool: Arc<Pool<String>> = Arc::new(Pool::new());
/// let key = pool.create_with(|item| item.push_str("hello world")).unwrap();
///
/// // Look up the created `Key`, returning an `OwnedRef`.
/// let pool_ref = pool.clone().get_owned(key).unwrap();
/// let my_struct = MyStruct {
/// pool_ref,
/// // ...
/// };
///
/// // We can use `my_struct` anywhere where it is required to have the
/// // `'static` lifetime:
/// function_requiring_static(&my_struct);
/// ```
///
/// `OwnedRef`s may be sent between threads:
///
/// ```
/// # use sharded_slab::Pool;
/// use std::{thread, sync::Arc};
///
/// let pool: Arc<Pool<String>> = Arc::new(Pool::new());
/// let key = pool.create_with(|item| item.push_str("hello world")).unwrap();
///
/// // Look up the created `Key`, returning an `OwnedRef`.
/// let value = pool.clone().get_owned(key).unwrap();
///
/// thread::spawn(move || {
/// assert_eq!(value, String::from("hello world"));
/// // ...
/// }).join().unwrap();
/// ```
///
/// [`Ref`]: crate::pool::Ref
pub struct OwnedRef<T, C = DefaultConfig>
where
T: Clear + Default,
C: cfg::Config,
{
inner: page::slot::Guard<T, C>,
pool: Arc<Pool<T, C>>,
key: usize,
}
/// An owned guard that allows exclusive, mutable access to an object in a pool.
///
/// An `OwnedRefMut<T>` functions more or less identically to an owned
/// `Box<T>`: it can be passed to functions, stored in structure fields, and
/// borrowed mutably or immutably, and can be owned for arbitrary lifetimes.
/// The difference is that, unlike a `Box<T>`, the memory allocation for the
/// `T` lives in the `Pool`; when an `OwnedRefMut` is created, it may reuse
/// memory that was allocated for a previous pooled object that has been
/// cleared. Additionally, the `OwnedRefMut` may be [downgraded] to an
/// [`OwnedRef`] which may be shared freely, essentially turning the `Box`
/// into an `Arc`.
///
/// This is returned by [`Pool::create_owned`].
///
/// While the guard exists, it indicates to the pool that the item the guard
/// references is currently being accessed. If the item is removed from the pool
/// while the guard exists, theremoval will be deferred until all guards are
/// dropped.
///
/// Unlike [`RefMut`], which borrows the pool, an `OwnedRefMut` clones the `Arc`
/// around the pool. Therefore, it keeps the pool from being dropped until all
/// such guards have been dropped. This means that an `OwnedRefMut` may be held for
/// an arbitrary lifetime.
///
/// # Examples
///
/// ```rust
/// # use sharded_slab::Pool;
/// # use std::thread;
/// use std::sync::Arc;
///
/// let pool: Arc<Pool<String>> = Arc::new(Pool::new());
///
/// // Create a new pooled item, returning an owned guard that allows mutable
/// // access to the new item.
/// let mut item = pool.clone().create_owned().unwrap();
/// // Return a key that allows indexing the created item once the guard
/// // has been dropped.
/// let key = item.key();
///
/// // Mutate the item.
/// item.push_str("Hello");
/// // Drop the guard, releasing mutable access to the new item.
/// drop(item);
///
/// /// Other threads may now (immutably) access the item using the returned key.
/// thread::spawn(move || {
/// assert_eq!(pool.get(key).unwrap(), String::from("Hello"));
/// }).join().unwrap();
/// ```
///
/// ```rust
/// # use sharded_slab::Pool;
/// use std::sync::Arc;
///
/// let pool: Arc<Pool<String>> = Arc::new(Pool::new());
///
/// // Create a new item, returning an owned, mutable guard.
/// let mut value = pool.clone().create_owned().unwrap();
///
/// // Now, the original `Arc` clone of the pool may be dropped, but the
/// // returned `OwnedRefMut` can still access the value.
/// drop(pool);
///
/// value.push_str("hello world");
/// assert_eq!(value, String::from("hello world"));
/// ```
///
/// Unlike [`RefMut`], an `OwnedRefMut` may be stored in a struct which must live
/// for the `'static` lifetime:
///
/// ```
/// # use sharded_slab::Pool;
/// use sharded_slab::pool::OwnedRefMut;
/// use std::sync::Arc;
///
/// pub struct MyStruct {
/// pool_ref: OwnedRefMut<String>,
/// // ... other fields ...
/// }
///
/// // Suppose this is some arbitrary function which requires a value that
/// // lives for the 'static lifetime...
/// fn function_requiring_static<T: 'static>(t: &T) {
/// // ... do something extremely important and interesting ...
/// }
///
/// let pool: Arc<Pool<String>> = Arc::new(Pool::new());
///
/// // Create a new item, returning a mutable owned reference.
/// let pool_ref = pool.clone().create_owned().unwrap();
///
/// let my_struct = MyStruct {
/// pool_ref,
/// // ...
/// };
///
/// // We can use `my_struct` anywhere where it is required to have the
/// // `'static` lifetime:
/// function_requiring_static(&my_struct);
/// ```
///
/// `OwnedRefMut`s may be sent between threads:
///
/// ```
/// # use sharded_slab::Pool;
/// use std::{thread, sync::Arc};
///
/// let pool: Arc<Pool<String>> = Arc::new(Pool::new());
///
/// let mut value = pool.clone().create_owned().unwrap();
/// let key = value.key();
///
/// thread::spawn(move || {
/// value.push_str("hello world");
/// // ...
/// }).join().unwrap();
///
/// // Once the `OwnedRefMut` has been dropped by the other thread, we may
/// // now access the value immutably on this thread.
///
/// assert_eq!(pool.get(key).unwrap(), String::from("hello world"));
/// ```
///
/// Downgrading from a mutable to an immutable reference:
///
/// ```
/// # use sharded_slab::Pool;
/// use std::{thread, sync::Arc};
///
/// let pool: Arc<Pool<String>> = Arc::new(Pool::new());
///
/// let mut value = pool.clone().create_owned().unwrap();
/// let key = value.key();
/// value.push_str("hello world");
///
/// // Downgrade the mutable owned ref to an immutable owned ref.
/// let value = value.downgrade();
///
/// // Once the `OwnedRefMut` has been downgraded, other threads may
/// // immutably access the pooled value:
/// thread::spawn(move || {
/// assert_eq!(pool.get(key).unwrap(), String::from("hello world"));
/// }).join().unwrap();
///
/// // This thread can still access the pooled value through the
/// // immutable owned ref:
/// assert_eq!(value, String::from("hello world"));
/// ```
///
/// [`Pool::create_owned`]: crate::Pool::create_owned
/// [`RefMut`]: crate::pool::RefMut
/// [`OwnedRefMut`]: crate::pool::OwnedRefMut
/// [downgraded]: crate::pool::OwnedRefMut::downgrade
pub struct OwnedRefMut<T, C = DefaultConfig>
where
T: Clear + Default,
C: cfg::Config,
{
inner: page::slot::InitGuard<T, C>,
pool: Arc<Pool<T, C>>,
key: usize,
}
impl<T> Pool<T>
where
T: Clear + Default,
{
/// Returns a new `Pool` with the default configuration parameters.
pub fn new() -> Self {
Self::new_with_config()
}
/// Returns a new `Pool` with the provided configuration parameters.
pub fn new_with_config<C: cfg::Config>() -> Pool<T, C> {
C::validate();
Pool {
shards: shard::Array::new(),
_cfg: PhantomData,
}
}
}
impl<T, C> Pool<T, C>
where
T: Clear + Default,
C: cfg::Config,
{
/// The number of bits in each index which are used by the pool.
///
/// If other data is packed into the `usize` indices returned by
/// [`Pool::create`], user code is free to use any bits higher than the
/// `USED_BITS`-th bit freely.
///
/// This is determined by the [`Config`] type that configures the pool's
/// parameters. By default, all bits are used; this can be changed by
/// overriding the [`Config::RESERVED_BITS`][res] constant.
///
/// [`Config`]: trait.Config.html
/// [res]: trait.Config.html#associatedconstant.RESERVED_BITS
/// [`Slab::insert`]: struct.Slab.html#method.insert
pub const USED_BITS: usize = C::USED_BITS;
/// Creates a new object in the pool, returning an [`RefMut`] guard that
/// may be used to mutate the new object.
///
/// If this function returns `None`, then the shard for the current thread is full and no items
/// can be added until some are removed, or the maximum number of shards has been reached.
///
/// # Examples
/// ```rust
/// # use sharded_slab::Pool;
/// # use std::thread;
/// let pool: Pool<String> = Pool::new();
///
/// // Create a new pooled item, returning a guard that allows mutable
/// // access to the new item.
/// let mut item = pool.create().unwrap();
/// // Return a key that allows indexing the created item once the guard
/// // has been dropped.
/// let key = item.key();
///
/// // Mutate the item.
/// item.push_str("Hello");
/// // Drop the guard, releasing mutable access to the new item.
/// drop(item);
///
/// /// Other threads may now (immutably) access the item using the returned key.
/// thread::spawn(move || {
/// assert_eq!(pool.get(key).unwrap(), String::from("Hello"));
/// }).join().unwrap();
/// ```
///
/// [`RefMut`]: pool/struct.RefMut.html
pub fn create(&self) -> Option<RefMut<'_, T, C>> {
let (tid, shard) = self.shards.current();
test_println!("pool: create {:?}", tid);
let (key, inner) = shard.init_with(|idx, slot| {
let guard = slot.init()?;
let gen = guard.generation();
Some((gen.pack(idx), guard))
})?;
Some(RefMut {
inner,
key: tid.pack(key),
shard,
})
}
/// Creates a new object in the pool, returning an [`OwnedRefMut`] guard that
/// may be used to mutate the new object.
///
/// If this function returns `None`, then the shard for the current thread
/// is full and no items can be added until some are removed, or the maximum
/// number of shards has been reached.
///
/// Unlike [`create`], which borrows the pool, this method _clones_ the `Arc`
/// around the pool if a value exists for the given key. This means that the
/// returned [`OwnedRefMut`] can be held for an arbitrary lifetime. However,
/// this method requires that the pool itself be wrapped in an `Arc`.
///
/// An `OwnedRefMut<T>` functions more or less identically to an owned
/// `Box<T>`: it can be passed to functions, stored in structure fields, and
/// borrowed mutably or immutably, and can be owned for arbitrary lifetimes.
/// The difference is that, unlike a `Box<T>`, the memory allocation for the
/// `T` lives in the `Pool`; when an `OwnedRefMut` is created, it may reuse
/// memory that was allocated for a previous pooled object that has been
/// cleared. Additionally, the `OwnedRefMut` may be [downgraded] to an
/// [`OwnedRef`] which may be shared freely, essentially turning the `Box`
/// into an `Arc`.
///
/// # Examples
///
/// ```rust
/// # use sharded_slab::Pool;
/// # use std::thread;
/// use std::sync::Arc;
///
/// let pool: Arc<Pool<String>> = Arc::new(Pool::new());
///
/// // Create a new pooled item, returning an owned guard that allows mutable
/// // access to the new item.
/// let mut item = pool.clone().create_owned().unwrap();
/// // Return a key that allows indexing the created item once the guard
/// // has been dropped.
/// let key = item.key();
///
/// // Mutate the item.
/// item.push_str("Hello");
/// // Drop the guard, releasing mutable access to the new item.
/// drop(item);
///
/// /// Other threads may now (immutably) access the item using the returned key.
/// thread::spawn(move || {
/// assert_eq!(pool.get(key).unwrap(), String::from("Hello"));
/// }).join().unwrap();
/// ```
///
/// ```rust
/// # use sharded_slab::Pool;
/// use std::sync::Arc;
///
/// let pool: Arc<Pool<String>> = Arc::new(Pool::new());
///
/// // Create a new item, returning an owned, mutable guard.
/// let mut value = pool.clone().create_owned().unwrap();
///
/// // Now, the original `Arc` clone of the pool may be dropped, but the
/// // returned `OwnedRefMut` can still access the value.
/// drop(pool);
///
/// value.push_str("hello world");
/// assert_eq!(value, String::from("hello world"));
/// ```
///
/// Unlike [`RefMut`], an `OwnedRefMut` may be stored in a struct which must live
/// for the `'static` lifetime:
///
/// ```
/// # use sharded_slab::Pool;
/// use sharded_slab::pool::OwnedRefMut;
/// use std::sync::Arc;
///
/// pub struct MyStruct {
/// pool_ref: OwnedRefMut<String>,
/// // ... other fields ...
/// }
///
/// // Suppose this is some arbitrary function which requires a value that
/// // lives for the 'static lifetime...
/// fn function_requiring_static<T: 'static>(t: &T) {
/// // ... do something extremely important and interesting ...
/// }
///
/// let pool: Arc<Pool<String>> = Arc::new(Pool::new());
///
/// // Create a new item, returning a mutable owned reference.
/// let pool_ref = pool.clone().create_owned().unwrap();
///
/// let my_struct = MyStruct {
/// pool_ref,
/// // ...
/// };
///
/// // We can use `my_struct` anywhere where it is required to have the
/// // `'static` lifetime:
/// function_requiring_static(&my_struct);
/// ```
///
/// `OwnedRefMut`s may be sent between threads:
///
/// ```
/// # use sharded_slab::Pool;
/// use std::{thread, sync::Arc};
///
/// let pool: Arc<Pool<String>> = Arc::new(Pool::new());
///
/// let mut value = pool.clone().create_owned().unwrap();
/// let key = value.key();
///
/// thread::spawn(move || {
/// value.push_str("hello world");
/// // ...
/// }).join().unwrap();
///
/// // Once the `OwnedRefMut` has been dropped by the other thread, we may
/// // now access the value immutably on this thread.
///
/// assert_eq!(pool.get(key).unwrap(), String::from("hello world"));
/// ```
///
/// Downgrading from a mutable to an immutable reference:
///
/// ```
/// # use sharded_slab::Pool;
/// use std::{thread, sync::Arc};
///
/// let pool: Arc<Pool<String>> = Arc::new(Pool::new());
///
/// let mut value = pool.clone().create_owned().unwrap();
/// let key = value.key();
/// value.push_str("hello world");
///
/// // Downgrade the mutable owned ref to an immutable owned ref.
/// let value = value.downgrade();
///
/// // Once the `OwnedRefMut` has been downgraded, other threads may
/// // immutably access the pooled value:
/// thread::spawn(move || {
/// assert_eq!(pool.get(key).unwrap(), String::from("hello world"));
/// }).join().unwrap();
///
/// // This thread can still access the pooled value through the
/// // immutable owned ref:
/// assert_eq!(value, String::from("hello world"));
/// ```
///
/// [`create`]: Pool::create
/// [`OwnedRef`]: crate::pool::OwnedRef
/// [`RefMut`]: crate::pool::RefMut
/// [`OwnedRefMut`]: crate::pool::OwnedRefMut
/// [downgraded]: crate::pool::OwnedRefMut::downgrade
pub fn create_owned(self: Arc<Self>) -> Option<OwnedRefMut<T, C>> {
let (tid, shard) = self.shards.current();
test_println!("pool: create_owned {:?}", tid);
let (inner, key) = shard.init_with(|idx, slot| {
let inner = slot.init()?;
let gen = inner.generation();
Some((inner, tid.pack(gen.pack(idx))))
})?;
Some(OwnedRefMut {
inner,
pool: self,
key,
})
}
/// Creates a new object in the pool with the provided initializer,
/// returning a key that may be used to access the new object.
///
/// If this function returns `None`, then the shard for the current thread is full and no items
/// can be added until some are removed, or the maximum number of shards has been reached.
///
/// # Examples
/// ```rust
/// # use sharded_slab::Pool;
/// # use std::thread;
/// let pool: Pool<String> = Pool::new();
///
/// // Create a new pooled item, returning its integer key.
/// let key = pool.create_with(|s| s.push_str("Hello")).unwrap();
///
/// /// Other threads may now (immutably) access the item using the key.
/// thread::spawn(move || {
/// assert_eq!(pool.get(key).unwrap(), String::from("Hello"));
/// }).join().unwrap();
/// ```
pub fn create_with(&self, init: impl FnOnce(&mut T)) -> Option<usize> {
test_println!("pool: create_with");
let mut guard = self.create()?;
init(&mut guard);
Some(guard.key())
}
/// Return a borrowed reference to the value associated with the given key.
///
/// If the pool does not contain a value for the given key, `None` is returned instead.
///
/// # Examples
///
/// ```rust
/// # use sharded_slab::Pool;
/// let pool: Pool<String> = Pool::new();
/// let key = pool.create_with(|item| item.push_str("hello world")).unwrap();
///
/// assert_eq!(pool.get(key).unwrap(), String::from("hello world"));
/// assert!(pool.get(12345).is_none());
/// ```
pub fn get(&self, key: usize) -> Option<Ref<'_, T, C>> {
let tid = C::unpack_tid(key);
test_println!("pool: get{:?}; current={:?}", tid, Tid::<C>::current());
let shard = self.shards.get(tid.as_usize())?;
let inner = shard.with_slot(key, |slot| slot.get(C::unpack_gen(key)))?;
Some(Ref { inner, shard, key })
}
/// Return an owned reference to the value associated with the given key.
///
/// If the pool does not contain a value for the given key, `None` is
/// returned instead.
///
/// Unlike [`get`], which borrows the pool, this method _clones_ the `Arc`
/// around the pool if a value exists for the given key. This means that the
/// returned [`OwnedRef`] can be held for an arbitrary lifetime. However,
/// this method requires that the pool itself be wrapped in an `Arc`.
///
/// # Examples
///
/// ```rust
/// # use sharded_slab::Pool;
/// use std::sync::Arc;
///
/// let pool: Arc<Pool<String>> = Arc::new(Pool::new());
/// let key = pool.create_with(|item| item.push_str("hello world")).unwrap();
///
/// // Look up the created `Key`, returning an `OwnedRef`.
/// let value = pool.clone().get_owned(key).unwrap();
///
/// // Now, the original `Arc` clone of the pool may be dropped, but the
/// // returned `OwnedRef` can still access the value.
/// assert_eq!(value, String::from("hello world"));
/// ```
///
/// Unlike [`Ref`], an `OwnedRef` may be stored in a struct which must live
/// for the `'static` lifetime:
///
/// ```
/// # use sharded_slab::Pool;
/// use sharded_slab::pool::OwnedRef;
/// use std::sync::Arc;
///
/// pub struct MyStruct {
/// pool_ref: OwnedRef<String>,
/// // ... other fields ...
/// }
///
/// // Suppose this is some arbitrary function which requires a value that
/// // lives for the 'static lifetime...
/// fn function_requiring_static<T: 'static>(t: &T) {
/// // ... do something extremely important and interesting ...
/// }
///
/// let pool: Arc<Pool<String>> = Arc::new(Pool::new());
/// let key = pool.create_with(|item| item.push_str("hello world")).unwrap();
///
/// // Look up the created `Key`, returning an `OwnedRef`.
/// let pool_ref = pool.clone().get_owned(key).unwrap();
/// let my_struct = MyStruct {
/// pool_ref,
/// // ...
/// };
///
/// // We can use `my_struct` anywhere where it is required to have the
/// // `'static` lifetime:
/// function_requiring_static(&my_struct);
/// ```
///
/// `OwnedRef`s may be sent between threads:
///
/// ```
/// # use sharded_slab::Pool;
/// use std::{thread, sync::Arc};
///
/// let pool: Arc<Pool<String>> = Arc::new(Pool::new());
/// let key = pool.create_with(|item| item.push_str("hello world")).unwrap();
///
/// // Look up the created `Key`, returning an `OwnedRef`.
/// let value = pool.clone().get_owned(key).unwrap();
///
/// thread::spawn(move || {
/// assert_eq!(value, String::from("hello world"));
/// // ...
/// }).join().unwrap();
/// ```
///
/// [`get`]: Pool::get
/// [`OwnedRef`]: crate::pool::OwnedRef
/// [`Ref`]: crate::pool::Ref
pub fn get_owned(self: Arc<Self>, key: usize) -> Option<OwnedRef<T, C>> {
let tid = C::unpack_tid(key);
test_println!("pool: get{:?}; current={:?}", tid, Tid::<C>::current());
let shard = self.shards.get(tid.as_usize())?;
let inner = shard.with_slot(key, |slot| slot.get(C::unpack_gen(key)))?;
Some(OwnedRef {
inner,
pool: self.clone(),
key,
})
}
/// Remove the value using the storage associated with the given key from the pool, returning
/// `true` if the value was removed.
///
/// This method does _not_ block the current thread until the value can be
/// cleared. Instead, if another thread is currently accessing that value, this marks it to be
/// cleared by that thread when it is done accessing that value.
///
/// # Examples
///
/// ```rust
/// # use sharded_slab::Pool;
/// let pool: Pool<String> = Pool::new();
///
/// // Check out an item from the pool.
/// let mut item = pool.create().unwrap();
/// let key = item.key();
/// item.push_str("hello world");
/// drop(item);
///
/// assert_eq!(pool.get(key).unwrap(), String::from("hello world"));
///
/// pool.clear(key);
/// assert!(pool.get(key).is_none());
/// ```
///
/// ```
/// # use sharded_slab::Pool;
/// let pool: Pool<String> = Pool::new();
///
/// let key = pool.create_with(|item| item.push_str("Hello world!")).unwrap();
///
/// // Clearing a key that doesn't exist in the `Pool` will return `false`
/// assert_eq!(pool.clear(key + 69420), false);
///
/// // Clearing a key that does exist returns `true`
/// assert!(pool.clear(key));
///
/// // Clearing a key that has previously been cleared will return `false`
/// assert_eq!(pool.clear(key), false);
/// ```
/// [`clear`]: #method.clear
pub fn clear(&self, key: usize) -> bool {
let tid = C::unpack_tid(key);
let shard = self.shards.get(tid.as_usize());
if tid.is_current() {
shard
.map(|shard| shard.mark_clear_local(key))
.unwrap_or(false)
} else {
shard
.map(|shard| shard.mark_clear_remote(key))
.unwrap_or(false)
}
}
}
unsafe impl<T, C> Send for Pool<T, C>
where
T: Send + Clear + Default,
C: cfg::Config,
{
}
unsafe impl<T, C> Sync for Pool<T, C>
where
T: Sync + Clear + Default,
C: cfg::Config,
{
}
impl<T> Default for Pool<T>
where
T: Clear + Default,
{
fn default() -> Self {
Self::new()
}
}
impl<T, C> fmt::Debug for Pool<T, C>
where
T: fmt::Debug + Clear + Default,
C: cfg::Config,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Pool")
.field("shards", &self.shards)
.field("config", &C::debug())
.finish()
}
}
// === impl Ref ===
impl<'a, T, C> Ref<'a, T, C>
where
T: Clear + Default,
C: cfg::Config,
{
/// Returns the key used to access this guard
pub fn key(&self) -> usize {
self.key
}
#[inline]
fn value(&self) -> &T {
unsafe {
// Safety: calling `slot::Guard::value` is unsafe, since the `Guard`
// value contains a pointer to the slot that may outlive the slab
// containing that slot. Here, the `Ref` has a borrowed reference to
// the shard containing that slot, which ensures that the slot will
// not be dropped while this `Guard` exists.
self.inner.value()
}
}
}
impl<'a, T, C> std::ops::Deref for Ref<'a, T, C>
where
T: Clear + Default,
C: cfg::Config,
{
type Target = T;
fn deref(&self) -> &Self::Target {
self.value()
}
}
impl<'a, T, C> Drop for Ref<'a, T, C>
where
T: Clear + Default,
C: cfg::Config,
{
fn drop(&mut self) {
test_println!("drop Ref: try clearing data");
let should_clear = unsafe {
// Safety: calling `slot::Guard::release` is unsafe, since the
// `Guard` value contains a pointer to the slot that may outlive the
// slab containing that slot. Here, the `Ref` guard owns a
// borrowed reference to the shard containing that slot, which
// ensures that the slot will not be dropped while this `Ref`
// exists.
self.inner.release()
};
if should_clear {
self.shard.clear_after_release(self.key);
}
}
}
impl<'a, T, C> fmt::Debug for Ref<'a, T, C>
where
T: fmt::Debug + Clear + Default,
C: cfg::Config,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self.value(), f)
}
}
impl<'a, T, C> PartialEq<T> for Ref<'a, T, C>
where
T: PartialEq<T> + Clear + Default,
C: cfg::Config,
{
fn eq(&self, other: &T) -> bool {
*self.value() == *other
}
}
// === impl GuardMut ===
impl<'a, T, C: cfg::Config> RefMut<'a, T, C>
where
T: Clear + Default,
C: cfg::Config,
{
/// Returns the key used to access the guard.
pub fn key(&self) -> usize {
self.key
}
/// Downgrades the mutable guard to an immutable guard, allowing access to
/// the pooled value from other threads.
///
/// ## Examples
///
/// ```
/// # use sharded_slab::Pool;
/// # use std::{sync::Arc, thread};
/// let pool = Arc::new(Pool::<String>::new());
///
/// let mut guard_mut = pool.clone().create_owned().unwrap();
/// let key = guard_mut.key();
/// guard_mut.push_str("Hello");
///
/// // The pooled string is currently borrowed mutably, so other threads
/// // may not access it.
/// let pool2 = pool.clone();
/// thread::spawn(move || {
/// assert!(pool2.get(key).is_none())
/// }).join().unwrap();
///
/// // Downgrade the guard to an immutable reference.
/// let guard = guard_mut.downgrade();
///
/// // Now, other threads may also access the pooled value.
/// let pool2 = pool.clone();
/// thread::spawn(move || {
/// let guard = pool2.get(key)
/// .expect("the item may now be referenced by other threads");
/// assert_eq!(guard, String::from("Hello"));
/// }).join().unwrap();
///
/// // We can still access the value immutably through the downgraded guard.
/// assert_eq!(guard, String::from("Hello"));
/// ```
pub fn downgrade(mut self) -> Ref<'a, T, C> {
let inner = unsafe { self.inner.downgrade() };
Ref {
inner,
shard: self.shard,
key: self.key,
}
}
#[inline]
fn value(&self) -> &T {
unsafe {
// Safety: we are holding a reference to the shard which keeps the
// pointed slot alive. The returned reference will not outlive
// `self`.
self.inner.value()
}
}
}
impl<'a, T, C: cfg::Config> std::ops::Deref for RefMut<'a, T, C>
where
T: Clear + Default,
C: cfg::Config,
{
type Target = T;
fn deref(&self) -> &Self::Target {
self.value()
}
}
impl<'a, T, C> std::ops::DerefMut for RefMut<'a, T, C>
where
T: Clear + Default,
C: cfg::Config,
{
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe {
// Safety: we are holding a reference to the shard which keeps the
// pointed slot alive. The returned reference will not outlive `self`.
self.inner.value_mut()
}
}
}
impl<'a, T, C> Drop for RefMut<'a, T, C>
where
T: Clear + Default,
C: cfg::Config,
{
fn drop(&mut self) {
test_println!(" -> drop RefMut: try clearing data");
let should_clear = unsafe {
// Safety: we are holding a reference to the shard which keeps the
// pointed slot alive. The returned reference will not outlive `self`.
self.inner.release()
};
if should_clear {
self.shard.clear_after_release(self.key);
}
}
}
impl<'a, T, C> fmt::Debug for RefMut<'a, T, C>
where
T: fmt::Debug + Clear + Default,
C: cfg::Config,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self.value(), f)
}
}
impl<'a, T, C> PartialEq<T> for RefMut<'a, T, C>
where
T: PartialEq<T> + Clear + Default,
C: cfg::Config,
{
fn eq(&self, other: &T) -> bool {
self.value().eq(other)
}
}
// === impl OwnedRef ===
impl<T, C> OwnedRef<T, C>
where
T: Clear + Default,
C: cfg::Config,
{
/// Returns the key used to access this guard
pub fn key(&self) -> usize {
self.key
}
#[inline]
fn value(&self) -> &T {
unsafe {
// Safety: calling `slot::Guard::value` is unsafe, since the `Guard`
// value contains a pointer to the slot that may outlive the slab
// containing that slot. Here, the `Ref` has a borrowed reference to
// the shard containing that slot, which ensures that the slot will
// not be dropped while this `Guard` exists.
self.inner.value()
}
}
}
impl<T, C> std::ops::Deref for OwnedRef<T, C>
where
T: Clear + Default,
C: cfg::Config,
{
type Target = T;
fn deref(&self) -> &Self::Target {
self.value()
}
}
impl<T, C> Drop for OwnedRef<T, C>
where
T: Clear + Default,
C: cfg::Config,
{
fn drop(&mut self) {
test_println!("drop OwnedRef: try clearing data");
let should_clear = unsafe {
// Safety: calling `slot::Guard::release` is unsafe, since the
// `Guard` value contains a pointer to the slot that may outlive the
// slab containing that slot. Here, the `OwnedRef` owns an `Arc`
// clone of the pool, which keeps it alive as long as the `OwnedRef`
// exists.
self.inner.release()
};
if should_clear {
let shard_idx = Tid::<C>::from_packed(self.key);
test_println!("-> shard={:?}", shard_idx);
if let Some(shard) = self.pool.shards.get(shard_idx.as_usize()) {
shard.clear_after_release(self.key);
} else {
test_println!("-> shard={:?} does not exist! THIS IS A BUG", shard_idx);
debug_assert!(std::thread::panicking(), "[internal error] tried to drop an `OwnedRef` to a slot on a shard that never existed!");
}
}
}
}
impl<T, C> fmt::Debug for OwnedRef<T, C>
where
T: fmt::Debug + Clear + Default,
C: cfg::Config,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self.value(), f)
}
}
impl<T, C> PartialEq<T> for OwnedRef<T, C>
where
T: PartialEq<T> + Clear + Default,
C: cfg::Config,
{
fn eq(&self, other: &T) -> bool {
*self.value() == *other
}
}
unsafe impl<T, C> Sync for OwnedRef<T, C>
where
T: Sync + Clear + Default,
C: cfg::Config,
{
}
unsafe impl<T, C> Send for OwnedRef<T, C>
where
T: Sync + Clear + Default,
C: cfg::Config,
{
}
// === impl OwnedRefMut ===
impl<T, C> OwnedRefMut<T, C>
where
T: Clear + Default,
C: cfg::Config,
{
/// Returns the key used to access this guard
pub fn key(&self) -> usize {
self.key
}
/// Downgrades the owned mutable guard to an owned immutable guard, allowing
/// access to the pooled value from other threads.
///
/// ## Examples
///
/// ```
/// # use sharded_slab::Pool;
/// # use std::{sync::Arc, thread};
/// let pool = Arc::new(Pool::<String>::new());
///
/// let mut guard_mut = pool.clone().create_owned().unwrap();
/// let key = guard_mut.key();
/// guard_mut.push_str("Hello");
///
/// // The pooled string is currently borrowed mutably, so other threads
/// // may not access it.
/// let pool2 = pool.clone();
/// thread::spawn(move || {
/// assert!(pool2.get(key).is_none())
/// }).join().unwrap();
///
/// // Downgrade the guard to an immutable reference.
/// let guard = guard_mut.downgrade();
///
/// // Now, other threads may also access the pooled value.
/// let pool2 = pool.clone();
/// thread::spawn(move || {
/// let guard = pool2.get(key)
/// .expect("the item may now be referenced by other threads");
/// assert_eq!(guard, String::from("Hello"));
/// }).join().unwrap();
///
/// // We can still access the value immutably through the downgraded guard.
/// assert_eq!(guard, String::from("Hello"));
/// ```
pub fn downgrade(mut self) -> OwnedRef<T, C> {
let inner = unsafe { self.inner.downgrade() };
OwnedRef {
inner,
pool: self.pool.clone(),
key: self.key,
}
}
fn shard(&self) -> Option<&Shard<T, C>> {
let shard_idx = Tid::<C>::from_packed(self.key);
test_println!("-> shard={:?}", shard_idx);
self.pool.shards.get(shard_idx.as_usize())
}
#[inline]
fn value(&self) -> &T {
unsafe {
// Safety: calling `slot::InitGuard::value` is unsafe, since the `Guard`
// value contains a pointer to the slot that may outlive the slab
// containing that slot. Here, the `OwnedRefMut` has an `Arc` clone of
// the shard containing that slot, which ensures that the slot will
// not be dropped while this `Guard` exists.
self.inner.value()
}
}
}
impl<T, C> std::ops::Deref for OwnedRefMut<T, C>
where
T: Clear + Default,
C: cfg::Config,
{
type Target = T;
fn deref(&self) -> &Self::Target {
self.value()
}
}
impl<T, C> std::ops::DerefMut for OwnedRefMut<T, C>
where
T: Clear + Default,
C: cfg::Config,
{
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe {
// Safety: calling `slot::InitGuard::value_mut` is unsafe, since the
// `Guard` value contains a pointer to the slot that may outlive
// the slab containing that slot. Here, the `OwnedRefMut` has an
// `Arc` clone of the shard containing that slot, which ensures that
// the slot will not be dropped while this `Guard` exists.
self.inner.value_mut()
}
}
}
impl<T, C> Drop for OwnedRefMut<T, C>
where
T: Clear + Default,
C: cfg::Config,
{
fn drop(&mut self) {
test_println!("drop OwnedRefMut: try clearing data");
let should_clear = unsafe {
// Safety: calling `slot::Guard::release` is unsafe, since the
// `Guard` value contains a pointer to the slot that may outlive the
// slab containing that slot. Here, the `OwnedRefMut` owns an `Arc`
// clone of the pool, which keeps it alive as long as the
// `OwnedRefMut` exists.
self.inner.release()
};
if should_clear {
if let Some(shard) = self.shard() {
shard.clear_after_release(self.key);
} else {
test_println!("-> shard does not exist! THIS IS A BUG");
debug_assert!(std::thread::panicking(), "[internal error] tried to drop an `OwnedRefMut` to a slot on a shard that never existed!");
}
}
}
}
impl<T, C> fmt::Debug for OwnedRefMut<T, C>
where
T: fmt::Debug + Clear + Default,
C: cfg::Config,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self.value(), f)
}
}
impl<T, C> PartialEq<T> for OwnedRefMut<T, C>
where
T: PartialEq<T> + Clear + Default,
C: cfg::Config,
{
fn eq(&self, other: &T) -> bool {
*self.value() == *other
}
}
unsafe impl<T, C> Sync for OwnedRefMut<T, C>
where
T: Sync + Clear + Default,
C: cfg::Config,
{
}
unsafe impl<T, C> Send for OwnedRefMut<T, C>
where
T: Sync + Clear + Default,
C: cfg::Config,
{
}