BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-base / src / index_path.rs

index_path.rs

eef6c0a4 History
index_path.rs 2.7 KiB Download Raw
1use std::fmt::{Debug, Display};
2
3use gpui::ElementId;
4
5/// Represents an index path in a list, which consists of a section index,
6///
7/// The default values for section, row, and column are all set to 0.
8#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
9pub struct IndexPath {
10 /// The section index.
11 pub section: usize,
12 /// The item index in the section.
13 pub row: usize,
14 /// The column index.
15 pub column: usize,
16}
17
18impl From<IndexPath> for ElementId {
19 fn from(path: IndexPath) -> Self {
20 ElementId::Name(format!("index-path({},{},{})", path.section, path.row, path.column).into())
21 }
22}
23
24impl Display for IndexPath {
25 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26 write!(
27 f,
28 "IndexPath(section: {}, row: {}, column: {})",
29 self.section, self.row, self.column
30 )
31 }
32}
33
34impl IndexPath {
35 /// Create a new index path with the specified section and row.
36 ///
37 /// The `section` is set to 0 by default.
38 /// The `column` is set to 0 by default.
39 pub fn new(row: usize) -> Self {
40 IndexPath {
41 section: 0,
42 row,
43 ..Default::default()
44 }
45 }
46
47 /// Set the section for the index path.
48 pub fn section(mut self, section: usize) -> Self {
49 self.section = section;
50 self
51 }
52
53 /// Set the row for the index path.
54 pub fn row(mut self, row: usize) -> Self {
55 self.row = row;
56 self
57 }
58
59 /// Set the column for the index path.
60 pub fn column(mut self, column: usize) -> Self {
61 self.column = column;
62 self
63 }
64
65 /// Check if the self is equal to the given index path (Same section and row).
66 pub fn eq_row(&self, index: IndexPath) -> bool {
67 self.section == index.section && self.row == index.row
68 }
69}
70
71#[cfg(test)]
72mod tests {
73 use super::*;
74
75 #[test]
76 fn test_into_element_id() {
77 let index_path = IndexPath::new(2).section(1).column(3);
78 let element_id: ElementId = index_path.into();
79 assert_eq!(element_id.to_string(), "index-path(1,2,3)");
80 }
81
82 #[test]
83 fn test_display() {
84 assert_eq!(
85 format!("{}", IndexPath::new(2).section(1).column(3)),
86 "IndexPath(section: 1, row: 2, column: 3)"
87 );
88 }
89
90 #[test]
91 fn test_index_path() {
92 let mut index_path = IndexPath::default();
93 assert_eq!(index_path.section, 0);
94 assert_eq!(index_path.row, 0);
95 assert_eq!(index_path.column, 0);
96
97 index_path = index_path.section(1).row(2).column(3);
98 assert_eq!(index_path.section, 1);
99 assert_eq!(index_path.row, 2);
100 assert_eq!(index_path.column, 3);
101 }
102}