Skip to main content

malachite_base/unsigned_vector/
access.rs

1// Copyright © 2026 Mikhail Hogrefe
2//
3// This file is part of Malachite.
4//
5// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
6// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
7// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
8
9use crate::num::basic::unsigneds::PrimitiveUnsigned;
10use crate::unsigned_vector::UnsignedVector;
11use core::ops::{Index, IndexMut};
12
13impl<T: PrimitiveUnsigned> Index<usize> for UnsignedVector<T> {
14    type Output = T;
15
16    /// Gets a reference to the element of an [`UnsignedVector`] at an index.
17    ///
18    /// Indices start at 0, as they do for a [`Vec`].
19    ///
20    /// # Worst-case complexity
21    /// Constant time and additional memory.
22    ///
23    /// # Panics
24    /// Panics if `i` is greater than or equal to the dimension of the vector.
25    ///
26    /// # Examples
27    /// ```
28    /// use core::str::FromStr;
29    /// use malachite_base::unsigned_vector::UnsignedVector;
30    ///
31    /// let v = UnsignedVector::<u32>::from_str("(1, 2, 3)").unwrap();
32    /// assert_eq!(v[0], 1);
33    /// assert_eq!(v[2], 3);
34    /// ```
35    #[inline]
36    fn index(&self, i: usize) -> &T {
37        &self.elements[i]
38    }
39}
40
41impl<T: PrimitiveUnsigned> IndexMut<usize> for UnsignedVector<T> {
42    /// Gets a mutable reference to the element of an [`UnsignedVector`] at an index.
43    ///
44    /// Indices start at 0, as they do for a [`Vec`].
45    ///
46    /// # Worst-case complexity
47    /// Constant time and additional memory.
48    ///
49    /// # Panics
50    /// Panics if `i` is greater than or equal to the dimension of the vector.
51    ///
52    /// # Examples
53    /// ```
54    /// use core::str::FromStr;
55    /// use malachite_base::unsigned_vector::UnsignedVector;
56    ///
57    /// let mut v = UnsignedVector::<u32>::from_str("(1, 2, 3)").unwrap();
58    /// v[1] = 10;
59    /// v[2] += 4;
60    /// assert_eq!(v.to_string(), "(1, 10, 7)");
61    /// ```
62    #[inline]
63    fn index_mut(&mut self, i: usize) -> &mut T {
64        &mut self.elements[i]
65    }
66}