Skip to main content

malachite_nz/integer_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::integer::Integer;
10use crate::integer_vector::IntegerVector;
11use core::ops::{Index, IndexMut};
12
13impl Index<usize> for IntegerVector {
14    type Output = Integer;
15
16    /// Gets a reference to the element of an [`IntegerVector`] 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_nz::integer_vector::IntegerVector;
30    ///
31    /// let v = IntegerVector::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) -> &Integer {
37        &self.elements[i]
38    }
39}
40
41impl IndexMut<usize> for IntegerVector {
42    /// Gets a mutable reference to the element of an [`IntegerVector`] 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_nz::integer::Integer;
56    /// use malachite_nz::integer_vector::IntegerVector;
57    ///
58    /// let mut v = IntegerVector::from_str("(1, 2, 3)").unwrap();
59    /// v[1] = Integer::from(10u32);
60    /// v[2] += Integer::from(4u32);
61    /// assert_eq!(v.to_string(), "(1, 10, 7)");
62    /// ```
63    #[inline]
64    fn index_mut(&mut self, i: usize) -> &mut Integer {
65        &mut self.elements[i]
66    }
67}