-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathlib.rs
216 lines (195 loc) · 6 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
use comments_docsource::CommentDocumentation;
use options_docsource::{OptionDocumentation, OptionsDatabaseType};
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
use std::path::PathBuf;
use thiserror::Error;
use xml_docsource::XmlFuncDocumentation;
pub mod comments_docsource;
pub mod nixpkgs_tree_docsource;
pub mod options_docsource;
pub mod xml_docsource;
pub trait Cache
where
Self: Sized + DocSource + serde::Serialize,
{
/// Deserializes content to Self
fn load<'a>(content: &'a [u8]) -> Result<Self, Errors>
where
Self: serde::Deserialize<'a>,
{
Ok(bincode::deserialize(content)?)
}
/// Saves self to a file, serialized with bincode
fn save(&self, filename: &PathBuf) -> Result<(), Errors> {
let x = bincode::serialize(self)?;
std::fs::write(filename, x)?;
Ok(())
}
}
#[derive(Error, Debug)]
pub enum Errors {
#[error("IO Error for file {}: {}", .filename, .err)]
FileIo {
filename: String,
err: std::io::Error,
},
#[error("Failed to perform IO on a cache file")]
CacheFileIo(#[from] std::io::Error),
#[error("Failed to serialize/deserialize cache(bincode)")]
Bincode(#[from] bincode::Error),
#[error("Failed to serialize/deserialize cache(serde_json)")]
SerdeJson(#[from] serde_json::Error),
#[error("XML parsing error for file {}: {}", .filename, .err)]
XmlParse {
filename: String,
err: roxmltree::Error,
},
}
#[derive(Debug, PartialEq, Eq)]
pub enum DocEntry {
OptionDoc(OptionsDatabaseType, OptionDocumentation),
CommentDoc(CommentDocumentation),
XmlFuncDoc(XmlFuncDocumentation),
NixpkgsTreeDoc(String),
}
impl DocEntry {
pub fn name(&self) -> String {
match self {
DocEntry::OptionDoc(_, x) => x.name(),
DocEntry::CommentDoc(x) => x.name(),
DocEntry::XmlFuncDoc(x) => x.name(),
DocEntry::NixpkgsTreeDoc(x) => x.clone(),
}
}
pub fn pretty_printed(&self) -> String {
match self {
DocEntry::OptionDoc(_, x) => x.pretty_printed(),
DocEntry::CommentDoc(x) => x.pretty_printed(),
DocEntry::XmlFuncDoc(x) => x.pretty_printed(),
DocEntry::NixpkgsTreeDoc(x) => x.clone(),
}
}
pub fn source(&self) -> &str {
match self {
DocEntry::OptionDoc(typ, _) => match typ {
OptionsDatabaseType::NixDarwin => "NixDarwin Options",
OptionsDatabaseType::NixOS => "NixOS Options",
OptionsDatabaseType::HomeManager => "HomeManager Options",
},
DocEntry::CommentDoc(_) => "Nixpkgs Comments",
DocEntry::XmlFuncDoc(_) => "Nixpkgs Documentation",
DocEntry::NixpkgsTreeDoc(_) => "Nixpkgs Tree",
}
}
}
pub trait DocSource {
fn all_keys(&self) -> Vec<&str>;
fn search(&self, query: &Lowercase) -> Vec<DocEntry>;
fn search_liberal(&self, query: &Lowercase) -> Vec<DocEntry>;
/// Updates the cache, returns true if anything changed
fn update(&mut self) -> Result<bool, Errors>;
}
#[derive(Default)]
pub struct AggregateDocSource {
sources: Vec<Box<dyn DocSource + Sync>>,
}
impl AggregateDocSource {
pub fn add_source(&mut self, source: Box<dyn DocSource + Sync>) {
self.sources.push(source)
}
}
impl DocSource for AggregateDocSource {
fn all_keys(&self) -> Vec<&str> {
self.sources
.par_iter()
.flat_map(|source| source.all_keys())
.collect()
}
fn search(&self, query: &Lowercase) -> Vec<DocEntry> {
self.sources
.par_iter()
.flat_map(|source| source.search(query))
.collect()
}
fn search_liberal(&self, query: &Lowercase) -> Vec<DocEntry> {
self.sources
.par_iter()
.flat_map(|source| source.search_liberal(query))
.collect()
}
fn update(&mut self) -> Result<bool, Errors> {
unimplemented!();
}
}
pub struct Lowercase<'a>(pub &'a [u8]);
pub(crate) fn starts_with_insensitive_ascii(s: &[u8], prefix: &Lowercase) -> bool {
let prefix = prefix.0;
if s.len() < prefix.len() {
return false;
}
for (i, b) in prefix.into_iter().enumerate() {
// this is safe because of the earlier if check
if unsafe { s.get_unchecked(i) }.to_ascii_lowercase() != *b {
return false;
}
}
true
}
pub(crate) fn contains_insensitive_ascii(s: &[u8], inner: &Lowercase) -> bool {
let inner = inner.0;
if s.len() < inner.len() {
return false;
}
'outer: for i in 0..(s.len() - inner.len() + 1) {
let target = &s[i..i + inner.len()];
for (y, b) in target.into_iter().enumerate() {
if *unsafe { inner.get_unchecked(y) } != b.to_ascii_lowercase() {
continue 'outer;
}
}
return true;
}
false
}
#[test]
fn test_starts_with_insensitive_ascii() {
assert_eq!(
starts_with_insensitive_ascii("This is a string".as_bytes(), &Lowercase(b"this ")),
true,
);
assert_eq!(
starts_with_insensitive_ascii("abc".as_bytes(), &Lowercase(b"abc")),
true,
);
assert_eq!(
starts_with_insensitive_ascii("This is a string".as_bytes(), &Lowercase(b"x")),
false,
);
assert_eq!(
starts_with_insensitive_ascii("thi".as_bytes(), &Lowercase(b"this ")),
false,
);
}
#[test]
fn test_contains_insensitive_ascii() {
assert_eq!(
contains_insensitive_ascii("abc".as_bytes(), &Lowercase(b"b")),
true
);
assert_eq!(
contains_insensitive_ascii("abc".as_bytes(), &Lowercase(b"abc")),
true
);
assert_eq!(
contains_insensitive_ascii("xabcx".as_bytes(), &Lowercase(b"abc")),
true
);
assert_eq!(
contains_insensitive_ascii("abc".as_bytes(), &Lowercase(b"x")),
false
);
assert_eq!(
contains_insensitive_ascii("abc".as_bytes(), &Lowercase(b"abcd")),
false
);
}