intaglio/bytes.rs
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
//! Intern arbitrary bytes.
//!
//! This module provides a nearly identical API to the one found in the
//! top-level of this crate. There is one important difference:
//!
//! 1. Interned contents are `&[u8]` instead of `&str`. Additionally, `Vec<u8>`
//! is used where `String` would have been used.
//!
//! # Example: intern byte string
//!
//! ```
//! # use intaglio::bytes::SymbolTable;
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let mut table = SymbolTable::new();
//! let sym = table.intern(&b"abc"[..])?;
//! assert_eq!(sym, table.intern(b"abc".to_vec())?);
//! assert_eq!(Some(&b"abc"[..]), table.get(sym));
//! # Ok(())
//! # }
//! # example().unwrap();
//! ```
//!
//! # Example: symbol iterators
//!
//! ```
//! # use std::collections::HashMap;
//! # use intaglio::bytes::SymbolTable;
//! # use intaglio::Symbol;
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let mut table = SymbolTable::new();
//! let sym = table.intern(&b"abc"[..])?;
//! // Retrieve set of `Symbol`s.
//! let all_symbols = table.all_symbols();
//! assert_eq!(vec![sym], all_symbols.collect::<Vec<_>>());
//!
//! table.intern(&b"xyz"[..])?;
//! let mut map = HashMap::new();
//! map.insert(Symbol::new(0), &b"abc"[..]);
//! map.insert(Symbol::new(1), &b"xyz"[..]);
//! // Retrieve symbol to byte content mappings.
//! let iter = table.iter();
//! assert_eq!(map, iter.collect::<HashMap<_, _>>());
//! # Ok(())
//! # }
//! # example().unwrap();
//! ```
//!
//! # Performance
//!
//! In general, one should expect this crate's performance on `&[u8]` to be
//! roughly similar to performance on `&str`.
use core::hash::BuildHasher;
use core::iter::{FromIterator, FusedIterator, Zip};
use core::marker::PhantomData;
use core::mem::ManuallyDrop;
use core::ops::Range;
use core::slice;
use std::borrow::Cow;
use std::collections::hash_map::{HashMap, RandomState};
use crate::internal::Interned;
use crate::{Symbol, SymbolOverflowError, DEFAULT_SYMBOL_TABLE_CAPACITY};
/// An iterator over all [`Symbol`]s in a [`SymbolTable`].
///
/// See the [`all_symbols`](SymbolTable::all_symbols) method in [`SymbolTable`].
///
/// # Usage
///
/// ```
/// # use intaglio::bytes::SymbolTable;
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let mut table = SymbolTable::new();
/// let sym = table.intern(&b"abc"[..])?;
/// let all_symbols = table.all_symbols();
/// assert_eq!(vec![sym], all_symbols.collect::<Vec<_>>());
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
#[cfg_attr(docsrs, doc(cfg(feature = "bytes")))]
pub struct AllSymbols<'a> {
range: Range<usize>,
// Hold a shared reference to the underlying `SymbolTable` to ensure the
// table is not modified while we are iterating which would make the results
// not match the real state.
phantom: PhantomData<&'a SymbolTable>,
}
impl<'a> Iterator for AllSymbols<'a> {
type Item = Symbol;
fn next(&mut self) -> Option<Self::Item> {
let next = self.range.next()?;
debug_assert!(u32::try_from(next).is_ok());
Some((next as u32).into())
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.range.size_hint()
}
fn count(self) -> usize {
self.range.count()
}
fn last(self) -> Option<Self::Item> {
let last = self.range.last()?;
debug_assert!(u32::try_from(last).is_ok());
Some((last as u32).into())
}
fn nth(&mut self, n: usize) -> Option<Self::Item> {
let nth = self.range.nth(n)?;
debug_assert!(u32::try_from(nth).is_ok());
Some((nth as u32).into())
}
fn collect<B: FromIterator<Self::Item>>(self) -> B {
self.range.map(|sym| Symbol::from(sym as u32)).collect()
}
}
impl<'a> DoubleEndedIterator for AllSymbols<'a> {
fn next_back(&mut self) -> Option<Self::Item> {
let next = self.range.next_back()?;
debug_assert!(u32::try_from(next).is_ok());
Some((next as u32).into())
}
fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
let nth = self.range.nth_back(n)?;
debug_assert!(u32::try_from(nth).is_ok());
Some((nth as u32).into())
}
}
impl<'a> FusedIterator for AllSymbols<'a> {}
/// An iterator over all interned byte strings in a [`SymbolTable`].
///
/// See the [`bytestrings`](SymbolTable::bytestrings) method in [`SymbolTable`].
///
/// # Usage
///
/// ```
/// # use intaglio::bytes::SymbolTable;
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let mut table = SymbolTable::new();
/// let sym = table.intern(b"abc".to_vec())?;
/// let bytestrings = table.bytestrings();
/// assert_eq!(vec![&b"abc"[..]], bytestrings.collect::<Vec<_>>());
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
#[derive(Debug, Clone)]
#[cfg_attr(docsrs, doc(cfg(feature = "bytes")))]
pub struct Bytestrings<'a>(slice::Iter<'a, Interned<[u8]>>);
impl<'a> Iterator for Bytestrings<'a> {
type Item = &'a [u8];
fn next(&mut self) -> Option<Self::Item> {
self.0.next().map(Interned::as_slice)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
fn count(self) -> usize {
self.0.count()
}
fn last(self) -> Option<Self::Item> {
self.0.last().map(Interned::as_slice)
}
fn nth(&mut self, n: usize) -> Option<Self::Item> {
self.0.nth(n).map(Interned::as_slice)
}
fn collect<B: FromIterator<Self::Item>>(self) -> B {
self.0.map(Interned::as_slice).collect()
}
}
impl<'a> DoubleEndedIterator for Bytestrings<'a> {
fn next_back(&mut self) -> Option<Self::Item> {
self.0.next_back().map(Interned::as_slice)
}
fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
self.0.nth_back(n).map(Interned::as_slice)
}
fn rfold<B, F>(self, accum: B, f: F) -> B
where
F: FnMut(B, Self::Item) -> B,
{
self.0.map(Interned::as_slice).rfold(accum, f)
}
}
impl<'a> ExactSizeIterator for Bytestrings<'a> {
fn len(&self) -> usize {
self.0.len()
}
}
impl<'a> FusedIterator for Bytestrings<'a> {}
/// An iterator over all symbols and interned byte strings in a [`SymbolTable`].
///
/// See the [`iter`](SymbolTable::iter) method in [`SymbolTable`].
///
/// # Usage
///
/// ```
/// # use std::collections::HashMap;
/// # use intaglio::bytes::SymbolTable;
/// # use intaglio::Symbol;
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let mut table = SymbolTable::new();
/// let sym = table.intern(b"abc".to_vec())?;
/// let iter = table.iter();
/// let mut map = HashMap::new();
/// map.insert(Symbol::new(0), &b"abc"[..]);
/// assert_eq!(map, iter.collect::<HashMap<_, _>>());
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
#[derive(Debug, Clone)]
#[cfg_attr(docsrs, doc(cfg(feature = "bytes")))]
pub struct Iter<'a>(Zip<AllSymbols<'a>, Bytestrings<'a>>);
impl<'a> Iterator for Iter<'a> {
type Item = (Symbol, &'a [u8]);
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
fn count(self) -> usize {
self.0.count()
}
fn last(self) -> Option<Self::Item> {
self.0.last()
}
fn nth(&mut self, n: usize) -> Option<Self::Item> {
self.0.nth(n)
}
fn collect<B: FromIterator<Self::Item>>(self) -> B {
self.0.collect()
}
}
impl<'a> FusedIterator for Iter<'a> {}
impl<'a> IntoIterator for &'a SymbolTable {
type Item = (Symbol, &'a [u8]);
type IntoIter = Iter<'a>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
/// Byte string interner.
///
/// This symbol table is implemented by storing byte strings with a fast path for
/// `&[u8]` that are already `'static`.
///
/// See module documentation for more.
///
/// # Usage
///
/// ```
/// # use intaglio::bytes::SymbolTable;
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let mut table = SymbolTable::new();
/// let sym = table.intern(&b"abc"[..])?;
/// assert_eq!(sym, table.intern(b"abc".to_vec())?);
/// assert!(table.contains(sym));
/// assert!(table.is_interned(b"abc"));
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
#[derive(Default, Debug)]
#[cfg_attr(docsrs, doc(cfg(feature = "bytes")))]
pub struct SymbolTable<S = RandomState> {
map: ManuallyDrop<HashMap<&'static [u8], Symbol, S>>,
vec: ManuallyDrop<Vec<Interned<[u8]>>>,
}
impl<S> Drop for SymbolTable<S> {
fn drop(&mut self) {
// SAFETY: No mutable references to `SymbolTable` internal fields are
// given out, which means `ManuallyDrop::drop` can only be invoked in
// this `Drop::drop` impl. Interal fields are guaranteed to be
// initialized by `SymbolTable` constructors.
unsafe {
// `Interned` requires that the `'static` references it gives out
// are dropped before the owning buffer stored in the `Interned`.
ManuallyDrop::drop(&mut self.map);
ManuallyDrop::drop(&mut self.vec);
}
}
}
impl SymbolTable<RandomState> {
/// Constructs a new, empty `SymbolTable` with [default capacity].
///
/// This function will always allocate. To construct a symbol table without
/// allocating, call [`SymbolTable::with_capacity(0)`].
///
/// # Examples
///
/// ```
/// # use intaglio::bytes::SymbolTable;
/// let table = SymbolTable::new();
/// assert_eq!(0, table.len());
/// assert!(table.capacity() >= 4096);
/// ```
///
/// [default capacity]: DEFAULT_SYMBOL_TABLE_CAPACITY
/// [`SymbolTable::with_capacity(0)`]: Self::with_capacity
#[must_use]
pub fn new() -> Self {
Self::with_capacity(DEFAULT_SYMBOL_TABLE_CAPACITY)
}
/// Constructs a new, empty `SymbolTable` with the specified capacity.
///
/// The symbol table will be able to hold at least `capacity` byte strings
/// without reallocating. If `capacity` is 0, the symbol table will not
/// allocate.
///
/// # Examples
///
/// ```
/// # use intaglio::bytes::SymbolTable;
/// let table = SymbolTable::with_capacity(10);
/// assert_eq!(0, table.len());
/// assert!(table.capacity() >= 10);
/// ```
#[must_use]
pub fn with_capacity(capacity: usize) -> Self {
let capacity = capacity.next_power_of_two();
Self {
map: ManuallyDrop::new(HashMap::with_capacity(capacity)),
vec: ManuallyDrop::new(Vec::with_capacity(capacity)),
}
}
}
impl<S> SymbolTable<S> {
/// Constructs a new, empty `SymbolTable` with
/// [default capacity](DEFAULT_SYMBOL_TABLE_CAPACITY) and the given hash
/// builder.
///
/// # Examples
///
/// ```
/// # use std::collections::hash_map::RandomState;
/// # use intaglio::bytes::SymbolTable;
/// let hash_builder = RandomState::new();
/// let table = SymbolTable::with_hasher(hash_builder);
/// assert_eq!(0, table.len());
/// assert!(table.capacity() >= 4096);
/// ```
pub fn with_hasher(hash_builder: S) -> Self {
Self::with_capacity_and_hasher(DEFAULT_SYMBOL_TABLE_CAPACITY, hash_builder)
}
/// Constructs a new, empty `SymbolTable` with the specified capacity and
/// the given hash builder.
///
/// # Examples
///
/// ```
/// # use std::collections::hash_map::RandomState;
/// # use intaglio::bytes::SymbolTable;
/// let hash_builder = RandomState::new();
/// let table = SymbolTable::with_capacity_and_hasher(10, hash_builder);
/// assert_eq!(0, table.len());
/// assert!(table.capacity() >= 10);
/// ```
pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self {
Self {
map: ManuallyDrop::new(HashMap::with_capacity_and_hasher(capacity, hash_builder)),
vec: ManuallyDrop::new(Vec::with_capacity(capacity)),
}
}
/// Returns the number of byte strings the table can hold without
/// reallocating.
///
/// # Examples
///
/// ```
/// # use intaglio::bytes::SymbolTable;
/// let table = SymbolTable::with_capacity(10);
/// assert!(table.capacity() >= 10);
/// ```
pub fn capacity(&self) -> usize {
usize::min(self.vec.capacity(), self.map.capacity())
}
/// Returns the number of interned byte strings in the table.
///
/// # Examples
///
/// ```
/// # use intaglio::bytes::SymbolTable;
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let mut table = SymbolTable::new();
/// assert_eq!(0, table.len());
///
/// table.intern(b"abc".to_vec())?;
/// // only uniquely interned byte strings grow the symbol table.
/// table.intern(b"abc".to_vec())?;
/// table.intern(b"xyz".to_vec())?;
/// assert_eq!(2, table.len());
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
pub fn len(&self) -> usize {
self.vec.len()
}
/// Returns `true` if the symbol table contains no interned byte strings.
///
/// # Examples
///
/// ```
/// # use intaglio::bytes::SymbolTable;
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let mut table = SymbolTable::new();
/// assert!(table.is_empty());
///
/// table.intern(b"abc".to_vec())?;
/// assert!(!table.is_empty());
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
pub fn is_empty(&self) -> bool {
self.vec.is_empty()
}
/// Returns `true` if the symbol table contains the given symbol.
///
/// # Examples
///
/// ```
/// # use intaglio::bytes::SymbolTable;
/// # use intaglio::Symbol;
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let mut table = SymbolTable::new();
/// assert!(!table.contains(Symbol::new(0)));
///
/// let sym = table.intern(b"abc".to_vec())?;
/// assert!(table.contains(Symbol::new(0)));
/// assert!(table.contains(sym));
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
#[must_use]
pub fn contains(&self, id: Symbol) -> bool {
self.get(id).is_some()
}
/// Returns a reference to the byte string associated with the given symbol.
///
/// If the given symbol does not exist in the underlying symbol table,
/// `None` is returned.
///
/// The lifetime of the returned reference is bound to the symbol table.
///
/// # Examples
///
/// ```
/// # use intaglio::bytes::SymbolTable;
/// # use intaglio::Symbol;
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let mut table = SymbolTable::new();
/// assert!(table.get(Symbol::new(0)).is_none());
///
/// let sym = table.intern(b"abc".to_vec())?;
/// assert_eq!(Some(&b"abc"[..]), table.get(Symbol::new(0)));
/// assert_eq!(Some(&b"abc"[..]), table.get(sym));
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
#[must_use]
pub fn get(&self, id: Symbol) -> Option<&[u8]> {
let bytes = self.vec.get(usize::from(id))?;
Some(bytes.as_slice())
}
/// Returns an iterator over all [`Symbol`]s and byte strings in the
/// [`SymbolTable`].
///
/// # Examples
///
/// ```
/// # use std::collections::HashMap;
/// # use intaglio::bytes::SymbolTable;
/// # use intaglio::Symbol;
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let mut table = SymbolTable::new();
/// table.intern(b"abc".to_vec())?;
/// table.intern(b"xyz".to_vec())?;
/// table.intern(b"123".to_vec())?;
/// table.intern(b"789".to_vec())?;
///
/// let iter = table.iter();
/// let mut map = HashMap::new();
/// map.insert(Symbol::new(0), &b"abc"[..]);
/// map.insert(Symbol::new(1), &b"xyz"[..]);
/// map.insert(Symbol::new(2), &b"123"[..]);
/// map.insert(Symbol::new(3), &b"789"[..]);
/// assert_eq!(map, iter.collect::<HashMap<_, _>>());
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
///
/// ```
/// # use intaglio::bytes::SymbolTable;
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let mut table = SymbolTable::new();
/// table.intern(b"abc".to_vec())?;
/// table.intern(b"xyz".to_vec())?;
/// table.intern(b"123".to_vec())?;
/// table.intern(b"789".to_vec())?;
///
/// let iter = table.iter();
/// assert_eq!(table.len(), iter.count());
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
pub fn iter(&self) -> Iter<'_> {
Iter(self.all_symbols().zip(self.bytestrings()))
}
/// Returns an iterator over all [`Symbol`]s in the [`SymbolTable`].
///
/// # Examples
///
/// ```
/// # use intaglio::bytes::SymbolTable;
/// # use intaglio::Symbol;
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let mut table = SymbolTable::new();
/// table.intern(b"abc".to_vec())?;
/// table.intern(b"xyz".to_vec())?;
/// table.intern(b"123".to_vec())?;
/// table.intern(b"789".to_vec())?;
///
/// let mut all_symbols = table.all_symbols();
/// assert_eq!(Some(Symbol::new(0)), all_symbols.next());
/// assert_eq!(Some(Symbol::new(1)), all_symbols.nth_back(2));
/// assert_eq!(None, all_symbols.next());
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
///
/// ```
/// # use intaglio::bytes::SymbolTable;
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let mut table = SymbolTable::new();
/// table.intern(b"abc".to_vec())?;
/// table.intern(b"xyz".to_vec())?;
/// table.intern(b"123".to_vec())?;
/// table.intern(b"789".to_vec())?;
///
/// let all_symbols = table.all_symbols();
/// assert_eq!(table.len(), all_symbols.count());
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
pub fn all_symbols(&self) -> AllSymbols<'_> {
AllSymbols {
range: 0..self.len(),
phantom: PhantomData,
}
}
/// Returns an iterator over all byte strings in the [`SymbolTable`].
///
/// # Examples
///
/// ```
/// # use intaglio::bytes::SymbolTable;
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let mut table = SymbolTable::new();
/// table.intern(b"abc".to_vec())?;
/// table.intern(b"xyz".to_vec())?;
/// table.intern(b"123".to_vec())?;
/// table.intern(b"789".to_vec())?;
///
/// let mut bytestrings = table.bytestrings();
/// assert_eq!(Some(&b"abc"[..]), bytestrings.next());
/// assert_eq!(Some(&b"xyz"[..]), bytestrings.nth_back(2));
/// assert_eq!(None, bytestrings.next());
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
///
/// ```
/// # use intaglio::bytes::SymbolTable;
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let mut table = SymbolTable::new();
/// table.intern(b"abc".to_vec())?;
/// table.intern(b"xyz".to_vec())?;
/// table.intern(b"123".to_vec())?;
/// table.intern(b"789".to_vec())?;
///
/// let bytestrings = table.bytestrings();
/// assert_eq!(table.len(), bytestrings.count());
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
pub fn bytestrings(&self) -> Bytestrings<'_> {
Bytestrings(self.vec.iter())
}
}
impl<S> SymbolTable<S>
where
S: BuildHasher,
{
/// Intern a byte string for the lifetime of the symbol table.
///
/// The returned `Symbol` allows retrieving of the underlying bytes.
/// Equal byte strings will be inserted into the symbol table exactly once.
///
/// This function only allocates if the underlying symbol table has no
/// remaining capacity.
///
/// # Errors
///
/// If the symbol table would grow larger than `u32::MAX` interned
/// byte strings, the [`Symbol`] counter would overflow and a
/// [`SymbolOverflowError`] is returned.
///
/// # Examples
///
/// ```
/// # use intaglio::bytes::SymbolTable;
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let mut table = SymbolTable::new();
/// let sym = table.intern(b"abc".to_vec())?;
/// table.intern(b"xyz".to_vec())?;
/// table.intern(&b"123"[..])?;
/// table.intern(&b"789"[..])?;
///
/// assert_eq!(4, table.len());
/// assert_eq!(Some(&b"abc"[..]), table.get(sym));
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
pub fn intern<T>(&mut self, contents: T) -> Result<Symbol, SymbolOverflowError>
where
T: Into<Cow<'static, [u8]>>,
{
let contents = contents.into();
if let Some(&id) = self.map.get(&*contents) {
return Ok(id);
}
// The `Interned::Owned` variant is derived from a `Box<T>`. When such
// a structure is moved or assigned, as it is below in the call to
// `self.vec.push`, the allocation is "retagged" in Miri/stacked borrows.
//
// Retagging an allocation pops all of the borrows derived from it off
// of the stack. This means we need to move the `Interned` into the
// `Vec` before calling `Interned::as_static_slice` to ensure the
// reference does not get invalidated by retagging.
//
// However, that alone may be insufficient as the `Interened` may be
// moved when the symbol table grows.
//
// The `SymbolTable` API prevents shared references to the `Interned`
// being invalidated by a retag by tying resolved symbol contents,
// `&'a T`, to `&'a SymbolTable`, which means the `SymbolTable` cannot
// grow, shrink, or otherwise reallocate/move contents while a reference
// to the `Interned`'s inner `T` is alive.
//
// To protect against future updates to stacked borrows or the unsafe
// code operational semantics, we can address this additional invariant
// with updated `Interned` internals which store the `Box<T>` in a raw
// pointer form, which allows moves to be treated as untyped copies.
//
// See:
//
// - <https://github.com/artichoke/intaglio/issues/235>
// - <https://github.com/artichoke/intaglio/pull/236>
let name = Interned::from(contents);
let id = Symbol::try_from(self.map.len())?;
// Move the `Interned` into the `Vec`, causing it to be retagged under
// stacked borrows, before taking any references to its inner `T`.
self.vec.push(name);
// Ensure we grow the map before we take any shared references to the
// inner `T`.
self.map.reserve(1);
// SAFETY: `self.vec` is non-empty because the preceding line of code
// pushed an entry into it.
let name = unsafe { self.vec.last().unwrap_unchecked() };
// SAFETY: This expression creates a reference with a `'static` lifetime
// from an owned and interned buffer, which is permissible because:
//
// - `Interned` is an internal implementation detail of `SymbolTable`.
// - `SymbolTable` never gives out `'static` references to underlying
// contents.
// - All slice references given out by the `SymbolTable` have the same
// lifetime as the `SymbolTable`.
// - The `map` field of `SymbolTable`, which contains the `'static`
// references, is dropped before the owned buffers stored in this
// `Interned`.
// - The shared reference may be derived from a `PinBox` which prevents
// moves from retagging the underlying boxed `T` under stacked borrows.
// - The symbol table cannot grow, shrink, or otherwise move its contents
// while this reference is alive.
let slice = unsafe { name.as_static_slice() };
self.map.insert(slice, id);
debug_assert_eq!(self.get(id), Some(slice));
debug_assert_eq!(self.intern(slice), Ok(id));
Ok(id)
}
/// Returns the `Symbol` identifier for `contents` if it has been interned
/// before, `None` otherwise.
///
/// This method does not modify the symbol table.
///
/// # Examples
///
/// ```
/// # use intaglio::bytes::SymbolTable;
/// # use intaglio::Symbol;
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let mut table = SymbolTable::new();
/// assert!(!table.is_interned(b"abc"));
/// assert_eq!(None, table.check_interned(b"abc"));
///
/// table.intern(b"abc".to_vec())?;
/// assert!(table.is_interned(b"abc"));
/// assert_eq!(Some(Symbol::new(0)), table.check_interned(b"abc"));
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
#[must_use]
pub fn check_interned(&self, contents: &[u8]) -> Option<Symbol> {
self.map.get(contents).copied()
}
/// Returns `true` if the given byte string has been interned before.
///
/// This method does not modify the symbol table.
///
/// # Examples
///
/// ```
/// # use intaglio::bytes::SymbolTable;
/// # use intaglio::Symbol;
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let mut table = SymbolTable::new();
/// assert!(!table.is_interned(b"abc"));
/// assert_eq!(None, table.check_interned(b"abc"));
///
/// table.intern(b"abc".to_vec())?;
/// assert!(table.is_interned(b"abc"));
/// assert_eq!(Some(Symbol::new(0)), table.check_interned(b"abc"));
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
#[must_use]
pub fn is_interned(&self, contents: &[u8]) -> bool {
self.map.contains_key(contents)
}
/// Reserves capacity for at least additional more elements to be inserted
/// in the given `SymbolTable`. The collection may reserve more space to
/// avoid frequent reallocations. After calling reserve, capacity will be
/// greater than or equal to `self.len() + additional`. Does nothing if
/// capacity is already sufficient.
///
/// # Panics
///
/// Panics if the new capacity overflows `usize`.
///
/// # Examples
///
/// ```
/// # use intaglio::bytes::SymbolTable;
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let mut table = SymbolTable::with_capacity(1);
/// table.intern(b"abc".to_vec())?;
/// table.reserve(10);
/// assert!(table.capacity() >= 11);
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
pub fn reserve(&mut self, additional: usize) {
self.map.reserve(additional);
self.vec.reserve(additional);
}
/// Shrinks the capacity of the symbol table as much as possible.
///
/// It will drop down as close as possible to the length but the allocator
/// may still inform the symbol table that there is space for a few more
/// elements.
///
/// # Examples
///
/// ```
/// # use intaglio::bytes::SymbolTable;
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let mut table = SymbolTable::with_capacity(10);
/// table.intern(b"abc".to_vec());
/// table.intern(b"xyz".to_vec());
/// table.intern(b"123".to_vec());
/// table.shrink_to_fit();
/// assert!(table.capacity() >= 3);
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
pub fn shrink_to_fit(&mut self) {
self.map.shrink_to_fit();
self.vec.shrink_to_fit();
}
/// Shrinks the capacity of the symbol table with a lower bound.
///
/// The capacity will remain at least as large as both the length and the
/// supplied value.
///
/// If the current capacity is less than the lower limit, this is a no-op.
///
/// # Examples
///
/// ```
/// # use intaglio::bytes::SymbolTable;
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let mut table = SymbolTable::with_capacity(10);
/// table.intern(b"abc".to_vec())?;
/// table.intern(b"xyz".to_vec())?;
/// table.intern(b"123".to_vec())?;
/// table.shrink_to(5);
/// assert!(table.capacity() >= 5);
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
pub fn shrink_to(&mut self, min_capacity: usize) {
self.map.shrink_to(min_capacity);
self.vec.shrink_to(min_capacity);
}
}
#[cfg(test)]
#[allow(clippy::needless_pass_by_value)]
mod tests {
use quickcheck_macros::quickcheck;
use super::SymbolTable;
#[test]
fn alloc_drop_new() {
let table = SymbolTable::new();
drop(table);
}
#[test]
fn alloc_drop_with_capacity() {
let table = SymbolTable::with_capacity(1 << 14);
drop(table);
}
#[test]
fn drop_with_true_static_data() {
let mut table = SymbolTable::new();
table.intern(&b"1"[..]).unwrap();
table.intern(&b"2"[..]).unwrap();
table.intern(&b"3"[..]).unwrap();
table.intern(&b"4"[..]).unwrap();
table.intern(&b"5"[..]).unwrap();
drop(table);
}
#[test]
fn drop_with_owned_data() {
let mut table = SymbolTable::new();
table.intern(b"1".to_vec()).unwrap();
table.intern(b"2".to_vec()).unwrap();
table.intern(b"3".to_vec()).unwrap();
table.intern(b"4".to_vec()).unwrap();
table.intern(b"5".to_vec()).unwrap();
drop(table);
}
#[test]
fn set_owned_value_and_get_with_owned_and_borrowed() {
let mut table = SymbolTable::new();
// intern an owned value
let sym = table.intern(b"abc".to_vec()).unwrap();
// retrieve bytes
assert_eq!(&b"abc"[..], table.get(sym).unwrap());
// intern owned value again
assert_eq!(sym, table.intern(b"abc".to_vec()).unwrap());
// intern borrowed value
assert_eq!(sym, table.intern(&b"abc"[..]).unwrap());
}
#[test]
fn set_borrowed_value_and_get_with_owned_and_borrowed() {
let mut table = SymbolTable::new();
// intern a borrowed value
let sym = table.intern(&b"abc"[..]).unwrap();
// retrieve bytes
assert_eq!(&b"abc"[..], table.get(sym).unwrap());
// intern owned value
assert_eq!(sym, table.intern(b"abc".to_vec()).unwrap());
// intern borrowed value again
assert_eq!(sym, table.intern(&b"abc"[..]).unwrap());
}
#[quickcheck]
fn intern_twice_symbol_equality(bytes: Vec<u8>) -> bool {
let mut table = SymbolTable::new();
let sym = table.intern(bytes.clone()).unwrap();
let sym_again = table.intern(bytes).unwrap();
sym == sym_again
}
#[quickcheck]
fn intern_get_roundtrip(bytes: Vec<u8>) -> bool {
let mut table = SymbolTable::new();
let sym = table.intern(bytes.clone()).unwrap();
let retrieved_bytes = table.get(sym).unwrap();
bytes == retrieved_bytes
}
#[quickcheck]
fn table_contains_sym(bytes: Vec<u8>) -> bool {
let mut table = SymbolTable::new();
let sym = table.intern(bytes).unwrap();
table.contains(sym)
}
#[quickcheck]
fn table_does_not_contain_missing_symbol_ids(sym: u32) -> bool {
let table = SymbolTable::new();
!table.contains(sym.into())
}
#[quickcheck]
fn empty_table_does_not_report_any_interned_byte_strings(bytes: Vec<u8>) -> bool {
let table = SymbolTable::new();
!table.is_interned(bytes.as_slice())
}
#[quickcheck]
fn table_reports_interned_byte_strings_as_interned(bytes: Vec<u8>) -> bool {
let mut table = SymbolTable::new();
table.intern(bytes.clone()).unwrap();
table.is_interned(bytes.as_slice())
}
}