1use std::ops::Range;
4use std::path::PathBuf;
5
6use serde::{Deserialize, Serialize};
7
8use super::helpers::{parse_todo_state_from_title, tag_token_spans_in};
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
21#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
22#[serde(rename_all = "lowercase")]
23pub enum DocumentKind {
24 Note,
25 Todo,
26 Bookmark,
27}
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
35#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
36#[serde(rename_all = "lowercase")]
37pub enum TodoState {
38 Open,
39 Done,
40}
41
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
54#[serde(rename_all = "snake_case", tag = "kind")]
55pub enum ParseContext {
56 FromPath(PathBuf),
57 Explicit(DocumentKind),
58}
59
60#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct NoteDocument {
72 pub(crate) source: Vec<u8>,
73 pub(crate) partition: Partition,
74}
75
76#[derive(Debug, Clone, PartialEq, Eq)]
77pub(crate) enum Partition {
78 Note(NotePartition),
79 Todo(TodoPartition),
80 Bookmark(BookmarkPartition),
81}
82
83#[derive(Debug, Clone, PartialEq, Eq)]
84pub(crate) struct NotePartition {
85 pub(crate) prefix_range: Range<usize>,
86 pub(crate) title_range: Option<Range<usize>>,
87 pub(crate) tags_prefix_range: Option<Range<usize>>,
88 pub(crate) separator_ranges: Vec<Range<usize>>,
89 pub(crate) body_ranges: Vec<Range<usize>>,
90}
91
92#[derive(Debug, Clone, PartialEq, Eq)]
93pub(crate) struct TodoPartition {
94 pub(crate) prefix_range: Range<usize>,
95 pub(crate) title_range: Option<Range<usize>>,
96 pub(crate) separator_ranges: Vec<Range<usize>>,
97 pub(crate) tag_section_range: Option<Range<usize>>,
98 pub(crate) body_ranges: Vec<Range<usize>>,
99}
100
101#[derive(Debug, Clone, PartialEq, Eq)]
102pub(crate) struct BookmarkPartition {
103 pub(crate) prefix_range: Range<usize>,
104 pub(crate) title_range: Option<Range<usize>>,
105 pub(crate) url_range: Option<Range<usize>>,
106 pub(crate) separator_ranges: Vec<Range<usize>>,
107 pub(crate) tag_section_range: Option<Range<usize>>,
108 pub(crate) body_ranges: Vec<Range<usize>>,
109}
110
111impl NoteDocument {
112 pub fn source(&self) -> &[u8] {
115 &self.source
116 }
117
118 pub fn emit(&self) -> &[u8] {
122 &self.source
123 }
124
125 pub fn verify_partition(&self) -> Result<(), &'static str> {
136 let source_len = self.source.len();
137 let mut covered: Vec<(usize, usize)> = Vec::new();
138 let mut check = |r: &std::ops::Range<usize>, name: &str| -> Result<(), &'static str> {
139 if r.start > r.end {
140 return Err("range not half-open (start > end)");
141 }
142 if r.end > source_len {
143 return Err("range extends past source.len()");
144 }
145 covered.push((r.start, r.end));
146 let _ = name;
147 Ok(())
148 };
149 match &self.partition {
150 Partition::Note(note) => {
151 check(¬e.prefix_range, "prefix")?;
152 if let Some(r) = ¬e.title_range {
153 check(r, "title")?;
154 }
155 if let Some(r) = ¬e.tags_prefix_range {
156 check(r, "tags_prefix")?;
157 }
158 for r in ¬e.separator_ranges {
159 check(r, "separator")?;
160 }
161 for r in ¬e.body_ranges {
162 check(r, "body")?;
163 }
164 }
165 Partition::Todo(todo) => {
166 check(&todo.prefix_range, "prefix")?;
167 if let Some(r) = &todo.title_range {
168 check(r, "title")?;
169 }
170 for r in &todo.separator_ranges {
171 check(r, "separator")?;
172 }
173 if let Some(r) = &todo.tag_section_range {
174 check(r, "tag_section")?;
175 }
176 for r in &todo.body_ranges {
177 check(r, "body")?;
178 }
179 }
180 Partition::Bookmark(bookmark) => {
181 check(&bookmark.prefix_range, "prefix")?;
182 if let Some(r) = &bookmark.title_range {
183 check(r, "title")?;
184 }
185 if let Some(r) = &bookmark.url_range {
186 check(r, "url")?;
187 }
188 for r in &bookmark.separator_ranges {
189 check(r, "separator")?;
190 }
191 if let Some(r) = &bookmark.tag_section_range {
192 check(r, "tag_section")?;
193 }
194 for r in &bookmark.body_ranges {
195 check(r, "body")?;
196 }
197 }
198 }
199 covered.sort_by_key(|&(s, _)| s);
200 for window in covered.windows(2) {
205 if window[0].1 > window[1].0 {
206 return Err("ranges overlap");
207 }
208 if window[0].1 < window[1].0 {
209 return Err("partition leaves a gap (internal unassigned bytes)");
210 }
211 }
212 if covered.first().map(|r| r.0) != Some(0) {
213 return Err("partition does not start at byte 0");
214 }
215 if covered.last().map(|r| r.1) != Some(source_len) {
216 return Err("partition does not cover to source.len()");
217 }
218 Ok(())
219 }
220
221 pub fn kind(&self) -> DocumentKind {
223 match &self.partition {
224 Partition::Note(_) => DocumentKind::Note,
225 Partition::Todo(_) => DocumentKind::Todo,
226 Partition::Bookmark(_) => DocumentKind::Bookmark,
227 }
228 }
229
230 pub fn todo_state(&self) -> Option<TodoState> {
234 match &self.partition {
235 Partition::Todo(todo) => {
236 let title = todo.title_range.as_ref()?;
237 let line = self.source.get(title.start..title.end)?;
238 parse_todo_state_from_title(line)
239 }
240 _ => None,
241 }
242 }
243
244 pub fn title(&self) -> Option<&[u8]> {
247 let range = self.title_range()?;
248 Some(&self.source[range])
249 }
250
251 pub fn title_str(&self) -> Option<Result<&str, std::str::Utf8Error>> {
255 self.title().map(std::str::from_utf8)
256 }
257
258 pub fn tags_prefix(&self) -> Option<&[u8]> {
261 let NotePartition {
262 tags_prefix_range, ..
263 } = match &self.partition {
264 Partition::Note(note) => note,
265 _ => return None,
266 };
267 Some(&self.source[tags_prefix_range.clone()?])
268 }
269
270 pub fn tag_section(&self) -> Option<&[u8]> {
274 let range = self.tag_section_range()?;
275 Some(&self.source[range])
276 }
277
278 pub fn tags(&self) -> TagsIter<'_> {
283 TagsIter {
284 doc: self,
285 token_spans: self.tag_token_spans().into_iter(),
286 }
287 }
288
289 pub fn tags_str(&self) -> TagsStrIter<'_> {
292 TagsStrIter {
293 doc: self,
294 token_spans: self.tag_token_spans().into_iter(),
295 }
296 }
297
298 pub fn tag_token_spans(&self) -> Vec<Range<usize>> {
303 match &self.partition {
304 Partition::Note(note) => {
305 tag_token_spans_in(&self.source, note.tags_prefix_range.as_ref())
306 }
307 Partition::Todo(todo) => {
308 tag_token_spans_in(&self.source, todo.tag_section_range.as_ref())
309 }
310 Partition::Bookmark(bookmark) => {
311 tag_token_spans_in(&self.source, bookmark.tag_section_range.as_ref())
312 }
313 }
314 }
315
316 pub fn body_ranges(&self) -> Vec<Range<usize>> {
318 match &self.partition {
319 Partition::Note(note) => note.body_ranges.clone(),
320 Partition::Todo(todo) => todo.body_ranges.clone(),
321 Partition::Bookmark(bookmark) => bookmark.body_ranges.clone(),
322 }
323 }
324
325 pub fn body(&self) -> BodyFragments<'_> {
327 BodyFragments {
328 source: &self.source,
329 ranges: self.body_ranges().into_iter(),
330 }
331 }
332
333 pub fn body_bytes(&self) -> Vec<u8> {
335 let mut out = Vec::new();
336 for fragment in self.body() {
337 out.extend_from_slice(fragment);
338 }
339 out
340 }
341
342 pub fn title_byte_range(&self) -> Option<Range<usize>> {
344 self.title_range()
345 }
346
347 pub fn tags_byte_range(&self) -> Option<Range<usize>> {
349 match &self.partition {
350 Partition::Note(note) => note.tags_prefix_range.clone(),
351 Partition::Todo(todo) => todo.tag_section_range.clone(),
352 Partition::Bookmark(bookmark) => bookmark.tag_section_range.clone(),
353 }
354 }
355
356 pub fn url(&self) -> Option<&[u8]> {
360 let BookmarkPartition { url_range, .. } = match &self.partition {
361 Partition::Bookmark(bookmark) => bookmark,
362 _ => return None,
363 };
364 url_range.as_ref().map(|r| &self.source[r.clone()])
365 }
366
367 pub fn url_str(&self) -> Option<Result<&str, std::str::Utf8Error>> {
370 self.url().map(std::str::from_utf8)
371 }
372
373 fn title_range(&self) -> Option<Range<usize>> {
374 match &self.partition {
375 Partition::Note(note) => note.title_range.clone(),
376 Partition::Todo(todo) => todo.title_range.clone(),
377 Partition::Bookmark(bookmark) => bookmark.title_range.clone(),
378 }
379 }
380
381 fn tag_section_range(&self) -> Option<Range<usize>> {
382 match &self.partition {
383 Partition::Note(_) => None,
384 Partition::Todo(todo) => todo.tag_section_range.clone(),
385 Partition::Bookmark(bookmark) => bookmark.tag_section_range.clone(),
386 }
387 }
388}
389
390pub struct TagsIter<'a> {
392 doc: &'a NoteDocument,
393 token_spans: std::vec::IntoIter<Range<usize>>,
394}
395
396impl<'a> Iterator for TagsIter<'a> {
397 type Item = &'a [u8];
398 fn next(&mut self) -> Option<Self::Item> {
399 self.token_spans.next().map(|r| &self.doc.source[r])
400 }
401}
402
403pub struct TagsStrIter<'a> {
405 doc: &'a NoteDocument,
406 token_spans: std::vec::IntoIter<Range<usize>>,
407}
408
409impl<'a> Iterator for TagsStrIter<'a> {
410 type Item = Result<&'a str, std::str::Utf8Error>;
411 fn next(&mut self) -> Option<Self::Item> {
412 self.token_spans
413 .next()
414 .map(|r| std::str::from_utf8(&self.doc.source[r]))
415 }
416}
417
418pub struct BodyFragments<'a> {
420 source: &'a [u8],
421 ranges: std::vec::IntoIter<Range<usize>>,
422}
423
424impl<'a> Iterator for BodyFragments<'a> {
425 type Item = &'a [u8];
426 fn next(&mut self) -> Option<Self::Item> {
427 self.ranges.next().map(|r| &self.source[r])
428 }
429}