vvv_engine/protocol/
selection.rs1use std::collections::BTreeSet;
2
3use serde::{Deserialize, Serialize};
4
5use crate::{Match, MatchId};
6
7#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
16#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
17#[serde(rename_all = "lowercase")]
18pub enum Selection {
19 #[default]
20 All,
21 Ids(BTreeSet<MatchId>),
22 Ordinals(BTreeSet<usize>),
23}
24
25#[derive(Debug, thiserror::Error, PartialEq, Eq)]
26pub enum SelectionError {
27 #[error("no match with id(s) {}; the files may have changed since the search", ids.iter().map(ToString::to_string).collect::<Vec<_>>().join(", "))]
28 Unresolved { ids: BTreeSet<MatchId> },
29 #[error("no match numbered {}; the search found {found}", ordinals.iter().map(ToString::to_string).collect::<Vec<_>>().join(", "))]
30 OutOfRange {
31 ordinals: BTreeSet<usize>,
32 found: usize,
33 },
34}
35
36impl Selection {
37 pub fn ids(ids: impl IntoIterator<Item = MatchId>) -> Self {
38 Self::Ids(ids.into_iter().collect())
39 }
40
41 pub fn ordinals(ordinals: impl IntoIterator<Item = usize>) -> Self {
42 Self::Ordinals(ordinals.into_iter().collect())
43 }
44
45 pub fn is_all(&self) -> bool {
46 matches!(self, Self::All)
47 }
48
49 pub fn narrow(&self, matches: Vec<Match>) -> Result<Vec<Match>, SelectionError> {
50 match self {
51 Self::All => Ok(matches),
52 Self::Ordinals(wanted) => {
53 let found = matches.len();
54 let out: BTreeSet<usize> = wanted
55 .iter()
56 .filter(|&&n| n == 0 || n > found)
57 .copied()
58 .collect();
59 if !out.is_empty() {
60 return Err(SelectionError::OutOfRange {
61 ordinals: out,
62 found,
63 });
64 }
65 Ok(matches
66 .into_iter()
67 .enumerate()
68 .filter(|(i, _)| wanted.contains(&(i + 1)))
69 .map(|(_, m)| m)
70 .collect())
71 }
72 Self::Ids(wanted) => {
73 let kept: Vec<Match> = matches
74 .into_iter()
75 .filter(|m| wanted.contains(&m.id))
76 .collect();
77 let found: BTreeSet<&MatchId> = kept.iter().map(|m| &m.id).collect();
78 let missing: BTreeSet<MatchId> = wanted
79 .iter()
80 .filter(|id| !found.contains(id))
81 .cloned()
82 .collect();
83 if missing.is_empty() {
84 Ok(kept)
85 } else {
86 Err(SelectionError::Unresolved { ids: missing })
87 }
88 }
89 }
90 }
91}
92
93impl FromIterator<MatchId> for Selection {
94 fn from_iter<I: IntoIterator<Item = MatchId>>(iter: I) -> Self {
95 Self::ids(iter)
96 }
97}