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
#![doc = include_str!("../README.md")]
use std::any::{Any, TypeId};
use std::fmt::{self, Debug, Formatter};
use std::mem;
/// A dynamic vector that can store elements of any single type.
#[derive(Default)]
pub struct UniVec(Option<Box<dyn UniVecOps>>);
/// A macro to create a `UniVec` with elements.
/// This macro wraps the `vec!` macro creating an `UniVec` instead.
///
/// # Examples
///
/// ```
/// # use univec::univec;
/// let univec = univec![42, 10];
/// assert_eq!(univec.get::<i32>(0), Some(&42));
/// assert_eq!(univec.get::<i32>(1), Some(&10));
/// ```
#[macro_export]
macro_rules! univec {
() => ( $crate::UniVec::new() );
($elem:expr; $n:expr) => ( $crate::UniVec::from(vec![$elem; $n]) );
($($x:expr),+ $(,)?) => { $crate::UniVec::from(vec![$($x),+]) };
}
impl UniVec {
/// Creates a new empty `UniVec`. A new `UniVec` is empty and has no type associated to it,
/// the type becomes associated when adding the first data to it.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let univec = UniVec::new();
/// assert!(univec.is_empty());
/// ```
#[must_use]
pub const fn new() -> Self {
Self(None)
}
/// Creates a new empty `UniVec` with the specified capacity and type.
///
/// # Arguments
///
/// This function requires the 'turbofish' notation to associate a type to the `UniVec`.
///
/// * `capacity` - The capacity to reserve.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let univec = UniVec::with_capacity::<i32>(10);
/// assert!(univec.capacity() >= 10);
/// ```
#[must_use]
pub fn with_capacity<T: 'static>(capacity: usize) -> Self {
Self(Some(Box::new(Vec::<T>::with_capacity(capacity))))
}
/// Try to get a reference to an element of type `T` by index.
///
/// # Arguments
///
/// * `index` - The index of the element to retrieve.
///
/// # Returns
///
/// Returns `Ok(Some(&T))` if the element is found, `Ok(None)` when the index is out of
/// range.
///
/// # Errors
///
/// Returns `Err(TypeError)` when this `UniVec` does not store `T's`.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
/// univec.push(42_i32);
///
/// let element = univec.try_get::<i32>(0).unwrap();
///
/// assert_eq!(element, Some(&42));
/// ```
pub fn try_get<T: 'static>(&self, index: impl IntoIndex) -> Result<Option<&T>, TypeError> {
Ok(self
.try_as_vec::<T>()?
.and_then(|s| s.get(index.into_index())))
}
/// Get a reference to an element of type `T` by index. This resembles the the `Vec::get`
/// method.
///
/// # Arguments
///
/// * `index` - The index of the element to retrieve.
///
/// # Returns
///
/// Returns `Some(&T)` it is found and `None` when the index is out of range.
///
/// # Panics
///
/// Panics if this `UniVec` does not store `T's`.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
/// univec.push(42_i32);
///
/// let element = univec.get::<i32>(0).unwrap();
///
/// assert_eq!(element, &42);
/// ```
#[must_use]
pub fn get<T: 'static>(&self, index: impl IntoIndex) -> Option<&T> {
self.as_vec::<T>().get(index.into_index())
}
/// Try to get a mutable reference to an element of type `T` by index.
///
/// # Arguments
///
/// * `index` - The index of the element to retrieve.
///
/// # Returns
///
/// Returns `Ok(Some(&mut T))` if the element is found, Ok(None) when the index is out of
/// range.
///
/// # Errors
///
/// Returns `Err(TypeError)` when this `UniVec` does not store `T's`.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
/// univec.push(42_i32);
///
/// let mut element = univec.try_get_mut::<i32>(0).unwrap();
///
/// if let Some(elem) = element {
/// *elem += 10;
/// }
///
/// assert_eq!(univec.try_get::<i32>(0).unwrap(), Some(&52));
/// ```
pub fn try_get_mut<T: 'static>(
&mut self,
index: impl IntoIndex,
) -> Result<Option<&mut T>, TypeError> {
Ok(self
.try_as_vec_mut::<T>()?
.and_then(|s| s.get_mut(index.into_index())))
}
/// Get a mutable reference to an element of type `T` by index. Will associate `Self` with
/// a empty `Vec<T>` when the `UniVec` is not associated to a type.
///
/// # Arguments
///
/// * `index` - The index of the element to retrieve.
///
/// # Returns
///
/// Returns `Some(&mut T)` it is found and `None` when the index is out of range.
///
/// # Panics
///
/// Panics if this `UniVec` does not store `T's`.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
/// univec.push(42_i32);
///
/// let mut element = univec.get_mut::<i32>(0).unwrap();
///
/// *element += 10;
///
/// assert_eq!(univec.get::<i32>(0), Some(&52));
/// ```
#[must_use]
pub fn get_mut<T: 'static>(&mut self, index: impl IntoIndex) -> Option<&mut T> {
self.as_vec_mut::<T>().get_mut(index.into_index())
}
/// Ensures that the `UniVec` stores `T's`. Possibly associate the requested type and
/// reserving the specified capacity.
///
/// # Arguments
///
/// * `capacity` - The capacity to reserve.
///
/// # Returns
///
/// Returns `Ok(())` when the `UniVec` was empty or `T` was already is associated.
/// The requested capacity is reserved then.
///
/// # Errors
///
/// Returns `Err(TypeError)` when this `UniVec` does not store `T's`.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
///
/// univec.ensure::<i32>(10).unwrap();
/// assert!(univec.capacity() >= 10);
/// assert_eq!(univec.associated_type(), Some(std::any::TypeId::of::<i32>()));
/// ```
pub fn ensure<T: 'static>(&mut self, capacity: usize) -> Result<(), TypeError> {
if self.0.is_none() {
self.0 = Some(Box::new(Vec::<T>::with_capacity(capacity)));
} else if !self.type_check::<T>() {
return Err(TypeError);
}
self.reserve(capacity);
Ok(())
}
/// Pushes a value of type `T` onto a `UniVec`.
///
/// # Arguments
///
/// * `value` - A `T` to push onto self.
///
/// # Returns
///
/// Returns `Ok(())` when the value was successfully pushed.
///
/// # Errors
///
/// Returns `Err(TypeErrorValue(value))` when this `UniVec` can not store `T's`.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
/// univec.push(42_i32);
///
/// let mut element = univec.get_mut::<i32>(0);
///
/// if let Some(elem) = element {
/// *elem += 10;
/// }
///
/// assert_eq!(univec.get::<i32>(0), Some(&52));
/// ```
pub fn push<T: 'static>(&mut self, value: T) -> Result<(), TypeErrorValue<T>> {
if self.ensure::<T>(1).is_ok() {
self.as_vec_mut::<T>().push(value);
Ok(())
} else {
Err(TypeErrorValue(value))
}
}
/// Pops a dynamic typed value from a `UniVec`.
///
/// # Returns
///
/// Returns `Some(Box<dyn Any>)` if a value is successfully popped. `None` when the univec
/// was empty.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
/// univec.push(42_i32);
///
/// let popped = univec.pop_any().unwrap();
///
/// assert_eq!(*popped.downcast::<i32>().unwrap(), 42);
/// ```
#[must_use]
pub fn pop_any(&mut self) -> Option<Box<dyn Any>> {
self.0.as_mut().and_then(|vec| vec.pop_box())
}
/// Pops a value of type `T` from a `UniVec`.
///
/// # Returns
///
/// Returns `Ok(Some(T))` with the value is successfully popped.
/// Returns `Ok(None)` when the univec is empty.
///
/// # Errors
///
/// Returns `Err(TypeError)` when the univec does not store `T's`.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
/// univec.push(42_i32);
///
/// let popped = univec.pop().unwrap();
///
/// assert_eq!(popped, Some(42));
/// assert!(univec.is_empty());
/// ```
#[allow(clippy::missing_panics_doc)]
pub fn pop<T: 'static>(&mut self) -> Result<Option<T>, TypeError> {
Ok(self.try_as_vec_mut::<T>()?.and_then(Vec::pop))
}
/// Drops the last value from a `UniVec`. This is more efficient than the other `pop`
/// variants when the value is not required anymore.
///
/// # Returns
///
/// Returns `true` if a value is successfully dropped, otherwise returns `false`.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
/// univec.push(42_i32);
///
/// assert!(univec.drop_last());
/// assert!(univec.is_empty());
/// ```
pub fn drop_last(&mut self) -> bool {
self.0.as_mut().map_or(false, |vec| vec.drop_last())
}
/// Inserts a value of type `T` into the `UniVec` at the specified index.
///
/// # Arguments
///
/// * `index` - The index at which to insert the value.
/// * `value` - A reference to the value of type `T` to insert into the vector.
///
/// # Errors
///
/// Returns `Err(TypeErrorValue(value))` when this `UniVec` does not store `T's`.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
/// univec.push(42_i32);
///
/// univec.insert(0, 10_i32).unwrap();
///
/// assert_eq!(univec.get::<i32>(0), Some(&10));
/// assert_eq!(univec.get::<i32>(1), Some(&42));
/// ```
pub fn insert<T: 'static>(
&mut self,
index: impl IntoIndex,
value: T,
) -> Result<(), TypeErrorValue<T>> {
if self.ensure::<T>(1).is_ok() {
self.as_vec_mut::<T>().insert(index.into_index(), value);
Ok(())
} else {
Err(TypeErrorValue(value))
}
}
/// Removes a value of type `T` from an `UniVec` at the specified index.
///
/// # Arguments
///
/// * `index` - The index of the element to remove.
///
/// # Panics
///
/// Panics if index is out of bounds.
///
/// # Returns
///
/// Returns `Ok(T)` if a value is successfully removed.
///
/// # Errors
///
/// Returns `Err(TypeError)` when this `UniVec` does not store `T's`.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
/// univec.push(42_i32);
///
/// let removed = univec.remove::<i32>(0).unwrap();
///
/// assert_eq!(removed, 42);
/// ```
pub fn remove<T: 'static>(&mut self, index: impl IntoIndex) -> Result<T, TypeError> {
Ok(self
.try_as_vec_mut::<T>()?
.map(|v| v.remove(index.into_index()))
.expect("index out of bounds"))
}
/// Returns the length of a `UniVec`.
///
/// # Returns
///
/// Returns the length of the `UniVec`. A `UniVec` with no type associated is considered
/// empty with length 0.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
/// assert_eq!(univec.len(), 0);
///
/// univec.push(42_i32);
///
/// assert_eq!(univec.len(), 1);
/// ```
#[must_use]
pub fn len(&self) -> usize {
self.0.as_ref().map_or(0, |vec| vec.len())
}
/// Returns whether a `UniVec` is empty.
///
/// # Returns
///
/// Returns `true` when the `UniVec` is empty, otherwise returns `false`.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let univec = UniVec::new();
///
/// assert!(univec.is_empty());
/// ```
#[must_use]
#[inline]
pub fn is_empty(&self) -> bool {
self.0.as_ref().map_or(true, |vec| vec.len() == 0)
}
/// Returns the capacity of a `UniVec`.
///
/// # Returns
///
/// Returns the capacity of the `UniVec`. A `UniVec` with no type associated is considered
/// empty with capacity 0.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
/// assert_eq!(univec.capacity(), 0);
///
/// univec.push(42_i32);
///
/// assert!(univec.capacity() >= 1);
/// ```
#[must_use]
pub fn capacity(&self) -> usize {
self.0.as_ref().map_or(0, |vec| vec.capacity())
}
/// Reserves capacity for at least additional more elements to be inserted in the given
/// `UniVec`. The collection may reserve more space to avoid frequent reallocations. Note
/// that `reserve()` will not reserve elements on a `UniVec` that has no type associated,
/// use `UniVec::with_capacity()` to initialize a `Univec` or `UniVec::ensure()` to
/// associate a type while reserving some elements.
///
/// # Arguments
///
/// * `additional` - The number of additional elements to reserve space for.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
/// univec.push(42_i32);
///
/// univec.reserve(10);
/// assert!(univec.capacity() >= 11);
/// ```
pub fn reserve(&mut self, additional: usize) {
if let Some(v) = self.0.as_mut() {
v.reserve(additional);
};
}
/// Replaces the element at the specified index with a new value.
///
/// # Arguments
///
/// * `index` - The index of the element to replace.
/// * `value` - The new value to replace the element with.
///
/// # Panics
///
/// Panics if index is out of bounds.
///
/// # Returns
///
/// Returns `Ok(T)` with the old value if a value is successfully replaced.
///
/// # Errors
///
/// Returns `Err(TypeErrorValue(value))` when this `UniVec` does not store `T's`.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
/// univec.push(42_i32);
///
/// let removed = univec.replace(0, 10_i32).unwrap();
///
/// assert_eq!(removed, 42);
/// assert_eq!(univec.get::<i32>(0), Some(&10));
/// ```
pub fn replace<T: 'static>(
&mut self,
index: impl IntoIndex,
value: T,
) -> Result<T, TypeErrorValue<T>> {
if self.type_check::<T>() {
Ok(mem::replace(
self.get_mut::<T>(index.into_index())
.expect("index out of bounds"),
value,
))
} else {
Err(TypeErrorValue(value))
}
}
/// Tries to sets the last element of an `UniVec` to a new value. When the `UniVec` is
/// empty or not associated to a type, an initial value is pushed.
///
/// # Arguments
///
/// * `value` - the new value to replace the last element with.
///
/// # Returns
///
/// Returns `Ok(Some(T))` with the old last element or `Ok(None)` when the univec was
/// empty.
///
/// # Errors
///
/// Returns `Err(TypeErrorValue(value))` when this `UniVec` does not store `T's`.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
///
/// univec.try_set_last(10_i32).unwrap();
/// assert_eq!(univec.get::<i32>(0), Some(&10));
///
/// univec.try_set_last(20_i32).unwrap();
/// assert_eq!(univec.get::<i32>(0), Some(&20));
/// ```
pub fn try_set_last<T: 'static>(&mut self, value: T) -> Result<Option<T>, TypeErrorValue<T>> {
Ok(if self.is_empty() {
self.push(value)?;
None
} else {
Some(self.replace(self.len() - 1, value)?)
})
}
/// Sets the last element of an `UniVec` to a new value. When the `UniVec` is
/// empty or not associated to a type, an initial value is pushed.
///
/// # Arguments
///
/// * `value` - The new value to replace the last element with.
///
/// # Returns
///
/// Returns `Some(T)` with the old last element or `None` when the univec was empty.
///
/// # Panics
///
/// Panics if this `UniVec` does not store `T's`.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
///
/// univec.set_last(10_i32);
/// assert_eq!(univec.get::<i32>(0), Some(&10));
///
/// univec.set_last(20_i32);
/// assert_eq!(univec.get::<i32>(0), Some(&20));
/// ```
pub fn set_last<T: 'static>(&mut self, value: T) -> Option<T> {
self.try_set_last(value)
.unwrap_or_else(|_| panic!("This UniVec does not store the requested type"))
}
/// Checks whenever this `UniVec` is capable of storing `T`.
#[inline]
fn type_check<T: 'static>(&self) -> bool {
self.0
.as_ref()
.map_or(true, |vec| vec.inner_type_id() == TypeId::of::<T>())
}
/// Returns an `Option<TypeId>` the type is associated to a `UniVec`.
///
/// # Returns
///
/// Returns `Some(TypeId)` if a type is associated to this `UniVec`, otherwise returns `None`.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
///
/// assert_eq!(univec.associated_type(), None);
///
/// univec.push(42_i32);
///
/// assert_eq!(univec.associated_type(), Some(std::any::TypeId::of::<i32>()));
/// ```
#[must_use]
pub fn associated_type(&self) -> Option<TypeId> {
self.0.as_ref().map(|vec| vec.inner_type_id())
}
/// Returns the name of the type is associated to a `UniVec`.
///
/// # Returns
///
/// Returns `Some('static str)` if a type is associated to this `UniVec`, otherwise returns `None`.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
///
/// assert_eq!(univec.associated_type_name(), None);
///
/// univec.push(42_i32);
///
/// assert_eq!(univec.associated_type_name(), Some("i32"));
/// ```
#[must_use]
pub fn associated_type_name(&self) -> Option<&'static str> {
self.0.as_ref().map(|vec| vec.inner_type_name())
}
/// Takes the underlying original `Vec<T>` out of the `UniVec` and returns it.
/// `self` is left non associated and can be used to store a different type.
///
/// # Returns
///
/// Returns `Ok(Some(Vec<T>))` when the underlying vector is successfully taken.
/// Returns `Ok(None)` when `self` had no type associated.
///
/// # Errors
///
/// Returns `Err(TypeError)` when the `UniVec` does not store `T's`.
/// The `UniVec` is left unchanged then.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
///
/// univec.push(42_i32);
///
/// let vec = univec.take::<i32>().unwrap().unwrap();
///
/// assert_eq!(vec, vec![42]);
/// ```
pub fn take<T: 'static>(&mut self) -> Result<Option<Vec<T>>, TypeError> {
if self.is_empty() {
Ok(None)
} else if self.type_check::<T>() {
// SAFETY: We just checked the type_id and that the UniVec is not empty
unsafe {
let vec = self.0.take().unwrap_unchecked();
// PLANNED: use Box::into_inner() once stable or trait downcasting when available.
#[allow(clippy::cast_ptr_alignment)]
Ok(Some(*Box::from_raw(Box::into_raw(vec).cast::<Vec<T>>())))
}
} else {
Err(TypeError)
}
}
/// Returns the underlying original `Vec<T>` of a `UniVec`. Consumes the `UniVec`.
///
/// # Returns
///
/// Returns `Ok(Some(Vec<T>))` if the underlying vector was successfully taken.
/// Returns `Ok(None)` when the `UniVec` was empty.
///
/// # Errors
///
/// Returns `Err(TypeErrorIntoInner(self))` when the `UniVec` does not store `T's`.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
///
/// univec.push(42_i32);
///
/// let vec = univec.into_inner::<i32>().unwrap().unwrap();
///
/// assert_eq!(vec, vec![42]);
/// ```
pub fn into_inner<T: 'static>(mut self) -> Result<Option<Vec<T>>, TypeErrorIntoInner> {
if self.is_empty() {
Ok(None)
} else if self.type_check::<T>() {
// SAFETY: We just checked the type_id and that the UniVec is not empty
unsafe {
let vec = self.0.take().unwrap_unchecked();
// PLANNED: use Box::into_inner() once stable or trait downcasting when available.
#[allow(clippy::cast_ptr_alignment)]
Ok(Some(*Box::from_raw(Box::into_raw(vec).cast::<Vec<T>>())))
}
} else {
Err(TypeErrorIntoInner(self))
}
}
/// Try to get a reference to the underlying original `Vec<T>` of a `UniVec`.
///
/// # Returns
///
/// Returns `Ok(Some(&Vec<T>))` when the underlying `Vec<T>` is available.
/// Returns `Ok(None)` when the `UniVec` is not associated with any type.
///
/// # Errors
///
/// Returns `Err(TypeError)` when the `UniVec` does not store `T's`.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
///
/// univec.push(42_i32);
///
/// let vec = univec.try_as_vec::<i32>().unwrap().unwrap();
///
/// assert_eq!(*vec, vec![42]);
/// ```
pub fn try_as_vec<T: 'static>(&self) -> Result<Option<&Vec<T>>, TypeError> {
self.0
.as_ref()
.map(|b| b.as_any().downcast_ref::<Vec<T>>().ok_or(TypeError))
.transpose()
}
/// Get a reference to the underlying original `Vec<T>` of a `UniVec`.
///
/// # Panics
///
/// Panics if the `UniVec` does not store `T's` this includes the case when it has no
/// associated type.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
///
/// univec.push(42_i32);
///
/// let vec = univec.as_vec::<i32>();
///
/// assert_eq!(*vec, vec![42]);
/// ```
#[must_use]
pub fn as_vec<T: 'static>(&self) -> &Vec<T> {
self.0
.as_ref()
.expect("This Univec has no type associated")
.as_any()
.downcast_ref::<Vec<T>>()
.expect("This UniVec does not store the requested type")
}
// PLANNED: when stable
// unsafe fn as_vec_unchecked<T: 'static>(&mut self) -> &mut Vec<T> {
// self.0
// .as_ref()
// .unwrap_unchecked()
// .as_any()
// .downcast_unchecked::<Vec<T>>()
// }
/// Try to get a mutable reference to the underlying original `Vec<T>` of a `UniVec`.
///
/// # Returns
///
/// Returns `Ok(Some(&mut Vec<T>))` if the underlying `Vec<T>` is available.
/// Returns `Ok(None)` when the `UniVec` is not associated to a type.
///
/// # Errors
///
/// Returns `Err(TypeError)` when the `UniVec` does not store `T's`.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
///
/// univec.push(42_i32);
///
/// let vec = univec.try_as_vec_mut::<i32>().unwrap().unwrap();
///
/// vec.push(10);
///
/// assert_eq!(*vec, vec![42, 10]);
/// ```
pub fn try_as_vec_mut<T: 'static>(&mut self) -> Result<Option<&mut Vec<T>>, TypeError> {
self.0
.as_mut()
.map(|b| b.as_any_mut().downcast_mut::<Vec<T>>().ok_or(TypeError))
.transpose()
}
/// Get a mutable reference to the underlying original `Vec<T>` of a `UniVec`. Will
/// associate `Self` with a empty `Vec<T>` when the `UniVec` is not associated to a type.
///
/// # Panics
///
/// Panics if the `UniVec` does not store `T's`.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
///
/// univec.push(42_i32);
///
/// let vec = univec.as_vec_mut::<i32>();
///
/// vec.push(10);
///
/// assert_eq!(*vec, vec![42, 10]);
/// ```
#[must_use]
pub fn as_vec_mut<T: 'static>(&mut self) -> &mut Vec<T> {
let _ = self.ensure::<T>(0);
self.0
.as_mut()
.expect("This Univec has no type associated")
.as_any_mut()
.downcast_mut::<Vec<T>>()
.expect("This UniVec does not store the requested type")
}
// PLANNED: when stable
// unsafe fn vec_mut_unchecked<T: 'static>(&mut self) -> &mut Vec<T> {
// self.0
// .as_mut()
// .unwrap_unchecked()
// .as_any_mut()
// .downcast_mut_unchecked::<Vec<T>>()
// }
/// Try to get a reference to a slice of underlying original `Vec<T>` of a `UniVec`.
///
/// # Returns
///
/// Returns `Ok(Some(&[T]))` if the underlying `Vec<T>` is available.
/// Returns `Ok(None)` when the `UniVec` is not associated to a type.
///
/// # Errors
///
/// Returns `Err(TypeError)` when the `UniVec` does not store `T's`.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
///
/// univec.push(42_i32);
///
/// let slice = univec.try_as_slice::<i32>().unwrap().unwrap();
///
/// assert_eq!(slice, &[42]);
/// ```
#[inline]
pub fn try_as_slice<T: 'static>(&self) -> Result<Option<&[T]>, TypeError> {
Ok(self.try_as_vec::<T>()?.map(Vec::as_slice))
}
/// Get a reference to a slice of underlying original `Vec<T>` of a `UniVec`.
///
/// # Returns
///
/// Returns `&[T]` if the underlying `Vec<T>` is available.
///
/// # Panics
///
/// Panics if the `UniVec` does not store `T's` or has no associated type.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
///
/// univec.push(42_i32);
///
/// let slice = univec.as_slice::<i32>();
///
/// assert_eq!(slice, &[42]);
/// ```
#[inline]
#[must_use]
pub fn as_slice<T: 'static>(&self) -> &[T] {
self.as_vec::<T>().as_slice()
}
/// Try to get a mutable reference to a slice of underlying original `Vec<T>` of a
/// `UniVec`.
///
/// # Returns
///
/// Returns `Ok(Some(&mut [T]))` if the underlying `Vec<T>` is available.
/// Returns `Ok(None)` when the `UniVec` is not associated to a type.
///
/// # Errors
///
/// Returns `Err(TypeError)` when the `UniVec` does not store `T's`.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
///
/// univec.push(42_i32);
///
/// let slice = univec.try_as_mut_slice::<i32>().unwrap().unwrap();
///
/// slice[0] = 10;
///
/// assert_eq!(slice, &[10]);
/// assert_eq!(univec.get::<i32>(0), Some(&10));
/// ```
#[inline]
pub fn try_as_mut_slice<T: 'static>(&mut self) -> Result<Option<&mut [T]>, TypeError> {
Ok(self.try_as_vec_mut::<T>()?.map(Vec::as_mut_slice))
}
/// Get a mutable reference to a slice of underlying original `Vec<T>` of a `UniVec`.
/// Will associate `Self` with a empty `Vec<T>` when the `UniVec` is not associated to a
/// type.
///
/// # Returns
///
/// Returns the underlying `&mut [T]`.
///
/// # Panics
///
/// Panics if the `UniVec` does not store `T's`.
///
/// # Example
///
/// ```
/// # use univec::UniVec;
/// let mut univec = UniVec::new();
///
/// univec.push(42_i32);
///
/// let slice = univec.as_mut_slice::<i32>();
///
/// slice[0] = 10;
///
/// assert_eq!(slice, &[10]);
/// assert_eq!(univec.get::<i32>(0), Some(&10));
/// ```
#[inline]
#[must_use]
pub fn as_mut_slice<T: 'static>(&mut self) -> &mut [T] {
self.as_vec_mut::<T>().as_mut_slice()
}
}
// UniVec needs a custom Debug implementation to relax the requirement of T: Debug.
impl Debug for UniVec {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self.0 {
Some(ref vec) => write!(f, "UniVec(Some(Vec<{}>))", vec.inner_type_name()),
None => write!(f, "UniVec(None)"),
}
}
}
// private trait
trait UniVecOps: Any {
/// Pops a value from the `UniVec` as a boxed trait object.
///
/// # Returns
///
/// Returns `Some(Box<dyn Any>)` if a value is successfully popped, otherwise returns `None`.
fn pop_box(&mut self) -> Option<Box<dyn Any>>;
/// Pops and drops a value from the univec.
///
/// # Returns
///
/// Returns `true` if a value is successfully popped, otherwise returns `false`.
fn drop_last(&mut self) -> bool;
/// Returns the length of an `UniVec`.
fn len(&self) -> usize;
/// Returns the capacity of an `UniVec`.
fn capacity(&self) -> usize;
/// Reserve capacity for at least additional more elements to be inserted in the given.
fn reserve(&mut self, additional: usize);
/// Returns the `TypeId` of the stored elements
fn inner_type_id(&self) -> TypeId;
/// Returns the type name of the stored elements
fn inner_type_name(&self) -> &'static str;
/// Coerces `&self` to `&dyn Any`.
fn as_any(&self) -> &dyn Any;
/// Coerces `&mut self` to `&mut dyn Any`.
fn as_any_mut(&mut self) -> &mut dyn Any;
}
impl<T> UniVecOps for Vec<T>
where
T: 'static,
{
fn pop_box(&mut self) -> Option<Box<dyn Any>> {
let value = self.pop()?;
Some(Box::new(value))
}
#[inline]
fn drop_last(&mut self) -> bool {
self.pop().is_some()
}
#[inline]
fn len(&self) -> usize {
self.len()
}
#[inline]
fn capacity(&self) -> usize {
self.capacity()
}
#[inline]
fn reserve(&mut self, additional: usize) {
self.reserve(additional);
}
#[inline]
fn inner_type_id(&self) -> TypeId {
TypeId::of::<T>()
}
fn inner_type_name(&self) -> &'static str {
std::any::type_name::<T>()
}
#[inline]
fn as_any(&self) -> &dyn Any {
self
}
#[inline]
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
}
impl<T> From<Vec<T>> for UniVec
where
T: 'static,
{
#[inline]
fn from(vec: Vec<T>) -> Self {
Self(Some(Box::new(vec)))
}
}
/// Trait to convert a types into an `usize` index.
///
/// Sometimes its convenient to keep indices in a type other than `usize`. This trait allows
/// to convert such types into an `usize` index. `UniVec` uses this trait to convert the
/// index parameters. Any other indexing operation that requires an `usize` index can use this
/// trait as well. Can be defined for custom types but consider to implement `impl
/// TryFrom<YourType> for usize` instead since you get `TryInto` and `IntoIndex` for free.
///
/// # Example
///
/// ```
/// # use univec::IntoIndex;
/// let v = vec![1,2,3];
///
/// assert_eq!(v[1u8.into_index()], 2);
/// ```
pub trait IntoIndex {
/// The error type that can be returned when converting the type into an index.
type Error;
/// Converts the type into an `usize` index. Unlike `std::convert::{Into, TryInto}` this
/// can panic when the value is not in the range of `usize::MIN..=usize::MAX`.
fn into_index(self) -> usize;
/// Tries to convert a type into `usize`.
/// This can be used to convert a type into an index without panicking.
///
/// # Errors
///
/// Returns an error when the value is not in the range of `usize::MIN..=usize::MAX`.
fn try_into_index(self) -> Result<usize, Self::Error>;
}
/// `IntoIndex` is implemented for all types that implement `TryInto<usize>`.
impl<T> IntoIndex for T
where
Self: TryInto<usize>,
<T as TryInto<usize>>::Error: Debug,
{
type Error = <T as TryInto<usize>>::Error;
#[inline]
fn into_index(self) -> usize {
self.try_into().expect("index out of bounds")
}
#[inline]
fn try_into_index(self) -> Result<usize, Self::Error> {
self.try_into()
}
}
/// Trait to get a reference to an element at a given index.
///
/// `UniVec` can not use the standard indexing syntax `[]` because it can store multiple types.
/// Instead, one can use the `at` method to get a reference to an element at a given index.
/// For convenience this trait is implemented for `Vec<T>` as well. The index can be of any type
/// that implements `IntoIndex`.
///
/// # Example
///
/// ```
/// # use univec::At;
/// let v = vec![1,2,3];
///
/// assert_eq!(*v.at(1u8), 2);
/// ```
pub trait At<T> {
/// Returns a reference to the element at the given index.
///
/// # Panics
///
/// Panics when the index is out of bounds.
fn at(&self, index: impl IntoIndex) -> &T;
}
impl<T: 'static> At<T> for UniVec {
fn at(&self, index: impl IntoIndex) -> &T {
self.get(index.into_index()).unwrap()
}
}
impl<T> At<T> for Vec<T> {
fn at(&self, index: impl IntoIndex) -> &T {
&self[index.into_index()]
}
}
/// Trait to get a mutable reference to an element at a given index.
///
/// This trait is implemented for `UniVec` and `Vec<T>`. It allows to get a mutable reference
/// to an element at a given index. The index can be of any type that implements `IntoIndex`.
///
/// # Example
///
/// ```
/// # use univec::{At,AtMut};
/// let mut v = vec![1,2,3];
///
/// *v.at_mut(1u8) = 10;
///
/// assert_eq!(*v.at(1i16), 10);
/// ```
pub trait AtMut<T> {
/// Returns a mutable reference to the element at the given index.
///
/// # Panics
///
/// Panics when the index is out of bounds.
fn at_mut(&mut self, index: impl IntoIndex) -> &mut T;
}
impl<T: 'static> AtMut<T> for UniVec {
fn at_mut(&mut self, index: impl IntoIndex) -> &mut T {
self.get_mut(index.into_index()).unwrap()
}
}
impl<T> AtMut<T> for Vec<T> {
fn at_mut(&mut self, index: impl IntoIndex) -> &mut T {
&mut self[index.into_index()]
}
}
/// Error that happens on a query when the requested type is not stored in the `UniVec`.
#[derive(thiserror::Error, Debug, PartialEq)]
#[error("This UniVec does not store the requested type")]
pub struct TypeError;
/// When pushing/setting an element fails because of a type error, one gets the failed element back.
#[derive(thiserror::Error, PartialEq)]
#[error("This UniVec does not store the requested type")]
pub struct TypeErrorValue<T>(
/// The element that failed to insert.
pub T,
);
// needs a custom debug implementation to relax the requirement of T: Debug.
impl<T> Debug for TypeErrorValue<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "TypeErrorValue<{}>", std::any::type_name::<T>())
}
}
/// When `UniVec::into_inner()` fails because of a type error, one gets the failed `UniVec` back.
#[derive(thiserror::Error, Debug)]
#[error("This UniVec does not store the requested type")]
pub struct TypeErrorIntoInner(
/// The `UniVec` that failed to convert into the inner `Vec<T>`.
pub UniVec,
);
#[cfg(test)]
mod tests {
use super::*;
// test UniVec::type_check()
#[test]
fn test_type_check() {
let mut univec = UniVec::new();
assert!(univec.type_check::<i64>());
univec.push(42_i32).unwrap();
assert!(univec.type_check::<i32>());
assert!(!univec.type_check::<i64>());
}
}