| 1 | #[must_use] |
| 2 | pub const fn get_title_and_description(doc: &str) -> (&str, &str) { |
| 3 | let doc_bytes = trim_ascii(doc.as_bytes()); |
| 4 | |
| 5 | if !doc_bytes.is_empty() && doc_bytes[0] == b'#' { |
| 6 | let title_end_index = match strchr(doc_bytes, b'\n') { |
| 7 | Some(i) => i, |
| 8 | None => doc_bytes.len(), |
| 9 | }; |
| 10 | |
| 11 | let title = trim_ascii(trim_start(subslice(doc_bytes, 0, title_end_index), b'#')); |
| 12 | let description = trim_ascii(subslice(doc_bytes, title_end_index, doc_bytes.len())); |
| 13 | |
| 14 | (to_utf8(title), to_utf8(description)) |
| 15 | } else { |
| 16 | ("", to_utf8(doc_bytes)) |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | const fn strchr(bytes: &[u8], chr: u8) -> Option<usize> { |
| 21 | let len = bytes.len(); |
| 22 | let mut i = 0; |
| 23 | while i < len { |
| 24 | if bytes[i] == chr { |
| 25 | return Some(i); |
| 26 | } |
| 27 | i += 1; |
| 28 | } |
| 29 | None |
| 30 | } |
| 31 | |
| 32 | const fn subslice(mut bytes: &[u8], mut start: usize, end: usize) -> &[u8] { |
| 33 | let mut trim_end_count = bytes.len() - end; |
| 34 | if trim_end_count > 0 { |
| 35 | while let [rest @ .., _last] = bytes { |
| 36 | bytes = rest; |
| 37 | |
| 38 | trim_end_count -= 1; |
| 39 | if trim_end_count == 0 { |
| 40 | break; |
| 41 | } |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | if start > 0 { |
| 46 | while let [_first, rest @ ..] = bytes { |
| 47 | bytes = rest; |
| 48 | |
| 49 | start -= 1; |
| 50 | if start == 0 { |
| 51 | break; |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | bytes |
| 57 | } |
| 58 | |
| 59 | const fn to_utf8(bytes: &[u8]) -> &str { |
| 60 | match core::str::from_utf8(bytes) { |
| 61 | Ok(x) => x, |
| 62 | Err(_) => panic!("Invalid UTF-8"), |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | const fn trim_start(mut bytes: &[u8], chr: u8) -> &[u8] { |
| 67 | while let [first, rest @ ..] = bytes { |
| 68 | if *first == chr { |
| 69 | bytes = rest; |
| 70 | } else { |
| 71 | break; |
| 72 | } |
| 73 | } |
| 74 | bytes |
| 75 | } |
| 76 | |
| 77 | const fn trim_ascii(mut bytes: &[u8]) -> &[u8] { |
| 78 | while let [first, rest @ ..] = bytes { |
| 79 | if first.is_ascii_whitespace() { |
| 80 | bytes = rest; |
| 81 | } else { |
| 82 | break; |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | while let [rest @ .., last] = bytes { |
| 87 | if last.is_ascii_whitespace() { |
| 88 | bytes = rest; |
| 89 | } else { |
| 90 | break; |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | bytes |
| 95 | } |