1 //! The bridge from a token sequence to text.2 //!3 //! A vocabulary splits text into tokens, and a token boundary can fall inside4 //! a character: `é` is two bytes and a tokenizer may end a token after the5 //! first of them. The web layer and the JSON writer may only send whole UTF-8,6 //! so the pieces are held until the character is finished (chat.v1 rule 3).7 //!8 //! An invalid byte is never replaced with U+FFFD. It stays in the stream and9 //! `finish` reports it, because a reader cannot tell a replacement character10 //! that the model produced from one that the decoder invented.11 12 use std::fmt;13 14 /// An index into one vocabulary.15 ///16 /// A token carries no text of its own. Two models that share a token number do17 /// not share a token, so the vocabulary travels with the request and never18 /// with the token.19 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]20 pub struct Token(pub u32);21 22 /// Bytes that never became a whole character.23 ///24 /// A caller that ends a stream must know what it dropped. The bytes are given25 /// back so that an operator can see a broken vocabulary instead of a stream26 /// that merely stopped.27 #[derive(Clone, PartialEq, Eq, Debug)]28 pub struct Incomplete {29 /// The bytes that the stream still held.30 pub bytes: Vec<u8>,31 }32 33 impl fmt::Display for Incomplete {34 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {35 write!(f, "{} bytes are not a whole character", self.bytes.len())36 }37 }38 39 impl std::error::Error for Incomplete {}40 41 /// The decoder that turns token bytes into whole text.42 #[derive(Clone, Debug, Default)]43 pub struct TokenStream {44 /// Bytes that are not a character yet, or not UTF-8 at all.45 held: Vec<u8>,46 }47 48 impl TokenStream {49 /// An empty stream, at the start of a reply.50 pub fn new() -> TokenStream {51 TokenStream::default()52 }53 54 /// Takes the bytes of one token and returns the text that is now complete.55 ///56 /// A trailing partial character stays in the stream. A byte that cannot57 /// begin a character also stays, and no text follows it until `finish`.58 pub fn push(&mut self, bytes: &[u8]) -> String {59 self.held.extend_from_slice(bytes);60 let (text, rest) = split(&self.held);61 self.held = rest;62 text63 }64 65 /// The text that the stream still holds, or a refusal at the end of it.66 ///67 /// The stream is finished: what is left will never become a character.68 pub fn finish(&self) -> Result<String, Incomplete> {69 if self.held.is_empty() {70 Ok(String::new())71 } else {72 Err(Incomplete {73 bytes: self.held.clone(),74 })75 }76 }77 }78 79 /// The longest valid prefix of `bytes` as text, and the bytes after it.80 fn split(bytes: &[u8]) -> (String, Vec<u8>) {81 match std::str::from_utf8(bytes) {82 Ok(text) => (text.to_string(), Vec::new()),83 Err(why) => {84 let at = why.valid_up_to();85 match std::str::from_utf8(&bytes[..at]) {86 Ok(text) => (text.to_string(), bytes[at..].to_vec()),87 // `valid_up_to` is a boundary of a valid prefix, so this arm88 // cannot run. It holds every byte rather than panicking.89 Err(_) => (String::new(), bytes.to_vec()),90 }91 }92 }93 }