use std::ops::Range;
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use super::helpers::{parse_todo_state_from_title, tag_token_spans_in};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(rename_all = "lowercase")]
pub enum DocumentKind {
Note,
Todo,
Bookmark,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(rename_all = "lowercase")]
pub enum TodoState {
Open,
Done,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case", tag = "kind")]
pub enum ParseContext {
FromPath(PathBuf),
Explicit(DocumentKind),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NoteDocument {
pub(crate) source: Vec<u8>,
pub(crate) partition: Partition,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Partition {
Note(NotePartition),
Todo(TodoPartition),
Bookmark(BookmarkPartition),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct NotePartition {
pub(crate) prefix_range: Range<usize>,
pub(crate) title_range: Option<Range<usize>>,
pub(crate) tags_prefix_range: Option<Range<usize>>,
pub(crate) separator_ranges: Vec<Range<usize>>,
pub(crate) body_ranges: Vec<Range<usize>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct TodoPartition {
pub(crate) prefix_range: Range<usize>,
pub(crate) title_range: Option<Range<usize>>,
pub(crate) separator_ranges: Vec<Range<usize>>,
pub(crate) tag_section_range: Option<Range<usize>>,
pub(crate) body_ranges: Vec<Range<usize>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct BookmarkPartition {
pub(crate) prefix_range: Range<usize>,
pub(crate) title_range: Option<Range<usize>>,
pub(crate) url_range: Option<Range<usize>>,
pub(crate) separator_ranges: Vec<Range<usize>>,
pub(crate) tag_section_range: Option<Range<usize>>,
pub(crate) body_ranges: Vec<Range<usize>>,
}
impl NoteDocument {
pub fn source(&self) -> &[u8] {
&self.source
}
pub fn emit(&self) -> &[u8] {
&self.source
}
pub fn verify_partition(&self) -> Result<(), &'static str> {
let source_len = self.source.len();
let mut covered: Vec<(usize, usize)> = Vec::new();
let mut check = |r: &std::ops::Range<usize>, name: &str| -> Result<(), &'static str> {
if r.start > r.end {
return Err("range not half-open (start > end)");
}
if r.end > source_len {
return Err("range extends past source.len()");
}
covered.push((r.start, r.end));
let _ = name;
Ok(())
};
match &self.partition {
Partition::Note(note) => {
check(¬e.prefix_range, "prefix")?;
if let Some(r) = ¬e.title_range {
check(r, "title")?;
}
if let Some(r) = ¬e.tags_prefix_range {
check(r, "tags_prefix")?;
}
for r in ¬e.separator_ranges {
check(r, "separator")?;
}
for r in ¬e.body_ranges {
check(r, "body")?;
}
}
Partition::Todo(todo) => {
check(&todo.prefix_range, "prefix")?;
if let Some(r) = &todo.title_range {
check(r, "title")?;
}
for r in &todo.separator_ranges {
check(r, "separator")?;
}
if let Some(r) = &todo.tag_section_range {
check(r, "tag_section")?;
}
for r in &todo.body_ranges {
check(r, "body")?;
}
}
Partition::Bookmark(bookmark) => {
check(&bookmark.prefix_range, "prefix")?;
if let Some(r) = &bookmark.title_range {
check(r, "title")?;
}
if let Some(r) = &bookmark.url_range {
check(r, "url")?;
}
for r in &bookmark.separator_ranges {
check(r, "separator")?;
}
if let Some(r) = &bookmark.tag_section_range {
check(r, "tag_section")?;
}
for r in &bookmark.body_ranges {
check(r, "body")?;
}
}
}
covered.sort_by_key(|&(s, _)| s);
for window in covered.windows(2) {
if window[0].1 > window[1].0 {
return Err("ranges overlap");
}
if window[0].1 < window[1].0 {
return Err("partition leaves a gap (internal unassigned bytes)");
}
}
if covered.first().map(|r| r.0) != Some(0) {
return Err("partition does not start at byte 0");
}
if covered.last().map(|r| r.1) != Some(source_len) {
return Err("partition does not cover to source.len()");
}
Ok(())
}
pub fn kind(&self) -> DocumentKind {
match &self.partition {
Partition::Note(_) => DocumentKind::Note,
Partition::Todo(_) => DocumentKind::Todo,
Partition::Bookmark(_) => DocumentKind::Bookmark,
}
}
pub fn todo_state(&self) -> Option<TodoState> {
match &self.partition {
Partition::Todo(todo) => {
let title = todo.title_range.as_ref()?;
let line = self.source.get(title.start..title.end)?;
parse_todo_state_from_title(line)
}
_ => None,
}
}
pub fn title(&self) -> Option<&[u8]> {
let range = self.title_range()?;
Some(&self.source[range])
}
pub fn title_str(&self) -> Option<Result<&str, std::str::Utf8Error>> {
self.title().map(std::str::from_utf8)
}
pub fn tags_prefix(&self) -> Option<&[u8]> {
let NotePartition {
tags_prefix_range, ..
} = match &self.partition {
Partition::Note(note) => note,
_ => return None,
};
Some(&self.source[tags_prefix_range.clone()?])
}
pub fn tag_section(&self) -> Option<&[u8]> {
let range = self.tag_section_range()?;
Some(&self.source[range])
}
pub fn tags(&self) -> TagsIter<'_> {
TagsIter {
doc: self,
token_spans: self.tag_token_spans().into_iter(),
}
}
pub fn tags_str(&self) -> TagsStrIter<'_> {
TagsStrIter {
doc: self,
token_spans: self.tag_token_spans().into_iter(),
}
}
pub fn tag_token_spans(&self) -> Vec<Range<usize>> {
match &self.partition {
Partition::Note(note) => {
tag_token_spans_in(&self.source, note.tags_prefix_range.as_ref())
}
Partition::Todo(todo) => {
tag_token_spans_in(&self.source, todo.tag_section_range.as_ref())
}
Partition::Bookmark(bookmark) => {
tag_token_spans_in(&self.source, bookmark.tag_section_range.as_ref())
}
}
}
pub fn body_ranges(&self) -> Vec<Range<usize>> {
match &self.partition {
Partition::Note(note) => note.body_ranges.clone(),
Partition::Todo(todo) => todo.body_ranges.clone(),
Partition::Bookmark(bookmark) => bookmark.body_ranges.clone(),
}
}
pub fn body(&self) -> BodyFragments<'_> {
BodyFragments {
source: &self.source,
ranges: self.body_ranges().into_iter(),
}
}
pub fn body_bytes(&self) -> Vec<u8> {
let mut out = Vec::new();
for fragment in self.body() {
out.extend_from_slice(fragment);
}
out
}
pub fn title_byte_range(&self) -> Option<Range<usize>> {
self.title_range()
}
pub fn tags_byte_range(&self) -> Option<Range<usize>> {
match &self.partition {
Partition::Note(note) => note.tags_prefix_range.clone(),
Partition::Todo(todo) => todo.tag_section_range.clone(),
Partition::Bookmark(bookmark) => bookmark.tag_section_range.clone(),
}
}
pub fn url(&self) -> Option<&[u8]> {
let BookmarkPartition { url_range, .. } = match &self.partition {
Partition::Bookmark(bookmark) => bookmark,
_ => return None,
};
url_range.as_ref().map(|r| &self.source[r.clone()])
}
pub fn url_str(&self) -> Option<Result<&str, std::str::Utf8Error>> {
self.url().map(std::str::from_utf8)
}
fn title_range(&self) -> Option<Range<usize>> {
match &self.partition {
Partition::Note(note) => note.title_range.clone(),
Partition::Todo(todo) => todo.title_range.clone(),
Partition::Bookmark(bookmark) => bookmark.title_range.clone(),
}
}
fn tag_section_range(&self) -> Option<Range<usize>> {
match &self.partition {
Partition::Note(_) => None,
Partition::Todo(todo) => todo.tag_section_range.clone(),
Partition::Bookmark(bookmark) => bookmark.tag_section_range.clone(),
}
}
}
pub struct TagsIter<'a> {
doc: &'a NoteDocument,
token_spans: std::vec::IntoIter<Range<usize>>,
}
impl<'a> Iterator for TagsIter<'a> {
type Item = &'a [u8];
fn next(&mut self) -> Option<Self::Item> {
self.token_spans.next().map(|r| &self.doc.source[r])
}
}
pub struct TagsStrIter<'a> {
doc: &'a NoteDocument,
token_spans: std::vec::IntoIter<Range<usize>>,
}
impl<'a> Iterator for TagsStrIter<'a> {
type Item = Result<&'a str, std::str::Utf8Error>;
fn next(&mut self) -> Option<Self::Item> {
self.token_spans
.next()
.map(|r| std::str::from_utf8(&self.doc.source[r]))
}
}
pub struct BodyFragments<'a> {
source: &'a [u8],
ranges: std::vec::IntoIter<Range<usize>>,
}
impl<'a> Iterator for BodyFragments<'a> {
type Item = &'a [u8];
fn next(&mut self) -> Option<Self::Item> {
self.ranges.next().map(|r| &self.source[r])
}
}