Skip to main content

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