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
|
/*
* Copyright (C) 2020-2023 Fanout, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use slab::Slab;
use std::cell::{RefCell, RefMut};
use std::mem;
use std::ops::{Deref, DerefMut};
use std::sync::{Mutex, MutexGuard};
pub struct EntryGuard<'a, T> {
entries: RefMut<'a, Slab<T>>,
entry: &'a mut T,
key: usize,
}
impl<T> EntryGuard<'_, T> {
fn remove(mut self) {
self.entries.remove(self.key);
}
}
impl<T> Deref for EntryGuard<'_, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.entry
}
}
impl<T> DerefMut for EntryGuard<'_, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.entry
}
}
// this is essentially a sharable slab for use within a single thread.
// operations are protected by a RefCell. when an element is retrieved for
// reading or modification, it is wrapped in a EntryGuard which keeps the
// entire slab borrowed until the caller is done working with the element
pub struct Memory<T> {
entries: RefCell<Slab<T>>,
}
impl<T> Memory<T> {
pub fn new(capacity: usize) -> Self {
// allocate the slab with fixed capacity
let s = Slab::with_capacity(capacity);
Self {
entries: RefCell::new(s),
}
}
#[cfg(test)]
pub fn len(&self) -> usize {
let entries = self.entries.borrow();
entries.len()
}
fn insert(&self, e: T) -> Result<usize, ()> {
let mut entries = self.entries.borrow_mut();
// out of capacity. by preventing inserts beyond the capacity, we
// ensure the underlying memory won't get moved due to a realloc
if entries.len() == entries.capacity() {
return Err(());
}
Ok(entries.insert(e))
}
fn get<'a>(&'a self, key: usize) -> Option<EntryGuard<'a, T>> {
let mut entries = self.entries.borrow_mut();
let entry = entries.get_mut(key)?;
// slab element addresses are guaranteed to be stable once created,
// and the only place we remove the element is in EntryGuard's
// remove method which consumes itself, therefore it is safe to
// assume the element will live at least as long as the EntryGuard
// and we can extend the lifetime of the reference beyond the
// RefMut
let entry = unsafe { mem::transmute::<&mut T, &'a mut T>(entry) };
Some(EntryGuard {
entries,
entry,
key,
})
}
// for tests, as a way to confirm the memory isn't moving. be careful
// with this. the very first element inserted will be at index 0, but
// if the slab has been used and cleared, then the next element
// inserted may not be at index 0 and calling this method afterward
// will panic
#[cfg(test)]
fn entry0_ptr(&self) -> *const T {
let entries = self.entries.borrow();
entries.get(0).unwrap() as *const T
}
}
pub struct SyncEntryGuard<'a, T> {
entries: MutexGuard<'a, Slab<T>>,
entry: &'a mut T,
key: usize,
}
impl<T> SyncEntryGuard<'_, T> {
fn remove(mut self) {
self.entries.remove(self.key);
}
}
impl<T> Deref for SyncEntryGuard<'_, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.entry
}
}
impl<T> DerefMut for SyncEntryGuard<'_, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.entry
}
}
// this is essentially a thread-safe slab. operations are protected by a
// mutex. when an element is retrieved for reading or modification, it is
// wrapped in a EntryGuard which keeps the entire slab locked until the
// caller is done working with the element
pub struct SyncMemory<T> {
entries: Mutex<Slab<T>>,
}
impl<T> SyncMemory<T> {
pub fn new(capacity: usize) -> Self {
// allocate the slab with fixed capacity
let s = Slab::with_capacity(capacity);
Self {
entries: Mutex::new(s),
}
}
#[cfg(test)]
pub fn len(&self) -> usize {
let entries = self.entries.lock().unwrap();
entries.len()
}
fn insert(&self, e: T) -> Result<usize, ()> {
let mut entries = self.entries.lock().unwrap();
// out of capacity. by preventing inserts beyond the capacity, we
// ensure the underlying memory won't get moved due to a realloc
if entries.len() == entries.capacity() {
return Err(());
}
Ok(entries.insert(e))
}
fn get<'a>(&'a self, key: usize) -> Option<SyncEntryGuard<'a, T>> {
let mut entries = self.entries.lock().unwrap();
let entry = entries.get_mut(key)?;
// slab element addresses are guaranteed to be stable once created,
// and the only place we remove the element is in SyncEntryGuard's
// remove method which consumes itself, therefore it is safe to
// assume the element will live at least as long as the SyncEntryGuard
// and we can extend the lifetime of the reference beyond the
// MutexGuard
let entry = unsafe { mem::transmute::<&mut T, &'a mut T>(entry) };
Some(SyncEntryGuard {
entries,
entry,
key,
})
}
// for tests, as a way to confirm the memory isn't moving. be careful
// with this. the very first element inserted will be at index 0, but
// if the slab has been used and cleared, then the next element
// inserted may not be at index 0 and calling this method afterward
// will panic
#[cfg(test)]
fn entry0_ptr(&self) -> *const T {
let entries = self.entries.lock().unwrap();
entries.get(0).unwrap() as *const T
}
}
pub struct ReusableValue<T> {
reusable: std::sync::Arc<Reusable<T>>,
value: *mut T,
key: usize,
}
impl<T> ReusableValue<T> {
// vec element addresses are guaranteed to be stable once created,
// and elements are only removed when the Reusable is dropped, and
// the Arc'd Reusable is guaranteed to live as long as
// ReusableValue, therefore it is safe to assume the element will
// live at least as long as the ReusableValue
fn get(&self) -> &T {
unsafe { &*self.value }
}
fn get_mut(&mut self) -> &mut T {
unsafe { &mut *self.value }
}
}
impl<T> Drop for ReusableValue<T> {
fn drop(&mut self) {
let mut entries = self.reusable.entries.lock().unwrap();
entries.0.remove(self.key);
}
}
impl<T> Deref for ReusableValue<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.get()
}
}
impl<T> DerefMut for ReusableValue<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.get_mut()
}
}
// like Memory, but for preinitializing each value and reusing
pub struct Reusable<T> {
entries: Mutex<(Slab<()>, Vec<T>)>,
}
impl<T> Reusable<T> {
pub fn new<F>(capacity: usize, init_fn: F) -> Self
where
F: Fn() -> T,
{
let mut values = Vec::with_capacity(capacity);
for _ in 0..capacity {
values.push(init_fn());
}
// allocate the slab with fixed capacity
let s = Slab::with_capacity(capacity);
Self {
entries: Mutex::new((s, values)),
}
}
#[cfg(test)]
pub fn len(&self) -> usize {
let entries = self.entries.lock().unwrap();
entries.0.len()
}
#[allow(clippy::result_unit_err)]
pub fn reserve(self: &std::sync::Arc<Self>) -> Result<ReusableValue<T>, ()> {
let mut entries = self.entries.lock().unwrap();
// out of capacity. the number of buffers is fixed
if entries.0.len() == entries.0.capacity() {
return Err(());
}
let key = entries.0.insert(());
let value = &mut entries.1[key] as *mut T;
Ok(ReusableValue {
reusable: self.clone(),
value,
key,
})
}
}
pub struct RcEntry<T> {
value: T,
refs: usize,
}
pub type RcMemory<T> = Memory<RcEntry<T>>;
pub struct Rc<T> {
memory: std::rc::Rc<RcMemory<T>>,
key: usize,
}
impl<T> Rc<T> {
#[allow(clippy::result_unit_err)]
pub fn new(v: T, memory: &std::rc::Rc<RcMemory<T>>) -> Result<Self, ()> {
let key = memory.insert(RcEntry { value: v, refs: 1 })?;
Ok(Self {
memory: std::rc::Rc::clone(memory),
key,
})
}
#[allow(clippy::should_implement_trait)]
pub fn clone(rc: &Rc<T>) -> Self {
let mut e = rc.memory.get(rc.key).unwrap();
e.refs += 1;
Self {
memory: rc.memory.clone(),
key: rc.key,
}
}
pub fn get<'a>(&'a self) -> &'a T {
let e = self.memory.get(self.key).unwrap();
// get a reference to the inner value
let value = &e.value;
// entry addresses are guaranteed to be stable once created, and the
// entry managed by this Rc won't be dropped until this Rc drops,
// therefore it is safe to assume the entry managed by this Rc will
// live at least as long as this Rc, and we can extend the lifetime
// of the reference beyond the EntryGuard
unsafe { mem::transmute::<&T, &'a T>(value) }
}
}
impl<T> Drop for Rc<T> {
fn drop(&mut self) {
let mut e = self.memory.get(self.key).unwrap();
if e.refs == 1 {
e.remove();
return;
}
e.refs -= 1;
}
}
pub type ArcMemory<T> = SyncMemory<RcEntry<T>>;
pub struct Arc<T> {
memory: std::sync::Arc<ArcMemory<T>>,
key: usize,
}
impl<T> Arc<T> {
#[allow(clippy::result_unit_err)]
pub fn new(v: T, memory: &std::sync::Arc<ArcMemory<T>>) -> Result<Self, ()> {
let key = memory.insert(RcEntry { value: v, refs: 1 })?;
Ok(Self {
memory: memory.clone(),
key,
})
}
#[allow(clippy::should_implement_trait)]
pub fn clone(rc: &Arc<T>) -> Self {
let mut e = rc.memory.get(rc.key).unwrap();
e.refs += 1;
Self {
memory: rc.memory.clone(),
key: rc.key,
}
}
pub fn get<'a>(&'a self) -> &'a T {
let e = self.memory.get(self.key).unwrap();
// get a reference to the inner value
let value = &e.value;
// entry addresses are guaranteed to be stable once created, and the
// entry managed by this Arc won't be dropped until this Arc drops,
// therefore it is safe to assume the entry managed by this Arc will
// live at least as long as this Arc, and we can extend the lifetime
// of the reference beyond the SyncEntryGuard
unsafe { mem::transmute::<&T, &'a T>(value) }
}
}
impl<T> Drop for Arc<T> {
fn drop(&mut self) {
let mut e = self.memory.get(self.key).unwrap();
if e.refs == 1 {
e.remove();
return;
}
e.refs -= 1;
}
}
// adapted from https://github.com/rust-lang/rfcs/pull/2802
pub fn recycle_vec<T, U>(mut v: Vec<T>) -> Vec<U> {
assert_eq!(core::mem::size_of::<T>(), core::mem::size_of::<U>());
assert_eq!(core::mem::align_of::<T>(), core::mem::align_of::<U>());
v.clear();
let ptr = v.as_mut_ptr();
let capacity = v.capacity();
mem::forget(v);
let ptr = ptr as *mut U;
unsafe { Vec::from_raw_parts(ptr, 0, capacity) }
}
// ReusableVec inspired by recycle_vec
pub struct ReusableVecHandle<'a, T> {
vec: &'a mut Vec<T>,
}
impl<T> ReusableVecHandle<'_, T> {
pub fn get_ref(&self) -> &Vec<T> {
self.vec
}
pub fn get_mut(&mut self) -> &mut Vec<T> {
self.vec
}
}
impl<T> Drop for ReusableVecHandle<'_, T> {
fn drop(&mut self) {
self.vec.clear();
}
}
impl<T> Deref for ReusableVecHandle<'_, T> {
type Target = Vec<T>;
fn deref(&self) -> &Self::Target {
self.get_ref()
}
}
impl<T> DerefMut for ReusableVecHandle<'_, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.get_mut()
}
}
pub struct ReusableVec {
vec: Vec<()>,
size: usize,
align: usize,
}
impl ReusableVec {
pub fn new<T>(capacity: usize) -> Self {
let size = mem::size_of::<T>();
let align = mem::align_of::<T>();
let vec: Vec<T> = Vec::with_capacity(capacity);
// safety: we must cast to Vec<U> before using, where U has the same
// size and alignment as T
let vec: Vec<()> = unsafe { mem::transmute(vec) };
Self { vec, size, align }
}
pub fn get_as_new<U>(&mut self) -> ReusableVecHandle<'_, U> {
let size = mem::size_of::<U>();
let align = mem::align_of::<U>();
// if these don't match, panic. it's up the user to ensure the type
// is acceptable
assert_eq!(self.size, size);
assert_eq!(self.align, align);
let vec: &mut Vec<()> = &mut self.vec;
// safety: U has the expected size and alignment
let vec: &mut Vec<U> = unsafe { mem::transmute(vec) };
// the vec starts empty, and is always cleared when the handle drops.
// get_as_new() borrows self mutably, so it's not possible to create
// a handle when one already exists
assert!(vec.is_empty());
ReusableVecHandle { vec }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_reusable() {
let reusable = std::sync::Arc::new(Reusable::new(2, || vec![0; 128]));
assert_eq!(reusable.len(), 0);
let mut buf1 = reusable.reserve().unwrap();
assert_eq!(reusable.len(), 1);
let mut buf2 = reusable.reserve().unwrap();
assert_eq!(reusable.len(), 2);
// no room
assert!(reusable.reserve().is_err());
buf1[..5].copy_from_slice(b"hello");
buf2[..5].copy_from_slice(b"world");
assert_eq!(&buf1[..5], b"hello");
assert_eq!(&buf2[..5], b"world");
mem::drop(buf1);
assert_eq!(reusable.len(), 1);
mem::drop(buf2);
assert_eq!(reusable.len(), 0);
}
#[test]
fn test_rc() {
let memory = std::rc::Rc::new(RcMemory::new(2));
assert_eq!(memory.len(), 0);
let e0a = Rc::new(123 as i32, &memory).unwrap();
assert_eq!(memory.len(), 1);
let p = memory.entry0_ptr();
let e0b = Rc::clone(&e0a);
assert_eq!(memory.len(), 1);
assert_eq!(memory.entry0_ptr(), p);
let e1a = Rc::new(456 as i32, &memory).unwrap();
assert_eq!(memory.len(), 2);
assert_eq!(memory.entry0_ptr(), p);
// no room
assert!(Rc::new(789 as i32, &memory).is_err());
assert_eq!(*e0a.get(), 123);
assert_eq!(*e0b.get(), 123);
assert_eq!(*e1a.get(), 456);
mem::drop(e0b);
assert_eq!(memory.len(), 2);
assert_eq!(memory.entry0_ptr(), p);
mem::drop(e0a);
assert_eq!(memory.len(), 1);
mem::drop(e1a);
assert_eq!(memory.len(), 0);
}
#[test]
fn test_arc() {
let memory = std::sync::Arc::new(ArcMemory::new(2));
assert_eq!(memory.len(), 0);
let e0a = Arc::new(123 as i32, &memory).unwrap();
assert_eq!(memory.len(), 1);
let p = memory.entry0_ptr();
let e0b = Arc::clone(&e0a);
assert_eq!(memory.len(), 1);
assert_eq!(memory.entry0_ptr(), p);
let e1a = Arc::new(456 as i32, &memory).unwrap();
assert_eq!(memory.len(), 2);
assert_eq!(memory.entry0_ptr(), p);
// no room
assert!(Arc::new(789 as i32, &memory).is_err());
assert_eq!(*e0a.get(), 123);
assert_eq!(*e0b.get(), 123);
assert_eq!(*e1a.get(), 456);
mem::drop(e0b);
assert_eq!(memory.len(), 2);
assert_eq!(memory.entry0_ptr(), p);
mem::drop(e0a);
assert_eq!(memory.len(), 1);
mem::drop(e1a);
assert_eq!(memory.len(), 0);
}
#[test]
fn test_reusable_vec() {
let mut vec_mem = ReusableVec::new::<u32>(100);
let mut vec = vec_mem.get_as_new::<u32>();
assert_eq!(vec.capacity(), 100);
assert_eq!(vec.len(), 0);
vec.push(1);
assert_eq!(vec.len(), 1);
mem::drop(vec);
let vec = vec_mem.get_as_new::<u32>();
assert_eq!(vec.capacity(), 100);
assert_eq!(vec.len(), 0);
}
}
|